]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/channelmanager.rs
peel_payment_onion static fn in channelmanager
[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::BlockHeader;
21 use bitcoin::blockdata::transaction::Transaction;
22 use bitcoin::blockdata::constants::ChainHash;
23 use bitcoin::network::constants::Network;
24
25 use bitcoin::hashes::Hash;
26 use bitcoin::hashes::sha256::Hash as Sha256;
27 use bitcoin::hash_types::{BlockHash, Txid};
28
29 use bitcoin::secp256k1::{SecretKey,PublicKey};
30 use bitcoin::secp256k1::Secp256k1;
31 use bitcoin::{LockTime, secp256k1, Sequence};
32
33 use crate::blinded_path::BlindedPath;
34 use crate::blinded_path::payment::{PaymentConstraints, ReceiveTlvs};
35 use crate::chain;
36 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
37 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
38 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
39 use crate::chain::transaction::{OutPoint, TransactionData};
40 use crate::events;
41 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
42 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
43 // construct one themselves.
44 use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
45 use crate::ln::channel::{Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel};
46 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
47 #[cfg(any(feature = "_test_utils", test))]
48 use crate::ln::features::Bolt11InvoiceFeatures;
49 use crate::routing::gossip::NetworkGraph;
50 use crate::routing::router::{BlindedTail, DefaultRouter, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
51 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
52 use crate::ln::msgs;
53 use crate::ln::onion_utils;
54 use crate::ln::onion_utils::HTLCFailReason;
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::{Destination, OffersMessage, OffersMessageHandler, PendingOnionMessage, new_pending_onion_message};
67 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, WriteableEcdsaChannelSigner};
68 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
69 use crate::util::wakers::{Future, Notifier};
70 use crate::util::scid_utils::fake_scid;
71 use crate::util::string::UntrustedString;
72 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
73 use crate::util::logger::{Level, Logger};
74 use crate::util::errors::APIError;
75
76 use alloc::collections::{btree_map, BTreeMap};
77
78 use crate::io;
79 use crate::prelude::*;
80 use core::{cmp, mem};
81 use core::cell::RefCell;
82 use crate::io::Read;
83 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
84 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
85 use core::time::Duration;
86 use core::ops::Deref;
87
88 // Re-export this for use in the public API.
89 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
90 use crate::ln::script::ShutdownScript;
91
92 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
93 //
94 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
95 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
96 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
97 //
98 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
99 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
100 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
101 // before we forward it.
102 //
103 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
104 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
105 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
106 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
107 // our payment, which we can use to decode errors or inform the user that the payment was sent.
108
109 /// Routing info for an inbound HTLC onion.
110 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
111 pub enum PendingHTLCRouting {
112         /// A forwarded HTLC.
113         Forward {
114                 /// BOLT 4 onion packet.
115                 onion_packet: msgs::OnionPacket,
116                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
117                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
118                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
119         },
120         /// An HTLC paid to an invoice we generated.
121         Receive {
122                 /// Payment secret and total msat received.
123                 payment_data: msgs::FinalOnionHopData,
124                 /// See [`RecipientOnionFields::payment_metadata`] for more info.
125                 payment_metadata: Option<Vec<u8>>,
126                 /// Used to track when we should expire pending HTLCs that go unclaimed.
127                 incoming_cltv_expiry: u32,
128                 /// Optional shared secret for phantom node.
129                 phantom_shared_secret: Option<[u8; 32]>,
130                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
131                 custom_tlvs: Vec<(u64, Vec<u8>)>,
132         },
133         /// Incoming keysend (sender provided the preimage in a TLV).
134         ReceiveKeysend {
135                 /// This was added in 0.0.116 and will break deserialization on downgrades.
136                 payment_data: Option<msgs::FinalOnionHopData>,
137                 /// Preimage for this onion payment.
138                 payment_preimage: PaymentPreimage,
139                 /// See [`RecipientOnionFields::payment_metadata`] for more info.
140                 payment_metadata: Option<Vec<u8>>,
141                 /// CLTV expiry of the incoming HTLC.
142                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
143                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
144                 custom_tlvs: Vec<(u64, Vec<u8>)>,
145         },
146 }
147
148 /// Full details of an incoming HTLC, including routing info.
149 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
150 pub struct PendingHTLCInfo {
151         /// Further routing details based on whether the HTLC is being forwarded or received.
152         pub routing: PendingHTLCRouting,
153         /// Shared secret from the previous hop.
154         pub incoming_shared_secret: [u8; 32],
155         payment_hash: PaymentHash,
156         /// Amount received
157         pub incoming_amt_msat: Option<u64>, // Added in 0.0.113
158         /// Sender intended amount to forward or receive (actual amount received
159         /// may overshoot this in either case)
160         pub outgoing_amt_msat: u64,
161         /// Outgoing CLTV height.
162         pub outgoing_cltv_value: u32,
163         /// The fee being skimmed off the top of this HTLC. If this is a forward, it'll be the fee we are
164         /// skimming. If we're receiving this HTLC, it's the fee that our counterparty skimmed.
165         pub skimmed_fee_msat: Option<u64>,
166 }
167
168 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
169 pub(super) enum HTLCFailureMsg {
170         Relay(msgs::UpdateFailHTLC),
171         Malformed(msgs::UpdateFailMalformedHTLC),
172 }
173
174 /// Stores whether we can't forward an HTLC or relevant forwarding info
175 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
176 pub(super) enum PendingHTLCStatus {
177         Forward(PendingHTLCInfo),
178         Fail(HTLCFailureMsg),
179 }
180
181 pub(super) struct PendingAddHTLCInfo {
182         pub(super) forward_info: PendingHTLCInfo,
183
184         // These fields are produced in `forward_htlcs()` and consumed in
185         // `process_pending_htlc_forwards()` for constructing the
186         // `HTLCSource::PreviousHopData` for failed and forwarded
187         // HTLCs.
188         //
189         // Note that this may be an outbound SCID alias for the associated channel.
190         prev_short_channel_id: u64,
191         prev_htlc_id: u64,
192         prev_funding_outpoint: OutPoint,
193         prev_user_channel_id: u128,
194 }
195
196 pub(super) enum HTLCForwardInfo {
197         AddHTLC(PendingAddHTLCInfo),
198         FailHTLC {
199                 htlc_id: u64,
200                 err_packet: msgs::OnionErrorPacket,
201         },
202 }
203
204 /// Tracks the inbound corresponding to an outbound HTLC
205 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
206 pub(crate) struct HTLCPreviousHopData {
207         // Note that this may be an outbound SCID alias for the associated channel.
208         short_channel_id: u64,
209         user_channel_id: Option<u128>,
210         htlc_id: u64,
211         incoming_packet_shared_secret: [u8; 32],
212         phantom_shared_secret: Option<[u8; 32]>,
213
214         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
215         // channel with a preimage provided by the forward channel.
216         outpoint: OutPoint,
217 }
218
219 enum OnionPayload {
220         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
221         Invoice {
222                 /// This is only here for backwards-compatibility in serialization, in the future it can be
223                 /// removed, breaking clients running 0.0.106 and earlier.
224                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
225         },
226         /// Contains the payer-provided preimage.
227         Spontaneous(PaymentPreimage),
228 }
229
230 /// HTLCs that are to us and can be failed/claimed by the user
231 struct ClaimableHTLC {
232         prev_hop: HTLCPreviousHopData,
233         cltv_expiry: u32,
234         /// The amount (in msats) of this MPP part
235         value: u64,
236         /// The amount (in msats) that the sender intended to be sent in this MPP
237         /// part (used for validating total MPP amount)
238         sender_intended_value: u64,
239         onion_payload: OnionPayload,
240         timer_ticks: u8,
241         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
242         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
243         total_value_received: Option<u64>,
244         /// The sender intended sum total of all MPP parts specified in the onion
245         total_msat: u64,
246         /// The extra fee our counterparty skimmed off the top of this HTLC.
247         counterparty_skimmed_fee_msat: Option<u64>,
248 }
249
250 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
251         fn from(val: &ClaimableHTLC) -> Self {
252                 events::ClaimedHTLC {
253                         channel_id: val.prev_hop.outpoint.to_channel_id(),
254                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
255                         cltv_expiry: val.cltv_expiry,
256                         value_msat: val.value,
257                 }
258         }
259 }
260
261 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
262 /// a payment and ensure idempotency in LDK.
263 ///
264 /// This is not exported to bindings users as we just use [u8; 32] directly
265 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
266 pub struct PaymentId(pub [u8; Self::LENGTH]);
267
268 impl PaymentId {
269         /// Number of bytes in the id.
270         pub const LENGTH: usize = 32;
271 }
272
273 impl Writeable for PaymentId {
274         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
275                 self.0.write(w)
276         }
277 }
278
279 impl Readable for PaymentId {
280         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
281                 let buf: [u8; 32] = Readable::read(r)?;
282                 Ok(PaymentId(buf))
283         }
284 }
285
286 impl core::fmt::Display for PaymentId {
287         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
288                 crate::util::logger::DebugBytes(&self.0).fmt(f)
289         }
290 }
291
292 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
293 ///
294 /// This is not exported to bindings users as we just use [u8; 32] directly
295 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
296 pub struct InterceptId(pub [u8; 32]);
297
298 impl Writeable for InterceptId {
299         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
300                 self.0.write(w)
301         }
302 }
303
304 impl Readable for InterceptId {
305         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
306                 let buf: [u8; 32] = Readable::read(r)?;
307                 Ok(InterceptId(buf))
308         }
309 }
310
311 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
312 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
313 pub(crate) enum SentHTLCId {
314         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
315         OutboundRoute { session_priv: SecretKey },
316 }
317 impl SentHTLCId {
318         pub(crate) fn from_source(source: &HTLCSource) -> Self {
319                 match source {
320                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
321                                 short_channel_id: hop_data.short_channel_id,
322                                 htlc_id: hop_data.htlc_id,
323                         },
324                         HTLCSource::OutboundRoute { session_priv, .. } =>
325                                 Self::OutboundRoute { session_priv: *session_priv },
326                 }
327         }
328 }
329 impl_writeable_tlv_based_enum!(SentHTLCId,
330         (0, PreviousHopData) => {
331                 (0, short_channel_id, required),
332                 (2, htlc_id, required),
333         },
334         (2, OutboundRoute) => {
335                 (0, session_priv, required),
336         };
337 );
338
339
340 /// Tracks the inbound corresponding to an outbound HTLC
341 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
342 #[derive(Clone, Debug, PartialEq, Eq)]
343 pub(crate) enum HTLCSource {
344         PreviousHopData(HTLCPreviousHopData),
345         OutboundRoute {
346                 path: Path,
347                 session_priv: SecretKey,
348                 /// Technically we can recalculate this from the route, but we cache it here to avoid
349                 /// doing a double-pass on route when we get a failure back
350                 first_hop_htlc_msat: u64,
351                 payment_id: PaymentId,
352         },
353 }
354 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
355 impl core::hash::Hash for HTLCSource {
356         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
357                 match self {
358                         HTLCSource::PreviousHopData(prev_hop_data) => {
359                                 0u8.hash(hasher);
360                                 prev_hop_data.hash(hasher);
361                         },
362                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
363                                 1u8.hash(hasher);
364                                 path.hash(hasher);
365                                 session_priv[..].hash(hasher);
366                                 payment_id.hash(hasher);
367                                 first_hop_htlc_msat.hash(hasher);
368                         },
369                 }
370         }
371 }
372 impl HTLCSource {
373         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
374         #[cfg(test)]
375         pub fn dummy() -> Self {
376                 HTLCSource::OutboundRoute {
377                         path: Path { hops: Vec::new(), blinded_tail: None },
378                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
379                         first_hop_htlc_msat: 0,
380                         payment_id: PaymentId([2; 32]),
381                 }
382         }
383
384         #[cfg(debug_assertions)]
385         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
386         /// transaction. Useful to ensure different datastructures match up.
387         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
388                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
389                         *first_hop_htlc_msat == htlc.amount_msat
390                 } else {
391                         // There's nothing we can check for forwarded HTLCs
392                         true
393                 }
394         }
395 }
396
397 /// Invalid inbound onion payment.
398 pub struct InboundOnionErr {
399         err_code: u16,
400         err_data: Vec<u8>,
401         msg: &'static str,
402 }
403
404 /// This enum is used to specify which error data to send to peers when failing back an HTLC
405 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
406 ///
407 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
408 #[derive(Clone, Copy)]
409 pub enum FailureCode {
410         /// We had a temporary error processing the payment. Useful if no other error codes fit
411         /// and you want to indicate that the payer may want to retry.
412         TemporaryNodeFailure,
413         /// We have a required feature which was not in this onion. For example, you may require
414         /// some additional metadata that was not provided with this payment.
415         RequiredNodeFeatureMissing,
416         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
417         /// the HTLC is too close to the current block height for safe handling.
418         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
419         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
420         IncorrectOrUnknownPaymentDetails,
421         /// We failed to process the payload after the onion was decrypted. You may wish to
422         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
423         ///
424         /// If available, the tuple data may include the type number and byte offset in the
425         /// decrypted byte stream where the failure occurred.
426         InvalidOnionPayload(Option<(u64, u16)>),
427 }
428
429 impl Into<u16> for FailureCode {
430     fn into(self) -> u16 {
431                 match self {
432                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
433                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
434                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
435                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
436                 }
437         }
438 }
439
440 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
441 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
442 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
443 /// peer_state lock. We then return the set of things that need to be done outside the lock in
444 /// this struct and call handle_error!() on it.
445
446 struct MsgHandleErrInternal {
447         err: msgs::LightningError,
448         chan_id: Option<(ChannelId, u128)>, // If Some a channel of ours has been closed
449         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
450         channel_capacity: Option<u64>,
451 }
452 impl MsgHandleErrInternal {
453         #[inline]
454         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
455                 Self {
456                         err: LightningError {
457                                 err: err.clone(),
458                                 action: msgs::ErrorAction::SendErrorMessage {
459                                         msg: msgs::ErrorMessage {
460                                                 channel_id,
461                                                 data: err
462                                         },
463                                 },
464                         },
465                         chan_id: None,
466                         shutdown_finish: None,
467                         channel_capacity: None,
468                 }
469         }
470         #[inline]
471         fn from_no_close(err: msgs::LightningError) -> Self {
472                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
473         }
474         #[inline]
475         fn from_finish_shutdown(err: String, channel_id: ChannelId, user_channel_id: u128, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>, channel_capacity: u64) -> Self {
476                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
477                 let action = if shutdown_res.monitor_update.is_some() {
478                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
479                         // should disconnect our peer such that we force them to broadcast their latest
480                         // commitment upon reconnecting.
481                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
482                 } else {
483                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
484                 };
485                 Self {
486                         err: LightningError { err, action },
487                         chan_id: Some((channel_id, user_channel_id)),
488                         shutdown_finish: Some((shutdown_res, channel_update)),
489                         channel_capacity: Some(channel_capacity)
490                 }
491         }
492         #[inline]
493         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
494                 Self {
495                         err: match err {
496                                 ChannelError::Warn(msg) =>  LightningError {
497                                         err: msg.clone(),
498                                         action: msgs::ErrorAction::SendWarningMessage {
499                                                 msg: msgs::WarningMessage {
500                                                         channel_id,
501                                                         data: msg
502                                                 },
503                                                 log_level: Level::Warn,
504                                         },
505                                 },
506                                 ChannelError::Ignore(msg) => LightningError {
507                                         err: msg,
508                                         action: msgs::ErrorAction::IgnoreError,
509                                 },
510                                 ChannelError::Close(msg) => LightningError {
511                                         err: msg.clone(),
512                                         action: msgs::ErrorAction::SendErrorMessage {
513                                                 msg: msgs::ErrorMessage {
514                                                         channel_id,
515                                                         data: msg
516                                                 },
517                                         },
518                                 },
519                         },
520                         chan_id: None,
521                         shutdown_finish: None,
522                         channel_capacity: None,
523                 }
524         }
525
526         fn closes_channel(&self) -> bool {
527                 self.chan_id.is_some()
528         }
529 }
530
531 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
532 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
533 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
534 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
535 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
536
537 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
538 /// be sent in the order they appear in the return value, however sometimes the order needs to be
539 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
540 /// they were originally sent). In those cases, this enum is also returned.
541 #[derive(Clone, PartialEq)]
542 pub(super) enum RAACommitmentOrder {
543         /// Send the CommitmentUpdate messages first
544         CommitmentFirst,
545         /// Send the RevokeAndACK message first
546         RevokeAndACKFirst,
547 }
548
549 /// Information about a payment which is currently being claimed.
550 struct ClaimingPayment {
551         amount_msat: u64,
552         payment_purpose: events::PaymentPurpose,
553         receiver_node_id: PublicKey,
554         htlcs: Vec<events::ClaimedHTLC>,
555         sender_intended_value: Option<u64>,
556 }
557 impl_writeable_tlv_based!(ClaimingPayment, {
558         (0, amount_msat, required),
559         (2, payment_purpose, required),
560         (4, receiver_node_id, required),
561         (5, htlcs, optional_vec),
562         (7, sender_intended_value, option),
563 });
564
565 struct ClaimablePayment {
566         purpose: events::PaymentPurpose,
567         onion_fields: Option<RecipientOnionFields>,
568         htlcs: Vec<ClaimableHTLC>,
569 }
570
571 /// Information about claimable or being-claimed payments
572 struct ClaimablePayments {
573         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
574         /// failed/claimed by the user.
575         ///
576         /// Note that, no consistency guarantees are made about the channels given here actually
577         /// existing anymore by the time you go to read them!
578         ///
579         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
580         /// we don't get a duplicate payment.
581         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
582
583         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
584         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
585         /// as an [`events::Event::PaymentClaimed`].
586         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
587 }
588
589 /// Events which we process internally but cannot be processed immediately at the generation site
590 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
591 /// running normally, and specifically must be processed before any other non-background
592 /// [`ChannelMonitorUpdate`]s are applied.
593 #[derive(Debug)]
594 enum BackgroundEvent {
595         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
596         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
597         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
598         /// channel has been force-closed we do not need the counterparty node_id.
599         ///
600         /// Note that any such events are lost on shutdown, so in general they must be updates which
601         /// are regenerated on startup.
602         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
603         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
604         /// channel to continue normal operation.
605         ///
606         /// In general this should be used rather than
607         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
608         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
609         /// error the other variant is acceptable.
610         ///
611         /// Note that any such events are lost on shutdown, so in general they must be updates which
612         /// are regenerated on startup.
613         MonitorUpdateRegeneratedOnStartup {
614                 counterparty_node_id: PublicKey,
615                 funding_txo: OutPoint,
616                 update: ChannelMonitorUpdate
617         },
618         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
619         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
620         /// on a channel.
621         MonitorUpdatesComplete {
622                 counterparty_node_id: PublicKey,
623                 channel_id: ChannelId,
624         },
625 }
626
627 #[derive(Debug)]
628 pub(crate) enum MonitorUpdateCompletionAction {
629         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
630         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
631         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
632         /// event can be generated.
633         PaymentClaimed { payment_hash: PaymentHash },
634         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
635         /// operation of another channel.
636         ///
637         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
638         /// from completing a monitor update which removes the payment preimage until the inbound edge
639         /// completes a monitor update containing the payment preimage. In that case, after the inbound
640         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
641         /// outbound edge.
642         EmitEventAndFreeOtherChannel {
643                 event: events::Event,
644                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
645         },
646         /// Indicates we should immediately resume the operation of another channel, unless there is
647         /// some other reason why the channel is blocked. In practice this simply means immediately
648         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
649         ///
650         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
651         /// from completing a monitor update which removes the payment preimage until the inbound edge
652         /// completes a monitor update containing the payment preimage. However, we use this variant
653         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
654         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
655         ///
656         /// This variant should thus never be written to disk, as it is processed inline rather than
657         /// stored for later processing.
658         FreeOtherChannelImmediately {
659                 downstream_counterparty_node_id: PublicKey,
660                 downstream_funding_outpoint: OutPoint,
661                 blocking_action: RAAMonitorUpdateBlockingAction,
662         },
663 }
664
665 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
666         (0, PaymentClaimed) => { (0, payment_hash, required) },
667         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
668         // *immediately*. However, for simplicity we implement read/write here.
669         (1, FreeOtherChannelImmediately) => {
670                 (0, downstream_counterparty_node_id, required),
671                 (2, downstream_funding_outpoint, required),
672                 (4, blocking_action, required),
673         },
674         (2, EmitEventAndFreeOtherChannel) => {
675                 (0, event, upgradable_required),
676                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
677                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
678                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
679                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
680                 // downgrades to prior versions.
681                 (1, downstream_counterparty_and_funding_outpoint, option),
682         },
683 );
684
685 #[derive(Clone, Debug, PartialEq, Eq)]
686 pub(crate) enum EventCompletionAction {
687         ReleaseRAAChannelMonitorUpdate {
688                 counterparty_node_id: PublicKey,
689                 channel_funding_outpoint: OutPoint,
690         },
691 }
692 impl_writeable_tlv_based_enum!(EventCompletionAction,
693         (0, ReleaseRAAChannelMonitorUpdate) => {
694                 (0, channel_funding_outpoint, required),
695                 (2, counterparty_node_id, required),
696         };
697 );
698
699 #[derive(Clone, PartialEq, Eq, Debug)]
700 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
701 /// the blocked action here. See enum variants for more info.
702 pub(crate) enum RAAMonitorUpdateBlockingAction {
703         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
704         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
705         /// durably to disk.
706         ForwardedPaymentInboundClaim {
707                 /// The upstream channel ID (i.e. the inbound edge).
708                 channel_id: ChannelId,
709                 /// The HTLC ID on the inbound edge.
710                 htlc_id: u64,
711         },
712 }
713
714 impl RAAMonitorUpdateBlockingAction {
715         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
716                 Self::ForwardedPaymentInboundClaim {
717                         channel_id: prev_hop.outpoint.to_channel_id(),
718                         htlc_id: prev_hop.htlc_id,
719                 }
720         }
721 }
722
723 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
724         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
725 ;);
726
727
728 /// State we hold per-peer.
729 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
730         /// `channel_id` -> `ChannelPhase`
731         ///
732         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
733         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
734         /// `temporary_channel_id` -> `InboundChannelRequest`.
735         ///
736         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
737         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
738         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
739         /// the channel is rejected, then the entry is simply removed.
740         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
741         /// The latest `InitFeatures` we heard from the peer.
742         latest_features: InitFeatures,
743         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
744         /// for broadcast messages, where ordering isn't as strict).
745         pub(super) pending_msg_events: Vec<MessageSendEvent>,
746         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
747         /// user but which have not yet completed.
748         ///
749         /// Note that the channel may no longer exist. For example if the channel was closed but we
750         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
751         /// for a missing channel.
752         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
753         /// Map from a specific channel to some action(s) that should be taken when all pending
754         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
755         ///
756         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
757         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
758         /// channels with a peer this will just be one allocation and will amount to a linear list of
759         /// channels to walk, avoiding the whole hashing rigmarole.
760         ///
761         /// Note that the channel may no longer exist. For example, if a channel was closed but we
762         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
763         /// for a missing channel. While a malicious peer could construct a second channel with the
764         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
765         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
766         /// duplicates do not occur, so such channels should fail without a monitor update completing.
767         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
768         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
769         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
770         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
771         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
772         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
773         /// The peer is currently connected (i.e. we've seen a
774         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
775         /// [`ChannelMessageHandler::peer_disconnected`].
776         is_connected: bool,
777 }
778
779 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
780         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
781         /// If true is passed for `require_disconnected`, the function will return false if we haven't
782         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
783         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
784                 if require_disconnected && self.is_connected {
785                         return false
786                 }
787                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
788                         && self.monitor_update_blocked_actions.is_empty()
789                         && self.in_flight_monitor_updates.is_empty()
790         }
791
792         // Returns a count of all channels we have with this peer, including unfunded channels.
793         fn total_channel_count(&self) -> usize {
794                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
795         }
796
797         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
798         fn has_channel(&self, channel_id: &ChannelId) -> bool {
799                 self.channel_by_id.contains_key(channel_id) ||
800                         self.inbound_channel_request_by_id.contains_key(channel_id)
801         }
802 }
803
804 /// A not-yet-accepted inbound (from counterparty) channel. Once
805 /// accepted, the parameters will be used to construct a channel.
806 pub(super) struct InboundChannelRequest {
807         /// The original OpenChannel message.
808         pub open_channel_msg: msgs::OpenChannel,
809         /// The number of ticks remaining before the request expires.
810         pub ticks_remaining: i32,
811 }
812
813 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
814 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
815 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
816
817 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
818 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
819 ///
820 /// For users who don't want to bother doing their own payment preimage storage, we also store that
821 /// here.
822 ///
823 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
824 /// and instead encoding it in the payment secret.
825 struct PendingInboundPayment {
826         /// The payment secret that the sender must use for us to accept this payment
827         payment_secret: PaymentSecret,
828         /// Time at which this HTLC expires - blocks with a header time above this value will result in
829         /// this payment being removed.
830         expiry_time: u64,
831         /// Arbitrary identifier the user specifies (or not)
832         user_payment_id: u64,
833         // Other required attributes of the payment, optionally enforced:
834         payment_preimage: Option<PaymentPreimage>,
835         min_value_msat: Option<u64>,
836 }
837
838 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
839 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
840 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
841 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
842 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
843 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
844 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
845 /// of [`KeysManager`] and [`DefaultRouter`].
846 ///
847 /// This is not exported to bindings users as type aliases aren't supported in most languages.
848 #[cfg(not(c_bindings))]
849 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
850         Arc<M>,
851         Arc<T>,
852         Arc<KeysManager>,
853         Arc<KeysManager>,
854         Arc<KeysManager>,
855         Arc<F>,
856         Arc<DefaultRouter<
857                 Arc<NetworkGraph<Arc<L>>>,
858                 Arc<L>,
859                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
860                 ProbabilisticScoringFeeParameters,
861                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
862         >>,
863         Arc<L>
864 >;
865
866 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
867 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
868 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
869 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
870 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
871 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
872 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
873 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
874 /// of [`KeysManager`] and [`DefaultRouter`].
875 ///
876 /// This is not exported to bindings users as type aliases aren't supported in most languages.
877 #[cfg(not(c_bindings))]
878 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
879         ChannelManager<
880                 &'a M,
881                 &'b T,
882                 &'c KeysManager,
883                 &'c KeysManager,
884                 &'c KeysManager,
885                 &'d F,
886                 &'e DefaultRouter<
887                         &'f NetworkGraph<&'g L>,
888                         &'g L,
889                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
890                         ProbabilisticScoringFeeParameters,
891                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
892                 >,
893                 &'g L
894         >;
895
896 /// A trivial trait which describes any [`ChannelManager`].
897 ///
898 /// This is not exported to bindings users as general cover traits aren't useful in other
899 /// languages.
900 pub trait AChannelManager {
901         /// A type implementing [`chain::Watch`].
902         type Watch: chain::Watch<Self::Signer> + ?Sized;
903         /// A type that may be dereferenced to [`Self::Watch`].
904         type M: Deref<Target = Self::Watch>;
905         /// A type implementing [`BroadcasterInterface`].
906         type Broadcaster: BroadcasterInterface + ?Sized;
907         /// A type that may be dereferenced to [`Self::Broadcaster`].
908         type T: Deref<Target = Self::Broadcaster>;
909         /// A type implementing [`EntropySource`].
910         type EntropySource: EntropySource + ?Sized;
911         /// A type that may be dereferenced to [`Self::EntropySource`].
912         type ES: Deref<Target = Self::EntropySource>;
913         /// A type implementing [`NodeSigner`].
914         type NodeSigner: NodeSigner + ?Sized;
915         /// A type that may be dereferenced to [`Self::NodeSigner`].
916         type NS: Deref<Target = Self::NodeSigner>;
917         /// A type implementing [`WriteableEcdsaChannelSigner`].
918         type Signer: WriteableEcdsaChannelSigner + Sized;
919         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
920         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
921         /// A type that may be dereferenced to [`Self::SignerProvider`].
922         type SP: Deref<Target = Self::SignerProvider>;
923         /// A type implementing [`FeeEstimator`].
924         type FeeEstimator: FeeEstimator + ?Sized;
925         /// A type that may be dereferenced to [`Self::FeeEstimator`].
926         type F: Deref<Target = Self::FeeEstimator>;
927         /// A type implementing [`Router`].
928         type Router: Router + ?Sized;
929         /// A type that may be dereferenced to [`Self::Router`].
930         type R: Deref<Target = Self::Router>;
931         /// A type implementing [`Logger`].
932         type Logger: Logger + ?Sized;
933         /// A type that may be dereferenced to [`Self::Logger`].
934         type L: Deref<Target = Self::Logger>;
935         /// Returns a reference to the actual [`ChannelManager`] object.
936         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
937 }
938
939 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
940 for ChannelManager<M, T, ES, NS, SP, F, R, L>
941 where
942         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
943         T::Target: BroadcasterInterface,
944         ES::Target: EntropySource,
945         NS::Target: NodeSigner,
946         SP::Target: SignerProvider,
947         F::Target: FeeEstimator,
948         R::Target: Router,
949         L::Target: Logger,
950 {
951         type Watch = M::Target;
952         type M = M;
953         type Broadcaster = T::Target;
954         type T = T;
955         type EntropySource = ES::Target;
956         type ES = ES;
957         type NodeSigner = NS::Target;
958         type NS = NS;
959         type Signer = <SP::Target as SignerProvider>::Signer;
960         type SignerProvider = SP::Target;
961         type SP = SP;
962         type FeeEstimator = F::Target;
963         type F = F;
964         type Router = R::Target;
965         type R = R;
966         type Logger = L::Target;
967         type L = L;
968         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
969 }
970
971 /// Manager which keeps track of a number of channels and sends messages to the appropriate
972 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
973 ///
974 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
975 /// to individual Channels.
976 ///
977 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
978 /// all peers during write/read (though does not modify this instance, only the instance being
979 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
980 /// called [`funding_transaction_generated`] for outbound channels) being closed.
981 ///
982 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
983 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
984 /// [`ChannelMonitorUpdate`] before returning from
985 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
986 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
987 /// `ChannelManager` operations from occurring during the serialization process). If the
988 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
989 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
990 /// will be lost (modulo on-chain transaction fees).
991 ///
992 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
993 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
994 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
995 ///
996 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
997 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
998 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
999 /// offline for a full minute. In order to track this, you must call
1000 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1001 ///
1002 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1003 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1004 /// not have a channel with being unable to connect to us or open new channels with us if we have
1005 /// many peers with unfunded channels.
1006 ///
1007 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1008 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1009 /// never limited. Please ensure you limit the count of such channels yourself.
1010 ///
1011 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1012 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1013 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1014 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1015 /// you're using lightning-net-tokio.
1016 ///
1017 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1018 /// [`funding_created`]: msgs::FundingCreated
1019 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1020 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1021 /// [`update_channel`]: chain::Watch::update_channel
1022 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1023 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1024 /// [`read`]: ReadableArgs::read
1025 //
1026 // Lock order:
1027 // The tree structure below illustrates the lock order requirements for the different locks of the
1028 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1029 // and should then be taken in the order of the lowest to the highest level in the tree.
1030 // Note that locks on different branches shall not be taken at the same time, as doing so will
1031 // create a new lock order for those specific locks in the order they were taken.
1032 //
1033 // Lock order tree:
1034 //
1035 // `pending_offers_messages`
1036 //
1037 // `total_consistency_lock`
1038 //  |
1039 //  |__`forward_htlcs`
1040 //  |   |
1041 //  |   |__`pending_intercepted_htlcs`
1042 //  |
1043 //  |__`per_peer_state`
1044 //      |
1045 //      |__`pending_inbound_payments`
1046 //          |
1047 //          |__`claimable_payments`
1048 //          |
1049 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1050 //              |
1051 //              |__`peer_state`
1052 //                  |
1053 //                  |__`id_to_peer`
1054 //                  |
1055 //                  |__`short_to_chan_info`
1056 //                  |
1057 //                  |__`outbound_scid_aliases`
1058 //                  |
1059 //                  |__`best_block`
1060 //                  |
1061 //                  |__`pending_events`
1062 //                      |
1063 //                      |__`pending_background_events`
1064 //
1065 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1066 where
1067         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1068         T::Target: BroadcasterInterface,
1069         ES::Target: EntropySource,
1070         NS::Target: NodeSigner,
1071         SP::Target: SignerProvider,
1072         F::Target: FeeEstimator,
1073         R::Target: Router,
1074         L::Target: Logger,
1075 {
1076         default_configuration: UserConfig,
1077         chain_hash: ChainHash,
1078         fee_estimator: LowerBoundedFeeEstimator<F>,
1079         chain_monitor: M,
1080         tx_broadcaster: T,
1081         #[allow(unused)]
1082         router: R,
1083
1084         /// See `ChannelManager` struct-level documentation for lock order requirements.
1085         #[cfg(test)]
1086         pub(super) best_block: RwLock<BestBlock>,
1087         #[cfg(not(test))]
1088         best_block: RwLock<BestBlock>,
1089         secp_ctx: Secp256k1<secp256k1::All>,
1090
1091         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1092         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1093         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1094         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1095         ///
1096         /// See `ChannelManager` struct-level documentation for lock order requirements.
1097         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1098
1099         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1100         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1101         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1102         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1103         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1104         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1105         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1106         /// after reloading from disk while replaying blocks against ChannelMonitors.
1107         ///
1108         /// See `PendingOutboundPayment` documentation for more info.
1109         ///
1110         /// See `ChannelManager` struct-level documentation for lock order requirements.
1111         pending_outbound_payments: OutboundPayments,
1112
1113         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1114         ///
1115         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1116         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1117         /// and via the classic SCID.
1118         ///
1119         /// Note that no consistency guarantees are made about the existence of a channel with the
1120         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1121         ///
1122         /// See `ChannelManager` struct-level documentation for lock order requirements.
1123         #[cfg(test)]
1124         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1125         #[cfg(not(test))]
1126         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1127         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1128         /// until the user tells us what we should do with them.
1129         ///
1130         /// See `ChannelManager` struct-level documentation for lock order requirements.
1131         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1132
1133         /// The sets of payments which are claimable or currently being claimed. See
1134         /// [`ClaimablePayments`]' individual field docs for more info.
1135         ///
1136         /// See `ChannelManager` struct-level documentation for lock order requirements.
1137         claimable_payments: Mutex<ClaimablePayments>,
1138
1139         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1140         /// and some closed channels which reached a usable state prior to being closed. This is used
1141         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1142         /// active channel list on load.
1143         ///
1144         /// See `ChannelManager` struct-level documentation for lock order requirements.
1145         outbound_scid_aliases: Mutex<HashSet<u64>>,
1146
1147         /// `channel_id` -> `counterparty_node_id`.
1148         ///
1149         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1150         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1151         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1152         ///
1153         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1154         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1155         /// the handling of the events.
1156         ///
1157         /// Note that no consistency guarantees are made about the existence of a peer with the
1158         /// `counterparty_node_id` in our other maps.
1159         ///
1160         /// TODO:
1161         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1162         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1163         /// would break backwards compatability.
1164         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1165         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1166         /// required to access the channel with the `counterparty_node_id`.
1167         ///
1168         /// See `ChannelManager` struct-level documentation for lock order requirements.
1169         id_to_peer: Mutex<HashMap<ChannelId, PublicKey>>,
1170
1171         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1172         ///
1173         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1174         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1175         /// confirmation depth.
1176         ///
1177         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1178         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1179         /// channel with the `channel_id` in our other maps.
1180         ///
1181         /// See `ChannelManager` struct-level documentation for lock order requirements.
1182         #[cfg(test)]
1183         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1184         #[cfg(not(test))]
1185         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1186
1187         our_network_pubkey: PublicKey,
1188
1189         inbound_payment_key: inbound_payment::ExpandedKey,
1190
1191         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1192         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1193         /// we encrypt the namespace identifier using these bytes.
1194         ///
1195         /// [fake scids]: crate::util::scid_utils::fake_scid
1196         fake_scid_rand_bytes: [u8; 32],
1197
1198         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1199         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1200         /// keeping additional state.
1201         probing_cookie_secret: [u8; 32],
1202
1203         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1204         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1205         /// very far in the past, and can only ever be up to two hours in the future.
1206         highest_seen_timestamp: AtomicUsize,
1207
1208         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1209         /// basis, as well as the peer's latest features.
1210         ///
1211         /// If we are connected to a peer we always at least have an entry here, even if no channels
1212         /// are currently open with that peer.
1213         ///
1214         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1215         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1216         /// channels.
1217         ///
1218         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1219         ///
1220         /// See `ChannelManager` struct-level documentation for lock order requirements.
1221         #[cfg(not(any(test, feature = "_test_utils")))]
1222         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1223         #[cfg(any(test, feature = "_test_utils"))]
1224         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1225
1226         /// The set of events which we need to give to the user to handle. In some cases an event may
1227         /// require some further action after the user handles it (currently only blocking a monitor
1228         /// update from being handed to the user to ensure the included changes to the channel state
1229         /// are handled by the user before they're persisted durably to disk). In that case, the second
1230         /// element in the tuple is set to `Some` with further details of the action.
1231         ///
1232         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1233         /// could be in the middle of being processed without the direct mutex held.
1234         ///
1235         /// See `ChannelManager` struct-level documentation for lock order requirements.
1236         #[cfg(not(any(test, feature = "_test_utils")))]
1237         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1238         #[cfg(any(test, feature = "_test_utils"))]
1239         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1240
1241         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1242         pending_events_processor: AtomicBool,
1243
1244         /// If we are running during init (either directly during the deserialization method or in
1245         /// block connection methods which run after deserialization but before normal operation) we
1246         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1247         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1248         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1249         ///
1250         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1251         ///
1252         /// See `ChannelManager` struct-level documentation for lock order requirements.
1253         ///
1254         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1255         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1256         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1257         /// Essentially just when we're serializing ourselves out.
1258         /// Taken first everywhere where we are making changes before any other locks.
1259         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1260         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1261         /// Notifier the lock contains sends out a notification when the lock is released.
1262         total_consistency_lock: RwLock<()>,
1263         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1264         /// received and the monitor has been persisted.
1265         ///
1266         /// This information does not need to be persisted as funding nodes can forget
1267         /// unfunded channels upon disconnection.
1268         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1269
1270         background_events_processed_since_startup: AtomicBool,
1271
1272         event_persist_notifier: Notifier,
1273         needs_persist_flag: AtomicBool,
1274
1275         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1276
1277         entropy_source: ES,
1278         node_signer: NS,
1279         signer_provider: SP,
1280
1281         logger: L,
1282 }
1283
1284 /// Chain-related parameters used to construct a new `ChannelManager`.
1285 ///
1286 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1287 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1288 /// are not needed when deserializing a previously constructed `ChannelManager`.
1289 #[derive(Clone, Copy, PartialEq)]
1290 pub struct ChainParameters {
1291         /// The network for determining the `chain_hash` in Lightning messages.
1292         pub network: Network,
1293
1294         /// The hash and height of the latest block successfully connected.
1295         ///
1296         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1297         pub best_block: BestBlock,
1298 }
1299
1300 #[derive(Copy, Clone, PartialEq)]
1301 #[must_use]
1302 enum NotifyOption {
1303         DoPersist,
1304         SkipPersistHandleEvents,
1305         SkipPersistNoEvents,
1306 }
1307
1308 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1309 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1310 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1311 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1312 /// sending the aforementioned notification (since the lock being released indicates that the
1313 /// updates are ready for persistence).
1314 ///
1315 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1316 /// notify or not based on whether relevant changes have been made, providing a closure to
1317 /// `optionally_notify` which returns a `NotifyOption`.
1318 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1319         event_persist_notifier: &'a Notifier,
1320         needs_persist_flag: &'a AtomicBool,
1321         should_persist: F,
1322         // We hold onto this result so the lock doesn't get released immediately.
1323         _read_guard: RwLockReadGuard<'a, ()>,
1324 }
1325
1326 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1327         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1328         /// events to handle.
1329         ///
1330         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1331         /// other cases where losing the changes on restart may result in a force-close or otherwise
1332         /// isn't ideal.
1333         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1334                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1335         }
1336
1337         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1338         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1339                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1340                 let force_notify = cm.get_cm().process_background_events();
1341
1342                 PersistenceNotifierGuard {
1343                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1344                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1345                         should_persist: move || {
1346                                 // Pick the "most" action between `persist_check` and the background events
1347                                 // processing and return that.
1348                                 let notify = persist_check();
1349                                 match (notify, force_notify) {
1350                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1351                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1352                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1353                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1354                                         _ => NotifyOption::SkipPersistNoEvents,
1355                                 }
1356                         },
1357                         _read_guard: read_guard,
1358                 }
1359         }
1360
1361         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1362         /// [`ChannelManager::process_background_events`] MUST be called first (or
1363         /// [`Self::optionally_notify`] used).
1364         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1365         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1366                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1367
1368                 PersistenceNotifierGuard {
1369                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1370                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1371                         should_persist: persist_check,
1372                         _read_guard: read_guard,
1373                 }
1374         }
1375 }
1376
1377 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1378         fn drop(&mut self) {
1379                 match (self.should_persist)() {
1380                         NotifyOption::DoPersist => {
1381                                 self.needs_persist_flag.store(true, Ordering::Release);
1382                                 self.event_persist_notifier.notify()
1383                         },
1384                         NotifyOption::SkipPersistHandleEvents =>
1385                                 self.event_persist_notifier.notify(),
1386                         NotifyOption::SkipPersistNoEvents => {},
1387                 }
1388         }
1389 }
1390
1391 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1392 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1393 ///
1394 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1395 ///
1396 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1397 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1398 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1399 /// the maximum required amount in lnd as of March 2021.
1400 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1401
1402 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1403 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1404 ///
1405 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1406 ///
1407 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1408 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1409 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1410 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1411 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1412 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1413 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1414 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1415 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1416 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1417 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1418 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1419 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1420
1421 /// Minimum CLTV difference between the current block height and received inbound payments.
1422 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1423 /// this value.
1424 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1425 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1426 // a payment was being routed, so we add an extra block to be safe.
1427 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1428
1429 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1430 // ie that if the next-hop peer fails the HTLC within
1431 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1432 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1433 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1434 // LATENCY_GRACE_PERIOD_BLOCKS.
1435 #[deny(const_err)]
1436 #[allow(dead_code)]
1437 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;
1438
1439 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1440 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1441 #[deny(const_err)]
1442 #[allow(dead_code)]
1443 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1444
1445 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1446 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1447
1448 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1449 /// until we mark the channel disabled and gossip the update.
1450 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1451
1452 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1453 /// we mark the channel enabled and gossip the update.
1454 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1455
1456 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1457 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1458 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1459 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1460
1461 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1462 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1463 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1464
1465 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1466 /// many peers we reject new (inbound) connections.
1467 const MAX_NO_CHANNEL_PEERS: usize = 250;
1468
1469 /// Information needed for constructing an invoice route hint for this channel.
1470 #[derive(Clone, Debug, PartialEq)]
1471 pub struct CounterpartyForwardingInfo {
1472         /// Base routing fee in millisatoshis.
1473         pub fee_base_msat: u32,
1474         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1475         pub fee_proportional_millionths: u32,
1476         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1477         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1478         /// `cltv_expiry_delta` for more details.
1479         pub cltv_expiry_delta: u16,
1480 }
1481
1482 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1483 /// to better separate parameters.
1484 #[derive(Clone, Debug, PartialEq)]
1485 pub struct ChannelCounterparty {
1486         /// The node_id of our counterparty
1487         pub node_id: PublicKey,
1488         /// The Features the channel counterparty provided upon last connection.
1489         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1490         /// many routing-relevant features are present in the init context.
1491         pub features: InitFeatures,
1492         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1493         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1494         /// claiming at least this value on chain.
1495         ///
1496         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1497         ///
1498         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1499         pub unspendable_punishment_reserve: u64,
1500         /// Information on the fees and requirements that the counterparty requires when forwarding
1501         /// payments to us through this channel.
1502         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1503         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1504         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1505         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1506         pub outbound_htlc_minimum_msat: Option<u64>,
1507         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1508         pub outbound_htlc_maximum_msat: Option<u64>,
1509 }
1510
1511 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1512 #[derive(Clone, Debug, PartialEq)]
1513 pub struct ChannelDetails {
1514         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1515         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1516         /// Note that this means this value is *not* persistent - it can change once during the
1517         /// lifetime of the channel.
1518         pub channel_id: ChannelId,
1519         /// Parameters which apply to our counterparty. See individual fields for more information.
1520         pub counterparty: ChannelCounterparty,
1521         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1522         /// our counterparty already.
1523         ///
1524         /// Note that, if this has been set, `channel_id` will be equivalent to
1525         /// `funding_txo.unwrap().to_channel_id()`.
1526         pub funding_txo: Option<OutPoint>,
1527         /// The features which this channel operates with. See individual features for more info.
1528         ///
1529         /// `None` until negotiation completes and the channel type is finalized.
1530         pub channel_type: Option<ChannelTypeFeatures>,
1531         /// The position of the funding transaction in the chain. None if the funding transaction has
1532         /// not yet been confirmed and the channel fully opened.
1533         ///
1534         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1535         /// payments instead of this. See [`get_inbound_payment_scid`].
1536         ///
1537         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1538         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1539         ///
1540         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1541         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1542         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1543         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1544         /// [`confirmations_required`]: Self::confirmations_required
1545         pub short_channel_id: Option<u64>,
1546         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1547         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1548         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1549         /// `Some(0)`).
1550         ///
1551         /// This will be `None` as long as the channel is not available for routing outbound payments.
1552         ///
1553         /// [`short_channel_id`]: Self::short_channel_id
1554         /// [`confirmations_required`]: Self::confirmations_required
1555         pub outbound_scid_alias: Option<u64>,
1556         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1557         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1558         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1559         /// when they see a payment to be routed to us.
1560         ///
1561         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1562         /// previous values for inbound payment forwarding.
1563         ///
1564         /// [`short_channel_id`]: Self::short_channel_id
1565         pub inbound_scid_alias: Option<u64>,
1566         /// The value, in satoshis, of this channel as appears in the funding output
1567         pub channel_value_satoshis: u64,
1568         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1569         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1570         /// this value on chain.
1571         ///
1572         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1573         ///
1574         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1575         ///
1576         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1577         pub unspendable_punishment_reserve: Option<u64>,
1578         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1579         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1580         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1581         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1582         /// serialized with LDK versions prior to 0.0.113.
1583         ///
1584         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1585         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1586         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1587         pub user_channel_id: u128,
1588         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1589         /// which is applied to commitment and HTLC transactions.
1590         ///
1591         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1592         pub feerate_sat_per_1000_weight: Option<u32>,
1593         /// Our total balance.  This is the amount we would get if we close the channel.
1594         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1595         /// amount is not likely to be recoverable on close.
1596         ///
1597         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1598         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1599         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1600         /// This does not consider any on-chain fees.
1601         ///
1602         /// See also [`ChannelDetails::outbound_capacity_msat`]
1603         pub balance_msat: u64,
1604         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1605         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1606         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1607         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1608         ///
1609         /// See also [`ChannelDetails::balance_msat`]
1610         ///
1611         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1612         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1613         /// should be able to spend nearly this amount.
1614         pub outbound_capacity_msat: u64,
1615         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1616         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1617         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1618         /// to use a limit as close as possible to the HTLC limit we can currently send.
1619         ///
1620         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1621         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1622         pub next_outbound_htlc_limit_msat: u64,
1623         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1624         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1625         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1626         /// route which is valid.
1627         pub next_outbound_htlc_minimum_msat: u64,
1628         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1629         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1630         /// available for inclusion in new inbound HTLCs).
1631         /// Note that there are some corner cases not fully handled here, so the actual available
1632         /// inbound capacity may be slightly higher than this.
1633         ///
1634         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1635         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1636         /// However, our counterparty should be able to spend nearly this amount.
1637         pub inbound_capacity_msat: u64,
1638         /// The number of required confirmations on the funding transaction before the funding will be
1639         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1640         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1641         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1642         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1643         ///
1644         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1645         ///
1646         /// [`is_outbound`]: ChannelDetails::is_outbound
1647         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1648         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1649         pub confirmations_required: Option<u32>,
1650         /// The current number of confirmations on the funding transaction.
1651         ///
1652         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1653         pub confirmations: Option<u32>,
1654         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1655         /// until we can claim our funds after we force-close the channel. During this time our
1656         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1657         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1658         /// time to claim our non-HTLC-encumbered funds.
1659         ///
1660         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1661         pub force_close_spend_delay: Option<u16>,
1662         /// True if the channel was initiated (and thus funded) by us.
1663         pub is_outbound: bool,
1664         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1665         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1666         /// required confirmation count has been reached (and we were connected to the peer at some
1667         /// point after the funding transaction received enough confirmations). The required
1668         /// confirmation count is provided in [`confirmations_required`].
1669         ///
1670         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1671         pub is_channel_ready: bool,
1672         /// The stage of the channel's shutdown.
1673         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1674         pub channel_shutdown_state: Option<ChannelShutdownState>,
1675         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1676         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1677         ///
1678         /// This is a strict superset of `is_channel_ready`.
1679         pub is_usable: bool,
1680         /// True if this channel is (or will be) publicly-announced.
1681         pub is_public: bool,
1682         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1683         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1684         pub inbound_htlc_minimum_msat: Option<u64>,
1685         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1686         pub inbound_htlc_maximum_msat: Option<u64>,
1687         /// Set of configurable parameters that affect channel operation.
1688         ///
1689         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1690         pub config: Option<ChannelConfig>,
1691 }
1692
1693 impl ChannelDetails {
1694         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1695         /// This should be used for providing invoice hints or in any other context where our
1696         /// counterparty will forward a payment to us.
1697         ///
1698         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1699         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1700         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1701                 self.inbound_scid_alias.or(self.short_channel_id)
1702         }
1703
1704         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1705         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1706         /// we're sending or forwarding a payment outbound over this channel.
1707         ///
1708         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1709         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1710         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1711                 self.short_channel_id.or(self.outbound_scid_alias)
1712         }
1713
1714         fn from_channel_context<SP: Deref, F: Deref>(
1715                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1716                 fee_estimator: &LowerBoundedFeeEstimator<F>
1717         ) -> Self
1718         where
1719                 SP::Target: SignerProvider,
1720                 F::Target: FeeEstimator
1721         {
1722                 let balance = context.get_available_balances(fee_estimator);
1723                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1724                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1725                 ChannelDetails {
1726                         channel_id: context.channel_id(),
1727                         counterparty: ChannelCounterparty {
1728                                 node_id: context.get_counterparty_node_id(),
1729                                 features: latest_features,
1730                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1731                                 forwarding_info: context.counterparty_forwarding_info(),
1732                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1733                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1734                                 // message (as they are always the first message from the counterparty).
1735                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1736                                 // default `0` value set by `Channel::new_outbound`.
1737                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1738                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1739                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1740                         },
1741                         funding_txo: context.get_funding_txo(),
1742                         // Note that accept_channel (or open_channel) is always the first message, so
1743                         // `have_received_message` indicates that type negotiation has completed.
1744                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1745                         short_channel_id: context.get_short_channel_id(),
1746                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1747                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1748                         channel_value_satoshis: context.get_value_satoshis(),
1749                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1750                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1751                         balance_msat: balance.balance_msat,
1752                         inbound_capacity_msat: balance.inbound_capacity_msat,
1753                         outbound_capacity_msat: balance.outbound_capacity_msat,
1754                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1755                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1756                         user_channel_id: context.get_user_id(),
1757                         confirmations_required: context.minimum_depth(),
1758                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1759                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1760                         is_outbound: context.is_outbound(),
1761                         is_channel_ready: context.is_usable(),
1762                         is_usable: context.is_live(),
1763                         is_public: context.should_announce(),
1764                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1765                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1766                         config: Some(context.config()),
1767                         channel_shutdown_state: Some(context.shutdown_state()),
1768                 }
1769         }
1770 }
1771
1772 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1773 /// Further information on the details of the channel shutdown.
1774 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1775 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1776 /// the channel will be removed shortly.
1777 /// Also note, that in normal operation, peers could disconnect at any of these states
1778 /// and require peer re-connection before making progress onto other states
1779 pub enum ChannelShutdownState {
1780         /// Channel has not sent or received a shutdown message.
1781         NotShuttingDown,
1782         /// Local node has sent a shutdown message for this channel.
1783         ShutdownInitiated,
1784         /// Shutdown message exchanges have concluded and the channels are in the midst of
1785         /// resolving all existing open HTLCs before closing can continue.
1786         ResolvingHTLCs,
1787         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1788         NegotiatingClosingFee,
1789         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1790         /// to drop the channel.
1791         ShutdownComplete,
1792 }
1793
1794 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1795 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1796 #[derive(Debug, PartialEq)]
1797 pub enum RecentPaymentDetails {
1798         /// When an invoice was requested and thus a payment has not yet been sent.
1799         AwaitingInvoice {
1800                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1801                 /// a payment and ensure idempotency in LDK.
1802                 payment_id: PaymentId,
1803         },
1804         /// When a payment is still being sent and awaiting successful delivery.
1805         Pending {
1806                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1807                 /// a payment and ensure idempotency in LDK.
1808                 payment_id: PaymentId,
1809                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1810                 /// abandoned.
1811                 payment_hash: PaymentHash,
1812                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1813                 /// not just the amount currently inflight.
1814                 total_msat: u64,
1815         },
1816         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1817         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1818         /// payment is removed from tracking.
1819         Fulfilled {
1820                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1821                 /// a payment and ensure idempotency in LDK.
1822                 payment_id: PaymentId,
1823                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1824                 /// made before LDK version 0.0.104.
1825                 payment_hash: Option<PaymentHash>,
1826         },
1827         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1828         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1829         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1830         Abandoned {
1831                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1832                 /// a payment and ensure idempotency in LDK.
1833                 payment_id: PaymentId,
1834                 /// Hash of the payment that we have given up trying to send.
1835                 payment_hash: PaymentHash,
1836         },
1837 }
1838
1839 /// Route hints used in constructing invoices for [phantom node payents].
1840 ///
1841 /// [phantom node payments]: crate::sign::PhantomKeysManager
1842 #[derive(Clone)]
1843 pub struct PhantomRouteHints {
1844         /// The list of channels to be included in the invoice route hints.
1845         pub channels: Vec<ChannelDetails>,
1846         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1847         /// route hints.
1848         pub phantom_scid: u64,
1849         /// The pubkey of the real backing node that would ultimately receive the payment.
1850         pub real_node_pubkey: PublicKey,
1851 }
1852
1853 macro_rules! handle_error {
1854         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1855                 // In testing, ensure there are no deadlocks where the lock is already held upon
1856                 // entering the macro.
1857                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1858                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1859
1860                 match $internal {
1861                         Ok(msg) => Ok(msg),
1862                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1863                                 let mut msg_events = Vec::with_capacity(2);
1864
1865                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1866                                         $self.finish_close_channel(shutdown_res);
1867                                         if let Some(update) = update_option {
1868                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1869                                                         msg: update
1870                                                 });
1871                                         }
1872                                         if let Some((channel_id, user_channel_id)) = chan_id {
1873                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1874                                                         channel_id, user_channel_id,
1875                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1876                                                         counterparty_node_id: Some($counterparty_node_id),
1877                                                         channel_capacity_sats: channel_capacity,
1878                                                 }, None));
1879                                         }
1880                                 }
1881
1882                                 log_error!($self.logger, "{}", err.err);
1883                                 if let msgs::ErrorAction::IgnoreError = err.action {
1884                                 } else {
1885                                         msg_events.push(events::MessageSendEvent::HandleError {
1886                                                 node_id: $counterparty_node_id,
1887                                                 action: err.action.clone()
1888                                         });
1889                                 }
1890
1891                                 if !msg_events.is_empty() {
1892                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1893                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1894                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1895                                                 peer_state.pending_msg_events.append(&mut msg_events);
1896                                         }
1897                                 }
1898
1899                                 // Return error in case higher-API need one
1900                                 Err(err)
1901                         },
1902                 }
1903         } };
1904         ($self: ident, $internal: expr) => {
1905                 match $internal {
1906                         Ok(res) => Ok(res),
1907                         Err((chan, msg_handle_err)) => {
1908                                 let counterparty_node_id = chan.get_counterparty_node_id();
1909                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1910                         },
1911                 }
1912         };
1913 }
1914
1915 macro_rules! update_maps_on_chan_removal {
1916         ($self: expr, $channel_context: expr) => {{
1917                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1918                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1919                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1920                         short_to_chan_info.remove(&short_id);
1921                 } else {
1922                         // If the channel was never confirmed on-chain prior to its closure, remove the
1923                         // outbound SCID alias we used for it from the collision-prevention set. While we
1924                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1925                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1926                         // opening a million channels with us which are closed before we ever reach the funding
1927                         // stage.
1928                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1929                         debug_assert!(alias_removed);
1930                 }
1931                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1932         }}
1933 }
1934
1935 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1936 macro_rules! convert_chan_phase_err {
1937         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
1938                 match $err {
1939                         ChannelError::Warn(msg) => {
1940                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
1941                         },
1942                         ChannelError::Ignore(msg) => {
1943                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
1944                         },
1945                         ChannelError::Close(msg) => {
1946                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
1947                                 update_maps_on_chan_removal!($self, $channel.context);
1948                                 let shutdown_res = $channel.context.force_shutdown(true);
1949                                 let user_id = $channel.context.get_user_id();
1950                                 let channel_capacity_satoshis = $channel.context.get_value_satoshis();
1951
1952                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, user_id,
1953                                         shutdown_res, $channel_update, channel_capacity_satoshis))
1954                         },
1955                 }
1956         };
1957         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
1958                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
1959         };
1960         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
1961                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
1962         };
1963         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
1964                 match $channel_phase {
1965                         ChannelPhase::Funded(channel) => {
1966                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
1967                         },
1968                         ChannelPhase::UnfundedOutboundV1(channel) => {
1969                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1970                         },
1971                         ChannelPhase::UnfundedInboundV1(channel) => {
1972                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1973                         },
1974                 }
1975         };
1976 }
1977
1978 macro_rules! break_chan_phase_entry {
1979         ($self: ident, $res: expr, $entry: expr) => {
1980                 match $res {
1981                         Ok(res) => res,
1982                         Err(e) => {
1983                                 let key = *$entry.key();
1984                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1985                                 if drop {
1986                                         $entry.remove_entry();
1987                                 }
1988                                 break Err(res);
1989                         }
1990                 }
1991         }
1992 }
1993
1994 macro_rules! try_chan_phase_entry {
1995         ($self: ident, $res: expr, $entry: expr) => {
1996                 match $res {
1997                         Ok(res) => res,
1998                         Err(e) => {
1999                                 let key = *$entry.key();
2000                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2001                                 if drop {
2002                                         $entry.remove_entry();
2003                                 }
2004                                 return Err(res);
2005                         }
2006                 }
2007         }
2008 }
2009
2010 macro_rules! remove_channel_phase {
2011         ($self: expr, $entry: expr) => {
2012                 {
2013                         let channel = $entry.remove_entry().1;
2014                         update_maps_on_chan_removal!($self, &channel.context());
2015                         channel
2016                 }
2017         }
2018 }
2019
2020 macro_rules! send_channel_ready {
2021         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2022                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2023                         node_id: $channel.context.get_counterparty_node_id(),
2024                         msg: $channel_ready_msg,
2025                 });
2026                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2027                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2028                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2029                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2030                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2031                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2032                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2033                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2034                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2035                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2036                 }
2037         }}
2038 }
2039
2040 macro_rules! emit_channel_pending_event {
2041         ($locked_events: expr, $channel: expr) => {
2042                 if $channel.context.should_emit_channel_pending_event() {
2043                         $locked_events.push_back((events::Event::ChannelPending {
2044                                 channel_id: $channel.context.channel_id(),
2045                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2046                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2047                                 user_channel_id: $channel.context.get_user_id(),
2048                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2049                         }, None));
2050                         $channel.context.set_channel_pending_event_emitted();
2051                 }
2052         }
2053 }
2054
2055 macro_rules! emit_channel_ready_event {
2056         ($locked_events: expr, $channel: expr) => {
2057                 if $channel.context.should_emit_channel_ready_event() {
2058                         debug_assert!($channel.context.channel_pending_event_emitted());
2059                         $locked_events.push_back((events::Event::ChannelReady {
2060                                 channel_id: $channel.context.channel_id(),
2061                                 user_channel_id: $channel.context.get_user_id(),
2062                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2063                                 channel_type: $channel.context.get_channel_type().clone(),
2064                         }, None));
2065                         $channel.context.set_channel_ready_event_emitted();
2066                 }
2067         }
2068 }
2069
2070 macro_rules! handle_monitor_update_completion {
2071         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2072                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
2073                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2074                         $self.best_block.read().unwrap().height());
2075                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2076                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2077                         // We only send a channel_update in the case where we are just now sending a
2078                         // channel_ready and the channel is in a usable state. We may re-send a
2079                         // channel_update later through the announcement_signatures process for public
2080                         // channels, but there's no reason not to just inform our counterparty of our fees
2081                         // now.
2082                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2083                                 Some(events::MessageSendEvent::SendChannelUpdate {
2084                                         node_id: counterparty_node_id,
2085                                         msg,
2086                                 })
2087                         } else { None }
2088                 } else { None };
2089
2090                 let update_actions = $peer_state.monitor_update_blocked_actions
2091                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2092
2093                 let htlc_forwards = $self.handle_channel_resumption(
2094                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2095                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2096                         updates.funding_broadcastable, updates.channel_ready,
2097                         updates.announcement_sigs);
2098                 if let Some(upd) = channel_update {
2099                         $peer_state.pending_msg_events.push(upd);
2100                 }
2101
2102                 let channel_id = $chan.context.channel_id();
2103                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2104                 core::mem::drop($peer_state_lock);
2105                 core::mem::drop($per_peer_state_lock);
2106
2107                 // If the channel belongs to a batch funding transaction, the progress of the batch
2108                 // should be updated as we have received funding_signed and persisted the monitor.
2109                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2110                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2111                         let mut batch_completed = false;
2112                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2113                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2114                                         *chan_id == channel_id &&
2115                                         *pubkey == counterparty_node_id
2116                                 ));
2117                                 if let Some(channel_state) = channel_state {
2118                                         channel_state.2 = true;
2119                                 } else {
2120                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2121                                 }
2122                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2123                         } else {
2124                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2125                         }
2126
2127                         // When all channels in a batched funding transaction have become ready, it is not necessary
2128                         // to track the progress of the batch anymore and the state of the channels can be updated.
2129                         if batch_completed {
2130                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2131                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2132                                 let mut batch_funding_tx = None;
2133                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2134                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2135                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2136                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2137                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2138                                                         chan.set_batch_ready();
2139                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2140                                                         emit_channel_pending_event!(pending_events, chan);
2141                                                 }
2142                                         }
2143                                 }
2144                                 if let Some(tx) = batch_funding_tx {
2145                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2146                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2147                                 }
2148                         }
2149                 }
2150
2151                 $self.handle_monitor_update_completion_actions(update_actions);
2152
2153                 if let Some(forwards) = htlc_forwards {
2154                         $self.forward_htlcs(&mut [forwards][..]);
2155                 }
2156                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2157                 for failure in updates.failed_htlcs.drain(..) {
2158                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2159                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2160                 }
2161         } }
2162 }
2163
2164 macro_rules! handle_new_monitor_update {
2165         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2166                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2167                 match $update_res {
2168                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2169                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2170                                 log_error!($self.logger, "{}", err_str);
2171                                 panic!("{}", err_str);
2172                         },
2173                         ChannelMonitorUpdateStatus::InProgress => {
2174                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2175                                         &$chan.context.channel_id());
2176                                 false
2177                         },
2178                         ChannelMonitorUpdateStatus::Completed => {
2179                                 $completed;
2180                                 true
2181                         },
2182                 }
2183         } };
2184         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2185                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2186                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2187         };
2188         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2189                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2190                         .or_insert_with(Vec::new);
2191                 // During startup, we push monitor updates as background events through to here in
2192                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2193                 // filter for uniqueness here.
2194                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2195                         .unwrap_or_else(|| {
2196                                 in_flight_updates.push($update);
2197                                 in_flight_updates.len() - 1
2198                         });
2199                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2200                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2201                         {
2202                                 let _ = in_flight_updates.remove(idx);
2203                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2204                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2205                                 }
2206                         })
2207         } };
2208 }
2209
2210 macro_rules! process_events_body {
2211         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2212                 let mut processed_all_events = false;
2213                 while !processed_all_events {
2214                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2215                                 return;
2216                         }
2217
2218                         let mut result;
2219
2220                         {
2221                                 // We'll acquire our total consistency lock so that we can be sure no other
2222                                 // persists happen while processing monitor events.
2223                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2224
2225                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2226                                 // ensure any startup-generated background events are handled first.
2227                                 result = $self.process_background_events();
2228
2229                                 // TODO: This behavior should be documented. It's unintuitive that we query
2230                                 // ChannelMonitors when clearing other events.
2231                                 if $self.process_pending_monitor_events() {
2232                                         result = NotifyOption::DoPersist;
2233                                 }
2234                         }
2235
2236                         let pending_events = $self.pending_events.lock().unwrap().clone();
2237                         let num_events = pending_events.len();
2238                         if !pending_events.is_empty() {
2239                                 result = NotifyOption::DoPersist;
2240                         }
2241
2242                         let mut post_event_actions = Vec::new();
2243
2244                         for (event, action_opt) in pending_events {
2245                                 $event_to_handle = event;
2246                                 $handle_event;
2247                                 if let Some(action) = action_opt {
2248                                         post_event_actions.push(action);
2249                                 }
2250                         }
2251
2252                         {
2253                                 let mut pending_events = $self.pending_events.lock().unwrap();
2254                                 pending_events.drain(..num_events);
2255                                 processed_all_events = pending_events.is_empty();
2256                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2257                                 // updated here with the `pending_events` lock acquired.
2258                                 $self.pending_events_processor.store(false, Ordering::Release);
2259                         }
2260
2261                         if !post_event_actions.is_empty() {
2262                                 $self.handle_post_event_actions(post_event_actions);
2263                                 // If we had some actions, go around again as we may have more events now
2264                                 processed_all_events = false;
2265                         }
2266
2267                         match result {
2268                                 NotifyOption::DoPersist => {
2269                                         $self.needs_persist_flag.store(true, Ordering::Release);
2270                                         $self.event_persist_notifier.notify();
2271                                 },
2272                                 NotifyOption::SkipPersistHandleEvents =>
2273                                         $self.event_persist_notifier.notify(),
2274                                 NotifyOption::SkipPersistNoEvents => {},
2275                         }
2276                 }
2277         }
2278 }
2279
2280 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>
2281 where
2282         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2283         T::Target: BroadcasterInterface,
2284         ES::Target: EntropySource,
2285         NS::Target: NodeSigner,
2286         SP::Target: SignerProvider,
2287         F::Target: FeeEstimator,
2288         R::Target: Router,
2289         L::Target: Logger,
2290 {
2291         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2292         ///
2293         /// The current time or latest block header time can be provided as the `current_timestamp`.
2294         ///
2295         /// This is the main "logic hub" for all channel-related actions, and implements
2296         /// [`ChannelMessageHandler`].
2297         ///
2298         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2299         ///
2300         /// Users need to notify the new `ChannelManager` when a new block is connected or
2301         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2302         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2303         /// more details.
2304         ///
2305         /// [`block_connected`]: chain::Listen::block_connected
2306         /// [`block_disconnected`]: chain::Listen::block_disconnected
2307         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2308         pub fn new(
2309                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2310                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2311                 current_timestamp: u32,
2312         ) -> Self {
2313                 let mut secp_ctx = Secp256k1::new();
2314                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2315                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2316                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2317                 ChannelManager {
2318                         default_configuration: config.clone(),
2319                         chain_hash: ChainHash::using_genesis_block(params.network),
2320                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2321                         chain_monitor,
2322                         tx_broadcaster,
2323                         router,
2324
2325                         best_block: RwLock::new(params.best_block),
2326
2327                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2328                         pending_inbound_payments: Mutex::new(HashMap::new()),
2329                         pending_outbound_payments: OutboundPayments::new(),
2330                         forward_htlcs: Mutex::new(HashMap::new()),
2331                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2332                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2333                         id_to_peer: Mutex::new(HashMap::new()),
2334                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2335
2336                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2337                         secp_ctx,
2338
2339                         inbound_payment_key: expanded_inbound_key,
2340                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2341
2342                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2343
2344                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2345
2346                         per_peer_state: FairRwLock::new(HashMap::new()),
2347
2348                         pending_events: Mutex::new(VecDeque::new()),
2349                         pending_events_processor: AtomicBool::new(false),
2350                         pending_background_events: Mutex::new(Vec::new()),
2351                         total_consistency_lock: RwLock::new(()),
2352                         background_events_processed_since_startup: AtomicBool::new(false),
2353                         event_persist_notifier: Notifier::new(),
2354                         needs_persist_flag: AtomicBool::new(false),
2355                         funding_batch_states: Mutex::new(BTreeMap::new()),
2356
2357                         pending_offers_messages: Mutex::new(Vec::new()),
2358
2359                         entropy_source,
2360                         node_signer,
2361                         signer_provider,
2362
2363                         logger,
2364                 }
2365         }
2366
2367         /// Gets the current configuration applied to all new channels.
2368         pub fn get_current_default_configuration(&self) -> &UserConfig {
2369                 &self.default_configuration
2370         }
2371
2372         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2373                 let height = self.best_block.read().unwrap().height();
2374                 let mut outbound_scid_alias = 0;
2375                 let mut i = 0;
2376                 loop {
2377                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2378                                 outbound_scid_alias += 1;
2379                         } else {
2380                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2381                         }
2382                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2383                                 break;
2384                         }
2385                         i += 1;
2386                         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"); }
2387                 }
2388                 outbound_scid_alias
2389         }
2390
2391         /// Creates a new outbound channel to the given remote node and with the given value.
2392         ///
2393         /// `user_channel_id` will be provided back as in
2394         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2395         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2396         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2397         /// is simply copied to events and otherwise ignored.
2398         ///
2399         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2400         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2401         ///
2402         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2403         /// generate a shutdown scriptpubkey or destination script set by
2404         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2405         ///
2406         /// Note that we do not check if you are currently connected to the given peer. If no
2407         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2408         /// the channel eventually being silently forgotten (dropped on reload).
2409         ///
2410         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2411         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2412         /// [`ChannelDetails::channel_id`] until after
2413         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2414         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2415         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2416         ///
2417         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2418         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2419         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2420         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_channel_id: u128, override_config: Option<UserConfig>) -> Result<ChannelId, APIError> {
2421                 if channel_value_satoshis < 1000 {
2422                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2423                 }
2424
2425                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2426                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2427                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2428
2429                 let per_peer_state = self.per_peer_state.read().unwrap();
2430
2431                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2432                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2433
2434                 let mut peer_state = peer_state_mutex.lock().unwrap();
2435                 let channel = {
2436                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2437                         let their_features = &peer_state.latest_features;
2438                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2439                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2440                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2441                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2442                         {
2443                                 Ok(res) => res,
2444                                 Err(e) => {
2445                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2446                                         return Err(e);
2447                                 },
2448                         }
2449                 };
2450                 let res = channel.get_open_channel(self.chain_hash);
2451
2452                 let temporary_channel_id = channel.context.channel_id();
2453                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2454                         hash_map::Entry::Occupied(_) => {
2455                                 if cfg!(fuzzing) {
2456                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2457                                 } else {
2458                                         panic!("RNG is bad???");
2459                                 }
2460                         },
2461                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2462                 }
2463
2464                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2465                         node_id: their_network_key,
2466                         msg: res,
2467                 });
2468                 Ok(temporary_channel_id)
2469         }
2470
2471         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2472                 // Allocate our best estimate of the number of channels we have in the `res`
2473                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2474                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2475                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2476                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2477                 // the same channel.
2478                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2479                 {
2480                         let best_block_height = self.best_block.read().unwrap().height();
2481                         let per_peer_state = self.per_peer_state.read().unwrap();
2482                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2483                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2484                                 let peer_state = &mut *peer_state_lock;
2485                                 res.extend(peer_state.channel_by_id.iter()
2486                                         .filter_map(|(chan_id, phase)| match phase {
2487                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2488                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2489                                                 _ => None,
2490                                         })
2491                                         .filter(f)
2492                                         .map(|(_channel_id, channel)| {
2493                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2494                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2495                                         })
2496                                 );
2497                         }
2498                 }
2499                 res
2500         }
2501
2502         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2503         /// more information.
2504         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2505                 // Allocate our best estimate of the number of channels we have in the `res`
2506                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2507                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2508                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2509                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2510                 // the same channel.
2511                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2512                 {
2513                         let best_block_height = self.best_block.read().unwrap().height();
2514                         let per_peer_state = self.per_peer_state.read().unwrap();
2515                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2516                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2517                                 let peer_state = &mut *peer_state_lock;
2518                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2519                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2520                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2521                                         res.push(details);
2522                                 }
2523                         }
2524                 }
2525                 res
2526         }
2527
2528         /// Gets the list of usable channels, in random order. Useful as an argument to
2529         /// [`Router::find_route`] to ensure non-announced channels are used.
2530         ///
2531         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2532         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2533         /// are.
2534         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2535                 // Note we use is_live here instead of usable which leads to somewhat confused
2536                 // internal/external nomenclature, but that's ok cause that's probably what the user
2537                 // really wanted anyway.
2538                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2539         }
2540
2541         /// Gets the list of channels we have with a given counterparty, in random order.
2542         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2543                 let best_block_height = self.best_block.read().unwrap().height();
2544                 let per_peer_state = self.per_peer_state.read().unwrap();
2545
2546                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2547                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2548                         let peer_state = &mut *peer_state_lock;
2549                         let features = &peer_state.latest_features;
2550                         let context_to_details = |context| {
2551                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2552                         };
2553                         return peer_state.channel_by_id
2554                                 .iter()
2555                                 .map(|(_, phase)| phase.context())
2556                                 .map(context_to_details)
2557                                 .collect();
2558                 }
2559                 vec![]
2560         }
2561
2562         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2563         /// successful path, or have unresolved HTLCs.
2564         ///
2565         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2566         /// result of a crash. If such a payment exists, is not listed here, and an
2567         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2568         ///
2569         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2570         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2571                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2572                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2573                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2574                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2575                                 },
2576                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2577                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2578                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2579                                 },
2580                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2581                                         Some(RecentPaymentDetails::Pending {
2582                                                 payment_id: *payment_id,
2583                                                 payment_hash: *payment_hash,
2584                                                 total_msat: *total_msat,
2585                                         })
2586                                 },
2587                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2588                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2589                                 },
2590                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2591                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2592                                 },
2593                                 PendingOutboundPayment::Legacy { .. } => None
2594                         })
2595                         .collect()
2596         }
2597
2598         /// Helper function that issues the channel close events
2599         fn issue_channel_close_events(&self, context: &ChannelContext<SP>, closure_reason: ClosureReason) {
2600                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2601                 match context.unbroadcasted_funding() {
2602                         Some(transaction) => {
2603                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2604                                         channel_id: context.channel_id(), transaction
2605                                 }, None));
2606                         },
2607                         None => {},
2608                 }
2609                 pending_events_lock.push_back((events::Event::ChannelClosed {
2610                         channel_id: context.channel_id(),
2611                         user_channel_id: context.get_user_id(),
2612                         reason: closure_reason,
2613                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2614                         channel_capacity_sats: Some(context.get_value_satoshis()),
2615                 }, None));
2616         }
2617
2618         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> {
2619                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2620
2621                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2622                 let shutdown_result;
2623                 loop {
2624                         let per_peer_state = self.per_peer_state.read().unwrap();
2625
2626                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2627                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2628
2629                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2630                         let peer_state = &mut *peer_state_lock;
2631
2632                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2633                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2634                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2635                                                 let funding_txo_opt = chan.context.get_funding_txo();
2636                                                 let their_features = &peer_state.latest_features;
2637                                                 let (shutdown_msg, mut monitor_update_opt, htlcs, local_shutdown_result) =
2638                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2639                                                 failed_htlcs = htlcs;
2640                                                 shutdown_result = local_shutdown_result;
2641                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
2642
2643                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2644                                                 // here as we don't need the monitor update to complete until we send a
2645                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2646                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2647                                                         node_id: *counterparty_node_id,
2648                                                         msg: shutdown_msg,
2649                                                 });
2650
2651                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2652                                                         "We can't both complete shutdown and generate a monitor update");
2653
2654                                                 // Update the monitor with the shutdown script if necessary.
2655                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2656                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2657                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2658                                                         break;
2659                                                 }
2660
2661                                                 if chan.is_shutdown() {
2662                                                         if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2663                                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2664                                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2665                                                                                 msg: channel_update
2666                                                                         });
2667                                                                 }
2668                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2669                                                         }
2670                                                 }
2671                                                 break;
2672                                         }
2673                                 },
2674                                 hash_map::Entry::Vacant(_) => {
2675                                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2676                                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2677                                         //
2678                                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2679                                         mem::drop(peer_state_lock);
2680                                         mem::drop(per_peer_state);
2681                                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2682                                 },
2683                         }
2684                 }
2685
2686                 for htlc_source in failed_htlcs.drain(..) {
2687                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2688                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2689                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2690                 }
2691
2692                 if let Some(shutdown_result) = shutdown_result {
2693                         self.finish_close_channel(shutdown_result);
2694                 }
2695
2696                 Ok(())
2697         }
2698
2699         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2700         /// will be accepted on the given channel, and after additional timeout/the closing of all
2701         /// pending HTLCs, the channel will be closed on chain.
2702         ///
2703         ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2704         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2705         ///    fee estimate.
2706         ///  * If our counterparty is the channel initiator, we will require a channel closing
2707         ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2708         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2709         ///    counterparty to pay as much fee as they'd like, however.
2710         ///
2711         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2712         ///
2713         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2714         /// generate a shutdown scriptpubkey or destination script set by
2715         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2716         /// channel.
2717         ///
2718         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2719         /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2720         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2721         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2722         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2723                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2724         }
2725
2726         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2727         /// will be accepted on the given channel, and after additional timeout/the closing of all
2728         /// pending HTLCs, the channel will be closed on chain.
2729         ///
2730         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2731         /// the channel being closed or not:
2732         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2733         ///    transaction. The upper-bound is set by
2734         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2735         ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2736         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2737         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2738         ///    will appear on a force-closure transaction, whichever is lower).
2739         ///
2740         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2741         /// Will fail if a shutdown script has already been set for this channel by
2742         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2743         /// also be compatible with our and the counterparty's features.
2744         ///
2745         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2746         ///
2747         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2748         /// generate a shutdown scriptpubkey or destination script set by
2749         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2750         /// channel.
2751         ///
2752         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2753         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2754         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2755         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> {
2756                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2757         }
2758
2759         fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) {
2760                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2761                 #[cfg(debug_assertions)]
2762                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2763                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2764                 }
2765
2766                 log_debug!(self.logger, "Finishing closure of channel with {} HTLCs to fail", shutdown_res.dropped_outbound_htlcs.len());
2767                 for htlc_source in shutdown_res.dropped_outbound_htlcs.drain(..) {
2768                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2769                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2770                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2771                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2772                 }
2773                 if let Some((_, funding_txo, monitor_update)) = shutdown_res.monitor_update {
2774                         // There isn't anything we can do if we get an update failure - we're already
2775                         // force-closing. The monitor update on the required in-memory copy should broadcast
2776                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2777                         // ignore the result here.
2778                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2779                 }
2780                 let mut shutdown_results = Vec::new();
2781                 if let Some(txid) = shutdown_res.unbroadcasted_batch_funding_txid {
2782                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2783                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2784                         let per_peer_state = self.per_peer_state.read().unwrap();
2785                         let mut has_uncompleted_channel = None;
2786                         for (channel_id, counterparty_node_id, state) in affected_channels {
2787                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2788                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2789                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2790                                                 update_maps_on_chan_removal!(self, &chan.context());
2791                                                 self.issue_channel_close_events(&chan.context(), ClosureReason::FundingBatchClosure);
2792                                                 shutdown_results.push(chan.context_mut().force_shutdown(false));
2793                                         }
2794                                 }
2795                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2796                         }
2797                         debug_assert!(
2798                                 has_uncompleted_channel.unwrap_or(true),
2799                                 "Closing a batch where all channels have completed initial monitor update",
2800                         );
2801                 }
2802                 for shutdown_result in shutdown_results.drain(..) {
2803                         self.finish_close_channel(shutdown_result);
2804                 }
2805         }
2806
2807         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2808         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2809         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2810         -> Result<PublicKey, APIError> {
2811                 let per_peer_state = self.per_peer_state.read().unwrap();
2812                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2813                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2814                 let (update_opt, counterparty_node_id) = {
2815                         let mut peer_state = peer_state_mutex.lock().unwrap();
2816                         let closure_reason = if let Some(peer_msg) = peer_msg {
2817                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2818                         } else {
2819                                 ClosureReason::HolderForceClosed
2820                         };
2821                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2822                                 log_error!(self.logger, "Force-closing channel {}", channel_id);
2823                                 self.issue_channel_close_events(&chan_phase_entry.get().context(), closure_reason);
2824                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2825                                 mem::drop(peer_state);
2826                                 mem::drop(per_peer_state);
2827                                 match chan_phase {
2828                                         ChannelPhase::Funded(mut chan) => {
2829                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast));
2830                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2831                                         },
2832                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2833                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false));
2834                                                 // Unfunded channel has no update
2835                                                 (None, chan_phase.context().get_counterparty_node_id())
2836                                         },
2837                                 }
2838                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2839                                 log_error!(self.logger, "Force-closing channel {}", &channel_id);
2840                                 // N.B. that we don't send any channel close event here: we
2841                                 // don't have a user_channel_id, and we never sent any opening
2842                                 // events anyway.
2843                                 (None, *peer_node_id)
2844                         } else {
2845                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2846                         }
2847                 };
2848                 if let Some(update) = update_opt {
2849                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2850                         // not try to broadcast it via whatever peer we have.
2851                         let per_peer_state = self.per_peer_state.read().unwrap();
2852                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2853                                 .ok_or(per_peer_state.values().next());
2854                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2855                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2856                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2857                                         msg: update
2858                                 });
2859                         }
2860                 }
2861
2862                 Ok(counterparty_node_id)
2863         }
2864
2865         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2866                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2867                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2868                         Ok(counterparty_node_id) => {
2869                                 let per_peer_state = self.per_peer_state.read().unwrap();
2870                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2871                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2872                                         peer_state.pending_msg_events.push(
2873                                                 events::MessageSendEvent::HandleError {
2874                                                         node_id: counterparty_node_id,
2875                                                         action: msgs::ErrorAction::DisconnectPeer {
2876                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2877                                                         },
2878                                                 }
2879                                         );
2880                                 }
2881                                 Ok(())
2882                         },
2883                         Err(e) => Err(e)
2884                 }
2885         }
2886
2887         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2888         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2889         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2890         /// channel.
2891         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2892         -> Result<(), APIError> {
2893                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2894         }
2895
2896         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2897         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2898         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2899         ///
2900         /// You can always get the latest local transaction(s) to broadcast from
2901         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2902         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2903         -> Result<(), APIError> {
2904                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2905         }
2906
2907         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2908         /// for each to the chain and rejecting new HTLCs on each.
2909         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2910                 for chan in self.list_channels() {
2911                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2912                 }
2913         }
2914
2915         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2916         /// local transaction(s).
2917         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2918                 for chan in self.list_channels() {
2919                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2920                 }
2921         }
2922
2923         fn decode_update_add_htlc_onion(
2924                 &self, msg: &msgs::UpdateAddHTLC
2925         ) -> Result<
2926                 (onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg
2927         > {
2928                 let (next_hop, shared_secret, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(
2929                         msg, &self.node_signer, &self.logger, &self.secp_ctx
2930                 )?;
2931
2932                 macro_rules! return_err {
2933                         ($msg: expr, $err_code: expr, $data: expr) => {
2934                                 {
2935                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2936                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2937                                                 channel_id: msg.channel_id,
2938                                                 htlc_id: msg.htlc_id,
2939                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2940                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2941                                         }));
2942                                 }
2943                         }
2944                 }
2945
2946                 let NextPacketDetails {
2947                         next_packet_pubkey, outgoing_amt_msat, outgoing_scid, outgoing_cltv_value
2948                 } = match next_packet_details_opt {
2949                         Some(next_packet_details) => next_packet_details,
2950                         // it is a receive, so no need for outbound checks
2951                         None => return Ok((next_hop, shared_secret, None)),
2952                 };
2953
2954                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
2955                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
2956                 if let Some((err, mut code, chan_update)) = loop {
2957                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
2958                         let forwarding_chan_info_opt = match id_option {
2959                                 None => { // unknown_next_peer
2960                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2961                                         // phantom or an intercept.
2962                                         if (self.default_configuration.accept_intercept_htlcs &&
2963                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
2964                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
2965                                         {
2966                                                 None
2967                                         } else {
2968                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2969                                         }
2970                                 },
2971                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
2972                         };
2973                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
2974                                 let per_peer_state = self.per_peer_state.read().unwrap();
2975                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2976                                 if peer_state_mutex_opt.is_none() {
2977                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2978                                 }
2979                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2980                                 let peer_state = &mut *peer_state_lock;
2981                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
2982                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
2983                                 ).flatten() {
2984                                         None => {
2985                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
2986                                                 // have no consistency guarantees.
2987                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2988                                         },
2989                                         Some(chan) => chan
2990                                 };
2991                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2992                                         // Note that the behavior here should be identical to the above block - we
2993                                         // should NOT reveal the existence or non-existence of a private channel if
2994                                         // we don't allow forwards outbound over them.
2995                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2996                                 }
2997                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
2998                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
2999                                         // "refuse to forward unless the SCID alias was used", so we pretend
3000                                         // we don't have the channel here.
3001                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3002                                 }
3003                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3004
3005                                 // Note that we could technically not return an error yet here and just hope
3006                                 // that the connection is reestablished or monitor updated by the time we get
3007                                 // around to doing the actual forward, but better to fail early if we can and
3008                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3009                                 // on a small/per-node/per-channel scale.
3010                                 if !chan.context.is_live() { // channel_disabled
3011                                         // If the channel_update we're going to return is disabled (i.e. the
3012                                         // peer has been disabled for some time), return `channel_disabled`,
3013                                         // otherwise return `temporary_channel_failure`.
3014                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3015                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3016                                         } else {
3017                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3018                                         }
3019                                 }
3020                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3021                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3022                                 }
3023                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3024                                         break Some((err, code, chan_update_opt));
3025                                 }
3026                                 chan_update_opt
3027                         } else {
3028                                 None
3029                         };
3030
3031                         let cur_height = self.best_block.read().unwrap().height() + 1;
3032
3033                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
3034                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
3035                         ) {
3036                                 if code & 0x1000 != 0 && chan_update_opt.is_none() {
3037                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3038                                         // forwarding over a real channel we can't generate a channel_update
3039                                         // for it. Instead we just return a generic temporary_node_failure.
3040                                         break Some((err_msg, 0x2000 | 2, None))
3041                                 }
3042                                 let chan_update_opt = if code & 0x1000 != 0 { chan_update_opt } else { None };
3043                                 break Some((err_msg, code, chan_update_opt));
3044                         }
3045
3046                         break None;
3047                 }
3048                 {
3049                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3050                         if let Some(chan_update) = chan_update {
3051                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3052                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3053                                 }
3054                                 else if code == 0x1000 | 13 {
3055                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3056                                 }
3057                                 else if code == 0x1000 | 20 {
3058                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3059                                         0u16.write(&mut res).expect("Writes cannot fail");
3060                                 }
3061                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3062                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3063                                 chan_update.write(&mut res).expect("Writes cannot fail");
3064                         } else if code & 0x1000 == 0x1000 {
3065                                 // If we're trying to return an error that requires a `channel_update` but
3066                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3067                                 // generate an update), just use the generic "temporary_node_failure"
3068                                 // instead.
3069                                 code = 0x2000 | 2;
3070                         }
3071                         return_err!(err, code, &res.0[..]);
3072                 }
3073                 Ok((next_hop, shared_secret, Some(next_packet_pubkey)))
3074         }
3075
3076         fn construct_pending_htlc_status<'a>(
3077                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3078                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3079         ) -> PendingHTLCStatus {
3080                 macro_rules! return_err {
3081                         ($msg: expr, $err_code: expr, $data: expr) => {
3082                                 {
3083                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3084                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3085                                                 channel_id: msg.channel_id,
3086                                                 htlc_id: msg.htlc_id,
3087                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3088                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3089                                         }));
3090                                 }
3091                         }
3092                 }
3093                 match decoded_hop {
3094                         onion_utils::Hop::Receive(next_hop_data) => {
3095                                 // OUR PAYMENT!
3096                                 let current_height: u32 = self.best_block.read().unwrap().height();
3097                                 match create_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3098                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat,
3099                                         current_height, self.default_configuration.accept_mpp_keysend)
3100                                 {
3101                                         Ok(info) => {
3102                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3103                                                 // message, however that would leak that we are the recipient of this payment, so
3104                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3105                                                 // delay) once they've send us a commitment_signed!
3106                                                 PendingHTLCStatus::Forward(info)
3107                                         },
3108                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3109                                 }
3110                         },
3111                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3112                                 match create_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3113                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3114                                         Ok(info) => PendingHTLCStatus::Forward(info),
3115                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3116                                 }
3117                         }
3118                 }
3119         }
3120
3121         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3122         /// public, and thus should be called whenever the result is going to be passed out in a
3123         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3124         ///
3125         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3126         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3127         /// storage and the `peer_state` lock has been dropped.
3128         ///
3129         /// [`channel_update`]: msgs::ChannelUpdate
3130         /// [`internal_closing_signed`]: Self::internal_closing_signed
3131         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3132                 if !chan.context.should_announce() {
3133                         return Err(LightningError {
3134                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3135                                 action: msgs::ErrorAction::IgnoreError
3136                         });
3137                 }
3138                 if chan.context.get_short_channel_id().is_none() {
3139                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3140                 }
3141                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3142                 self.get_channel_update_for_unicast(chan)
3143         }
3144
3145         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3146         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3147         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3148         /// provided evidence that they know about the existence of the channel.
3149         ///
3150         /// Note that through [`internal_closing_signed`], this function is called without the
3151         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3152         /// removed from the storage and the `peer_state` lock has been dropped.
3153         ///
3154         /// [`channel_update`]: msgs::ChannelUpdate
3155         /// [`internal_closing_signed`]: Self::internal_closing_signed
3156         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3157                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", &chan.context.channel_id());
3158                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3159                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3160                         Some(id) => id,
3161                 };
3162
3163                 self.get_channel_update_for_onion(short_channel_id, chan)
3164         }
3165
3166         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3167                 log_trace!(self.logger, "Generating channel update for channel {}", &chan.context.channel_id());
3168                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3169
3170                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3171                         ChannelUpdateStatus::Enabled => true,
3172                         ChannelUpdateStatus::DisabledStaged(_) => true,
3173                         ChannelUpdateStatus::Disabled => false,
3174                         ChannelUpdateStatus::EnabledStaged(_) => false,
3175                 };
3176
3177                 let unsigned = msgs::UnsignedChannelUpdate {
3178                         chain_hash: self.chain_hash,
3179                         short_channel_id,
3180                         timestamp: chan.context.get_update_time_counter(),
3181                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3182                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3183                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3184                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3185                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3186                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3187                         excess_data: Vec::new(),
3188                 };
3189                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3190                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3191                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3192                 // channel.
3193                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3194
3195                 Ok(msgs::ChannelUpdate {
3196                         signature: sig,
3197                         contents: unsigned
3198                 })
3199         }
3200
3201         #[cfg(test)]
3202         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> {
3203                 let _lck = self.total_consistency_lock.read().unwrap();
3204                 self.send_payment_along_path(SendAlongPathArgs {
3205                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3206                         session_priv_bytes
3207                 })
3208         }
3209
3210         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3211                 let SendAlongPathArgs {
3212                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3213                         session_priv_bytes
3214                 } = args;
3215                 // The top-level caller should hold the total_consistency_lock read lock.
3216                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3217
3218                 log_trace!(self.logger,
3219                         "Attempting to send payment with payment hash {} along path with next hop {}",
3220                         payment_hash, path.hops.first().unwrap().short_channel_id);
3221                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3222                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3223
3224                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3225                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3226                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3227
3228                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3229                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3230
3231                 let err: Result<(), _> = loop {
3232                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3233                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3234                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3235                         };
3236
3237                         let per_peer_state = self.per_peer_state.read().unwrap();
3238                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3239                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3240                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3241                         let peer_state = &mut *peer_state_lock;
3242                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3243                                 match chan_phase_entry.get_mut() {
3244                                         ChannelPhase::Funded(chan) => {
3245                                                 if !chan.context.is_live() {
3246                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3247                                                 }
3248                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3249                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3250                                                         htlc_cltv, HTLCSource::OutboundRoute {
3251                                                                 path: path.clone(),
3252                                                                 session_priv: session_priv.clone(),
3253                                                                 first_hop_htlc_msat: htlc_msat,
3254                                                                 payment_id,
3255                                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3256                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3257                                                         Some(monitor_update) => {
3258                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3259                                                                         false => {
3260                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3261                                                                                 // docs) that we will resend the commitment update once monitor
3262                                                                                 // updating completes. Therefore, we must return an error
3263                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3264                                                                                 // which we do in the send_payment check for
3265                                                                                 // MonitorUpdateInProgress, below.
3266                                                                                 return Err(APIError::MonitorUpdateInProgress);
3267                                                                         },
3268                                                                         true => {},
3269                                                                 }
3270                                                         },
3271                                                         None => {},
3272                                                 }
3273                                         },
3274                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3275                                 };
3276                         } else {
3277                                 // The channel was likely removed after we fetched the id from the
3278                                 // `short_to_chan_info` map, but before we successfully locked the
3279                                 // `channel_by_id` map.
3280                                 // This can occur as no consistency guarantees exists between the two maps.
3281                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3282                         }
3283                         return Ok(());
3284                 };
3285
3286                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3287                         Ok(_) => unreachable!(),
3288                         Err(e) => {
3289                                 Err(APIError::ChannelUnavailable { err: e.err })
3290                         },
3291                 }
3292         }
3293
3294         /// Sends a payment along a given route.
3295         ///
3296         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3297         /// fields for more info.
3298         ///
3299         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3300         /// [`PeerManager::process_events`]).
3301         ///
3302         /// # Avoiding Duplicate Payments
3303         ///
3304         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3305         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3306         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3307         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3308         /// second payment with the same [`PaymentId`].
3309         ///
3310         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3311         /// tracking of payments, including state to indicate once a payment has completed. Because you
3312         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3313         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3314         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3315         ///
3316         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3317         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3318         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3319         /// [`ChannelManager::list_recent_payments`] for more information.
3320         ///
3321         /// # Possible Error States on [`PaymentSendFailure`]
3322         ///
3323         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3324         /// each entry matching the corresponding-index entry in the route paths, see
3325         /// [`PaymentSendFailure`] for more info.
3326         ///
3327         /// In general, a path may raise:
3328         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3329         ///    node public key) is specified.
3330         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3331         ///    closed, doesn't exist, or the peer is currently disconnected.
3332         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3333         ///    relevant updates.
3334         ///
3335         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3336         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3337         /// different route unless you intend to pay twice!
3338         ///
3339         /// [`RouteHop`]: crate::routing::router::RouteHop
3340         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3341         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3342         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3343         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3344         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3345         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3346                 let best_block_height = self.best_block.read().unwrap().height();
3347                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3348                 self.pending_outbound_payments
3349                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3350                                 &self.entropy_source, &self.node_signer, best_block_height,
3351                                 |args| self.send_payment_along_path(args))
3352         }
3353
3354         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3355         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3356         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3357                 let best_block_height = self.best_block.read().unwrap().height();
3358                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3359                 self.pending_outbound_payments
3360                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3361                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3362                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3363                                 &self.pending_events, |args| self.send_payment_along_path(args))
3364         }
3365
3366         #[cfg(test)]
3367         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> {
3368                 let best_block_height = self.best_block.read().unwrap().height();
3369                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3370                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3371                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3372                         best_block_height, |args| self.send_payment_along_path(args))
3373         }
3374
3375         #[cfg(test)]
3376         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> {
3377                 let best_block_height = self.best_block.read().unwrap().height();
3378                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3379         }
3380
3381         #[cfg(test)]
3382         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3383                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3384         }
3385
3386         pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3387                 let best_block_height = self.best_block.read().unwrap().height();
3388                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3389                 self.pending_outbound_payments
3390                         .send_payment_for_bolt12_invoice(
3391                                 invoice, payment_id, &self.router, self.list_usable_channels(),
3392                                 || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3393                                 best_block_height, &self.logger, &self.pending_events,
3394                                 |args| self.send_payment_along_path(args)
3395                         )
3396         }
3397
3398         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3399         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3400         /// retries are exhausted.
3401         ///
3402         /// # Event Generation
3403         ///
3404         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3405         /// as there are no remaining pending HTLCs for this payment.
3406         ///
3407         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3408         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3409         /// determine the ultimate status of a payment.
3410         ///
3411         /// # Requested Invoices
3412         ///
3413         /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
3414         /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
3415         /// and prevent any attempts at paying it once received. The other events may only be generated
3416         /// once the invoice has been received.
3417         ///
3418         /// # Restart Behavior
3419         ///
3420         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3421         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
3422         /// [`Event::InvoiceRequestFailed`].
3423         ///
3424         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3425         pub fn abandon_payment(&self, payment_id: PaymentId) {
3426                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3427                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3428         }
3429
3430         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3431         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3432         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3433         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3434         /// never reach the recipient.
3435         ///
3436         /// See [`send_payment`] documentation for more details on the return value of this function
3437         /// and idempotency guarantees provided by the [`PaymentId`] key.
3438         ///
3439         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3440         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3441         ///
3442         /// [`send_payment`]: Self::send_payment
3443         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3444                 let best_block_height = self.best_block.read().unwrap().height();
3445                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3446                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3447                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3448                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3449         }
3450
3451         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3452         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3453         ///
3454         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3455         /// payments.
3456         ///
3457         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3458         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> {
3459                 let best_block_height = self.best_block.read().unwrap().height();
3460                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3461                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3462                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3463                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3464                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3465         }
3466
3467         /// Send a payment that is probing the given route for liquidity. We calculate the
3468         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3469         /// us to easily discern them from real payments.
3470         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3471                 let best_block_height = self.best_block.read().unwrap().height();
3472                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3473                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3474                         &self.entropy_source, &self.node_signer, best_block_height,
3475                         |args| self.send_payment_along_path(args))
3476         }
3477
3478         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3479         /// payment probe.
3480         #[cfg(test)]
3481         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3482                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3483         }
3484
3485         /// Sends payment probes over all paths of a route that would be used to pay the given
3486         /// amount to the given `node_id`.
3487         ///
3488         /// See [`ChannelManager::send_preflight_probes`] for more information.
3489         pub fn send_spontaneous_preflight_probes(
3490                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3491                 liquidity_limit_multiplier: Option<u64>,
3492         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3493                 let payment_params =
3494                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3495
3496                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3497
3498                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3499         }
3500
3501         /// Sends payment probes over all paths of a route that would be used to pay a route found
3502         /// according to the given [`RouteParameters`].
3503         ///
3504         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3505         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3506         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3507         /// confirmation in a wallet UI.
3508         ///
3509         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3510         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3511         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3512         /// payment. To mitigate this issue, channels with available liquidity less than the required
3513         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3514         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3515         pub fn send_preflight_probes(
3516                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3517         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3518                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3519
3520                 let payer = self.get_our_node_id();
3521                 let usable_channels = self.list_usable_channels();
3522                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3523                 let inflight_htlcs = self.compute_inflight_htlcs();
3524
3525                 let route = self
3526                         .router
3527                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3528                         .map_err(|e| {
3529                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3530                                 ProbeSendFailure::RouteNotFound
3531                         })?;
3532
3533                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3534
3535                 let mut res = Vec::new();
3536
3537                 for mut path in route.paths {
3538                         // If the last hop is probably an unannounced channel we refrain from probing all the
3539                         // way through to the end and instead probe up to the second-to-last channel.
3540                         while let Some(last_path_hop) = path.hops.last() {
3541                                 if last_path_hop.maybe_announced_channel {
3542                                         // We found a potentially announced last hop.
3543                                         break;
3544                                 } else {
3545                                         // Drop the last hop, as it's likely unannounced.
3546                                         log_debug!(
3547                                                 self.logger,
3548                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3549                                                 last_path_hop.short_channel_id
3550                                         );
3551                                         let final_value_msat = path.final_value_msat();
3552                                         path.hops.pop();
3553                                         if let Some(new_last) = path.hops.last_mut() {
3554                                                 new_last.fee_msat += final_value_msat;
3555                                         }
3556                                 }
3557                         }
3558
3559                         if path.hops.len() < 2 {
3560                                 log_debug!(
3561                                         self.logger,
3562                                         "Skipped sending payment probe over path with less than two hops."
3563                                 );
3564                                 continue;
3565                         }
3566
3567                         if let Some(first_path_hop) = path.hops.first() {
3568                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3569                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3570                                 }) {
3571                                         let path_value = path.final_value_msat() + path.fee_msat();
3572                                         let used_liquidity =
3573                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3574
3575                                         if first_hop.next_outbound_htlc_limit_msat
3576                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3577                                         {
3578                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3579                                                 continue;
3580                                         } else {
3581                                                 *used_liquidity += path_value;
3582                                         }
3583                                 }
3584                         }
3585
3586                         res.push(self.send_probe(path).map_err(|e| {
3587                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3588                                 ProbeSendFailure::SendingFailed(e)
3589                         })?);
3590                 }
3591
3592                 Ok(res)
3593         }
3594
3595         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3596         /// which checks the correctness of the funding transaction given the associated channel.
3597         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3598                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3599                 mut find_funding_output: FundingOutput,
3600         ) -> Result<(), APIError> {
3601                 let per_peer_state = self.per_peer_state.read().unwrap();
3602                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3603                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3604
3605                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3606                 let peer_state = &mut *peer_state_lock;
3607                 let (chan, msg) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3608                         Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
3609                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3610
3611                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &self.logger)
3612                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3613                                                 let channel_id = chan.context.channel_id();
3614                                                 let user_id = chan.context.get_user_id();
3615                                                 let shutdown_res = chan.context.force_shutdown(false);
3616                                                 let channel_capacity = chan.context.get_value_satoshis();
3617                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3618                                         } else { unreachable!(); });
3619                                 match funding_res {
3620                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3621                                         Err((chan, err)) => {
3622                                                 mem::drop(peer_state_lock);
3623                                                 mem::drop(per_peer_state);
3624
3625                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3626                                                 return Err(APIError::ChannelUnavailable {
3627                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3628                                                 });
3629                                         },
3630                                 }
3631                         },
3632                         Some(phase) => {
3633                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3634                                 return Err(APIError::APIMisuseError {
3635                                         err: format!(
3636                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3637                                                 temporary_channel_id, counterparty_node_id),
3638                                 })
3639                         },
3640                         None => return Err(APIError::ChannelUnavailable {err: format!(
3641                                 "Channel with id {} not found for the passed counterparty node_id {}",
3642                                 temporary_channel_id, counterparty_node_id),
3643                                 }),
3644                 };
3645
3646                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3647                         node_id: chan.context.get_counterparty_node_id(),
3648                         msg,
3649                 });
3650                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3651                         hash_map::Entry::Occupied(_) => {
3652                                 panic!("Generated duplicate funding txid?");
3653                         },
3654                         hash_map::Entry::Vacant(e) => {
3655                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3656                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3657                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3658                                 }
3659                                 e.insert(ChannelPhase::Funded(chan));
3660                         }
3661                 }
3662                 Ok(())
3663         }
3664
3665         #[cfg(test)]
3666         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3667                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3668                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3669                 })
3670         }
3671
3672         /// Call this upon creation of a funding transaction for the given channel.
3673         ///
3674         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3675         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3676         ///
3677         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3678         /// across the p2p network.
3679         ///
3680         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3681         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3682         ///
3683         /// May panic if the output found in the funding transaction is duplicative with some other
3684         /// channel (note that this should be trivially prevented by using unique funding transaction
3685         /// keys per-channel).
3686         ///
3687         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3688         /// counterparty's signature the funding transaction will automatically be broadcast via the
3689         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3690         ///
3691         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3692         /// not currently support replacing a funding transaction on an existing channel. Instead,
3693         /// create a new channel with a conflicting funding transaction.
3694         ///
3695         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3696         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3697         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3698         /// for more details.
3699         ///
3700         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3701         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3702         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3703                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3704         }
3705
3706         /// Call this upon creation of a batch funding transaction for the given channels.
3707         ///
3708         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3709         /// each individual channel and transaction output.
3710         ///
3711         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3712         /// will only be broadcast when we have safely received and persisted the counterparty's
3713         /// signature for each channel.
3714         ///
3715         /// If there is an error, all channels in the batch are to be considered closed.
3716         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3717                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3718                 let mut result = Ok(());
3719
3720                 if !funding_transaction.is_coin_base() {
3721                         for inp in funding_transaction.input.iter() {
3722                                 if inp.witness.is_empty() {
3723                                         result = result.and(Err(APIError::APIMisuseError {
3724                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3725                                         }));
3726                                 }
3727                         }
3728                 }
3729                 if funding_transaction.output.len() > u16::max_value() as usize {
3730                         result = result.and(Err(APIError::APIMisuseError {
3731                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3732                         }));
3733                 }
3734                 {
3735                         let height = self.best_block.read().unwrap().height();
3736                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3737                         // lower than the next block height. However, the modules constituting our Lightning
3738                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3739                         // module is ahead of LDK, only allow one more block of headroom.
3740                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) && LockTime::from(funding_transaction.lock_time).is_block_height() && funding_transaction.lock_time.0 > height + 1 {
3741                                 result = result.and(Err(APIError::APIMisuseError {
3742                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3743                                 }));
3744                         }
3745                 }
3746
3747                 let txid = funding_transaction.txid();
3748                 let is_batch_funding = temporary_channels.len() > 1;
3749                 let mut funding_batch_states = if is_batch_funding {
3750                         Some(self.funding_batch_states.lock().unwrap())
3751                 } else {
3752                         None
3753                 };
3754                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3755                         match states.entry(txid) {
3756                                 btree_map::Entry::Occupied(_) => {
3757                                         result = result.clone().and(Err(APIError::APIMisuseError {
3758                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3759                                         }));
3760                                         None
3761                                 },
3762                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3763                         }
3764                 });
3765                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3766                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3767                                 temporary_channel_id,
3768                                 counterparty_node_id,
3769                                 funding_transaction.clone(),
3770                                 is_batch_funding,
3771                                 |chan, tx| {
3772                                         let mut output_index = None;
3773                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3774                                         for (idx, outp) in tx.output.iter().enumerate() {
3775                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3776                                                         if output_index.is_some() {
3777                                                                 return Err(APIError::APIMisuseError {
3778                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3779                                                                 });
3780                                                         }
3781                                                         output_index = Some(idx as u16);
3782                                                 }
3783                                         }
3784                                         if output_index.is_none() {
3785                                                 return Err(APIError::APIMisuseError {
3786                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3787                                                 });
3788                                         }
3789                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3790                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3791                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3792                                         }
3793                                         Ok(outpoint)
3794                                 })
3795                         );
3796                 }
3797                 if let Err(ref e) = result {
3798                         // Remaining channels need to be removed on any error.
3799                         let e = format!("Error in transaction funding: {:?}", e);
3800                         let mut channels_to_remove = Vec::new();
3801                         channels_to_remove.extend(funding_batch_states.as_mut()
3802                                 .and_then(|states| states.remove(&txid))
3803                                 .into_iter().flatten()
3804                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3805                         );
3806                         channels_to_remove.extend(temporary_channels.iter()
3807                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3808                         );
3809                         let mut shutdown_results = Vec::new();
3810                         {
3811                                 let per_peer_state = self.per_peer_state.read().unwrap();
3812                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3813                                         per_peer_state.get(&counterparty_node_id)
3814                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3815                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3816                                                 .map(|mut chan| {
3817                                                         update_maps_on_chan_removal!(self, &chan.context());
3818                                                         self.issue_channel_close_events(&chan.context(), ClosureReason::ProcessingError { err: e.clone() });
3819                                                         shutdown_results.push(chan.context_mut().force_shutdown(false));
3820                                                 });
3821                                 }
3822                         }
3823                         for shutdown_result in shutdown_results.drain(..) {
3824                                 self.finish_close_channel(shutdown_result);
3825                         }
3826                 }
3827                 result
3828         }
3829
3830         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3831         ///
3832         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3833         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3834         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3835         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3836         ///
3837         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3838         /// `counterparty_node_id` is provided.
3839         ///
3840         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3841         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3842         ///
3843         /// If an error is returned, none of the updates should be considered applied.
3844         ///
3845         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3846         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3847         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3848         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3849         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3850         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3851         /// [`APIMisuseError`]: APIError::APIMisuseError
3852         pub fn update_partial_channel_config(
3853                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
3854         ) -> Result<(), APIError> {
3855                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
3856                         return Err(APIError::APIMisuseError {
3857                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
3858                         });
3859                 }
3860
3861                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3862                 let per_peer_state = self.per_peer_state.read().unwrap();
3863                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3864                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3865                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3866                 let peer_state = &mut *peer_state_lock;
3867                 for channel_id in channel_ids {
3868                         if !peer_state.has_channel(channel_id) {
3869                                 return Err(APIError::ChannelUnavailable {
3870                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
3871                                 });
3872                         };
3873                 }
3874                 for channel_id in channel_ids {
3875                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
3876                                 let mut config = channel_phase.context().config();
3877                                 config.apply(config_update);
3878                                 if !channel_phase.context_mut().update_config(&config) {
3879                                         continue;
3880                                 }
3881                                 if let ChannelPhase::Funded(channel) = channel_phase {
3882                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
3883                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
3884                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
3885                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
3886                                                         node_id: channel.context.get_counterparty_node_id(),
3887                                                         msg,
3888                                                 });
3889                                         }
3890                                 }
3891                                 continue;
3892                         } else {
3893                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
3894                                 debug_assert!(false);
3895                                 return Err(APIError::ChannelUnavailable {
3896                                         err: format!(
3897                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
3898                                                 channel_id, counterparty_node_id),
3899                                 });
3900                         };
3901                 }
3902                 Ok(())
3903         }
3904
3905         /// Atomically updates the [`ChannelConfig`] for the given channels.
3906         ///
3907         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3908         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3909         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3910         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3911         ///
3912         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3913         /// `counterparty_node_id` is provided.
3914         ///
3915         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3916         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3917         ///
3918         /// If an error is returned, none of the updates should be considered applied.
3919         ///
3920         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3921         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3922         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3923         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3924         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3925         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3926         /// [`APIMisuseError`]: APIError::APIMisuseError
3927         pub fn update_channel_config(
3928                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
3929         ) -> Result<(), APIError> {
3930                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
3931         }
3932
3933         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
3934         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
3935         ///
3936         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
3937         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
3938         ///
3939         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
3940         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
3941         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
3942         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
3943         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
3944         ///
3945         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
3946         /// you from forwarding more than you received. See
3947         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
3948         /// than expected.
3949         ///
3950         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3951         /// backwards.
3952         ///
3953         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
3954         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3955         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
3956         // TODO: when we move to deciding the best outbound channel at forward time, only take
3957         // `next_node_id` and not `next_hop_channel_id`
3958         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> {
3959                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3960
3961                 let next_hop_scid = {
3962                         let peer_state_lock = self.per_peer_state.read().unwrap();
3963                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
3964                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
3965                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3966                         let peer_state = &mut *peer_state_lock;
3967                         match peer_state.channel_by_id.get(next_hop_channel_id) {
3968                                 Some(ChannelPhase::Funded(chan)) => {
3969                                         if !chan.context.is_usable() {
3970                                                 return Err(APIError::ChannelUnavailable {
3971                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
3972                                                 })
3973                                         }
3974                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
3975                                 },
3976                                 Some(_) => return Err(APIError::ChannelUnavailable {
3977                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
3978                                                 next_hop_channel_id, next_node_id)
3979                                 }),
3980                                 None => return Err(APIError::ChannelUnavailable {
3981                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}",
3982                                                 next_hop_channel_id, next_node_id)
3983                                 })
3984                         }
3985                 };
3986
3987                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3988                         .ok_or_else(|| APIError::APIMisuseError {
3989                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3990                         })?;
3991
3992                 let routing = match payment.forward_info.routing {
3993                         PendingHTLCRouting::Forward { onion_packet, .. } => {
3994                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
3995                         },
3996                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
3997                 };
3998                 let skimmed_fee_msat =
3999                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4000                 let pending_htlc_info = PendingHTLCInfo {
4001                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4002                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4003                 };
4004
4005                 let mut per_source_pending_forward = [(
4006                         payment.prev_short_channel_id,
4007                         payment.prev_funding_outpoint,
4008                         payment.prev_user_channel_id,
4009                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4010                 )];
4011                 self.forward_htlcs(&mut per_source_pending_forward);
4012                 Ok(())
4013         }
4014
4015         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4016         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4017         ///
4018         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4019         /// backwards.
4020         ///
4021         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4022         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4023                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4024
4025                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4026                         .ok_or_else(|| APIError::APIMisuseError {
4027                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4028                         })?;
4029
4030                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4031                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4032                                 short_channel_id: payment.prev_short_channel_id,
4033                                 user_channel_id: Some(payment.prev_user_channel_id),
4034                                 outpoint: payment.prev_funding_outpoint,
4035                                 htlc_id: payment.prev_htlc_id,
4036                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4037                                 phantom_shared_secret: None,
4038                         });
4039
4040                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4041                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4042                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4043                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4044
4045                 Ok(())
4046         }
4047
4048         /// Processes HTLCs which are pending waiting on random forward delay.
4049         ///
4050         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4051         /// Will likely generate further events.
4052         pub fn process_pending_htlc_forwards(&self) {
4053                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4054
4055                 let mut new_events = VecDeque::new();
4056                 let mut failed_forwards = Vec::new();
4057                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4058                 {
4059                         let mut forward_htlcs = HashMap::new();
4060                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4061
4062                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4063                                 if short_chan_id != 0 {
4064                                         macro_rules! forwarding_channel_not_found {
4065                                                 () => {
4066                                                         for forward_info in pending_forwards.drain(..) {
4067                                                                 match forward_info {
4068                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4069                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4070                                                                                 forward_info: PendingHTLCInfo {
4071                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4072                                                                                         outgoing_cltv_value, ..
4073                                                                                 }
4074                                                                         }) => {
4075                                                                                 macro_rules! failure_handler {
4076                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4077                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4078
4079                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4080                                                                                                         short_channel_id: prev_short_channel_id,
4081                                                                                                         user_channel_id: Some(prev_user_channel_id),
4082                                                                                                         outpoint: prev_funding_outpoint,
4083                                                                                                         htlc_id: prev_htlc_id,
4084                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4085                                                                                                         phantom_shared_secret: $phantom_ss,
4086                                                                                                 });
4087
4088                                                                                                 let reason = if $next_hop_unknown {
4089                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4090                                                                                                 } else {
4091                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4092                                                                                                 };
4093
4094                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4095                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4096                                                                                                         reason
4097                                                                                                 ));
4098                                                                                                 continue;
4099                                                                                         }
4100                                                                                 }
4101                                                                                 macro_rules! fail_forward {
4102                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4103                                                                                                 {
4104                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4105                                                                                                 }
4106                                                                                         }
4107                                                                                 }
4108                                                                                 macro_rules! failed_payment {
4109                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4110                                                                                                 {
4111                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4112                                                                                                 }
4113                                                                                         }
4114                                                                                 }
4115                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
4116                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4117                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4118                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4119                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4120                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4121                                                                                                         payment_hash, &self.node_signer
4122                                                                                                 ) {
4123                                                                                                         Ok(res) => res,
4124                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4125                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
4126                                                                                                                 // In this scenario, the phantom would have sent us an
4127                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4128                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4129                                                                                                                 // of the onion.
4130                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4131                                                                                                         },
4132                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4133                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4134                                                                                                         },
4135                                                                                                 };
4136                                                                                                 match next_hop {
4137                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4138                                                                                                                 let current_height: u32 = self.best_block.read().unwrap().height();
4139                                                                                                                 match create_recv_pending_htlc_info(hop_data,
4140                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4141                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None,
4142                                                                                                                         current_height, self.default_configuration.accept_mpp_keysend)
4143                                                                                                                 {
4144                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4145                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4146                                                                                                                 }
4147                                                                                                         },
4148                                                                                                         _ => panic!(),
4149                                                                                                 }
4150                                                                                         } else {
4151                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4152                                                                                         }
4153                                                                                 } else {
4154                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4155                                                                                 }
4156                                                                         },
4157                                                                         HTLCForwardInfo::FailHTLC { .. } => {
4158                                                                                 // Channel went away before we could fail it. This implies
4159                                                                                 // the channel is now on chain and our counterparty is
4160                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4161                                                                                 // problem, not ours.
4162                                                                         }
4163                                                                 }
4164                                                         }
4165                                                 }
4166                                         }
4167                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4168                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4169                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4170                                                 None => {
4171                                                         forwarding_channel_not_found!();
4172                                                         continue;
4173                                                 }
4174                                         };
4175                                         let per_peer_state = self.per_peer_state.read().unwrap();
4176                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4177                                         if peer_state_mutex_opt.is_none() {
4178                                                 forwarding_channel_not_found!();
4179                                                 continue;
4180                                         }
4181                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4182                                         let peer_state = &mut *peer_state_lock;
4183                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4184                                                 for forward_info in pending_forwards.drain(..) {
4185                                                         match forward_info {
4186                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4187                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4188                                                                         forward_info: PendingHTLCInfo {
4189                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4190                                                                                 routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
4191                                                                         },
4192                                                                 }) => {
4193                                                                         log_trace!(self.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);
4194                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4195                                                                                 short_channel_id: prev_short_channel_id,
4196                                                                                 user_channel_id: Some(prev_user_channel_id),
4197                                                                                 outpoint: prev_funding_outpoint,
4198                                                                                 htlc_id: prev_htlc_id,
4199                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4200                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4201                                                                                 phantom_shared_secret: None,
4202                                                                         });
4203                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4204                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4205                                                                                 onion_packet, skimmed_fee_msat, &self.fee_estimator,
4206                                                                                 &self.logger)
4207                                                                         {
4208                                                                                 if let ChannelError::Ignore(msg) = e {
4209                                                                                         log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4210                                                                                 } else {
4211                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4212                                                                                 }
4213                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4214                                                                                 failed_forwards.push((htlc_source, payment_hash,
4215                                                                                         HTLCFailReason::reason(failure_code, data),
4216                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4217                                                                                 ));
4218                                                                                 continue;
4219                                                                         }
4220                                                                 },
4221                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4222                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4223                                                                 },
4224                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4225                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4226                                                                         if let Err(e) = chan.queue_fail_htlc(
4227                                                                                 htlc_id, err_packet, &self.logger
4228                                                                         ) {
4229                                                                                 if let ChannelError::Ignore(msg) = e {
4230                                                                                         log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4231                                                                                 } else {
4232                                                                                         panic!("Stated return value requirements in queue_fail_htlc() were not met");
4233                                                                                 }
4234                                                                                 // fail-backs are best-effort, we probably already have one
4235                                                                                 // pending, and if not that's OK, if not, the channel is on
4236                                                                                 // the chain and sending the HTLC-Timeout is their problem.
4237                                                                                 continue;
4238                                                                         }
4239                                                                 },
4240                                                         }
4241                                                 }
4242                                         } else {
4243                                                 forwarding_channel_not_found!();
4244                                                 continue;
4245                                         }
4246                                 } else {
4247                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4248                                                 match forward_info {
4249                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4250                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4251                                                                 forward_info: PendingHTLCInfo {
4252                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4253                                                                         skimmed_fee_msat, ..
4254                                                                 }
4255                                                         }) => {
4256                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4257                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4258                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4259                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4260                                                                                                 payment_metadata, custom_tlvs };
4261                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4262                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4263                                                                         },
4264                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4265                                                                                 let onion_fields = RecipientOnionFields {
4266                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4267                                                                                         payment_metadata,
4268                                                                                         custom_tlvs,
4269                                                                                 };
4270                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4271                                                                                         payment_data, None, onion_fields)
4272                                                                         },
4273                                                                         _ => {
4274                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4275                                                                         }
4276                                                                 };
4277                                                                 let claimable_htlc = ClaimableHTLC {
4278                                                                         prev_hop: HTLCPreviousHopData {
4279                                                                                 short_channel_id: prev_short_channel_id,
4280                                                                                 user_channel_id: Some(prev_user_channel_id),
4281                                                                                 outpoint: prev_funding_outpoint,
4282                                                                                 htlc_id: prev_htlc_id,
4283                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4284                                                                                 phantom_shared_secret,
4285                                                                         },
4286                                                                         // We differentiate the received value from the sender intended value
4287                                                                         // if possible so that we don't prematurely mark MPP payments complete
4288                                                                         // if routing nodes overpay
4289                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4290                                                                         sender_intended_value: outgoing_amt_msat,
4291                                                                         timer_ticks: 0,
4292                                                                         total_value_received: None,
4293                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4294                                                                         cltv_expiry,
4295                                                                         onion_payload,
4296                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4297                                                                 };
4298
4299                                                                 let mut committed_to_claimable = false;
4300
4301                                                                 macro_rules! fail_htlc {
4302                                                                         ($htlc: expr, $payment_hash: expr) => {
4303                                                                                 debug_assert!(!committed_to_claimable);
4304                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4305                                                                                 htlc_msat_height_data.extend_from_slice(
4306                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4307                                                                                 );
4308                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4309                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4310                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4311                                                                                                 outpoint: prev_funding_outpoint,
4312                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4313                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4314                                                                                                 phantom_shared_secret,
4315                                                                                         }), payment_hash,
4316                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4317                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4318                                                                                 ));
4319                                                                                 continue 'next_forwardable_htlc;
4320                                                                         }
4321                                                                 }
4322                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4323                                                                 let mut receiver_node_id = self.our_network_pubkey;
4324                                                                 if phantom_shared_secret.is_some() {
4325                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4326                                                                                 .expect("Failed to get node_id for phantom node recipient");
4327                                                                 }
4328
4329                                                                 macro_rules! check_total_value {
4330                                                                         ($purpose: expr) => {{
4331                                                                                 let mut payment_claimable_generated = false;
4332                                                                                 let is_keysend = match $purpose {
4333                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4334                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4335                                                                                 };
4336                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4337                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4338                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4339                                                                                 }
4340                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4341                                                                                         .entry(payment_hash)
4342                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4343                                                                                         .or_insert_with(|| {
4344                                                                                                 committed_to_claimable = true;
4345                                                                                                 ClaimablePayment {
4346                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4347                                                                                                 }
4348                                                                                         });
4349                                                                                 if $purpose != claimable_payment.purpose {
4350                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4351                                                                                         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));
4352                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4353                                                                                 }
4354                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4355                                                                                         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);
4356                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4357                                                                                 }
4358                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4359                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4360                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4361                                                                                         }
4362                                                                                 } else {
4363                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4364                                                                                 }
4365                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4366                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4367                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4368                                                                                 for htlc in htlcs.iter() {
4369                                                                                         total_value += htlc.sender_intended_value;
4370                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4371                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4372                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4373                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4374                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4375                                                                                         }
4376                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4377                                                                                 }
4378                                                                                 // The condition determining whether an MPP is complete must
4379                                                                                 // match exactly the condition used in `timer_tick_occurred`
4380                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4381                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4382                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4383                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4384                                                                                                 &payment_hash);
4385                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4386                                                                                 } else if total_value >= claimable_htlc.total_msat {
4387                                                                                         #[allow(unused_assignments)] {
4388                                                                                                 committed_to_claimable = true;
4389                                                                                         }
4390                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4391                                                                                         htlcs.push(claimable_htlc);
4392                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4393                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4394                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4395                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4396                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4397                                                                                                 counterparty_skimmed_fee_msat);
4398                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4399                                                                                                 receiver_node_id: Some(receiver_node_id),
4400                                                                                                 payment_hash,
4401                                                                                                 purpose: $purpose,
4402                                                                                                 amount_msat,
4403                                                                                                 counterparty_skimmed_fee_msat,
4404                                                                                                 via_channel_id: Some(prev_channel_id),
4405                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4406                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4407                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4408                                                                                         }, None));
4409                                                                                         payment_claimable_generated = true;
4410                                                                                 } else {
4411                                                                                         // Nothing to do - we haven't reached the total
4412                                                                                         // payment value yet, wait until we receive more
4413                                                                                         // MPP parts.
4414                                                                                         htlcs.push(claimable_htlc);
4415                                                                                         #[allow(unused_assignments)] {
4416                                                                                                 committed_to_claimable = true;
4417                                                                                         }
4418                                                                                 }
4419                                                                                 payment_claimable_generated
4420                                                                         }}
4421                                                                 }
4422
4423                                                                 // Check that the payment hash and secret are known. Note that we
4424                                                                 // MUST take care to handle the "unknown payment hash" and
4425                                                                 // "incorrect payment secret" cases here identically or we'd expose
4426                                                                 // that we are the ultimate recipient of the given payment hash.
4427                                                                 // Further, we must not expose whether we have any other HTLCs
4428                                                                 // associated with the same payment_hash pending or not.
4429                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4430                                                                 match payment_secrets.entry(payment_hash) {
4431                                                                         hash_map::Entry::Vacant(_) => {
4432                                                                                 match claimable_htlc.onion_payload {
4433                                                                                         OnionPayload::Invoice { .. } => {
4434                                                                                                 let payment_data = payment_data.unwrap();
4435                                                                                                 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) {
4436                                                                                                         Ok(result) => result,
4437                                                                                                         Err(()) => {
4438                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4439                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4440                                                                                                         }
4441                                                                                                 };
4442                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4443                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4444                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4445                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4446                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4447                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4448                                                                                                         }
4449                                                                                                 }
4450                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4451                                                                                                         payment_preimage: payment_preimage.clone(),
4452                                                                                                         payment_secret: payment_data.payment_secret,
4453                                                                                                 };
4454                                                                                                 check_total_value!(purpose);
4455                                                                                         },
4456                                                                                         OnionPayload::Spontaneous(preimage) => {
4457                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4458                                                                                                 check_total_value!(purpose);
4459                                                                                         }
4460                                                                                 }
4461                                                                         },
4462                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4463                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4464                                                                                         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);
4465                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4466                                                                                 }
4467                                                                                 let payment_data = payment_data.unwrap();
4468                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4469                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4470                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4471                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4472                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4473                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4474                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4475                                                                                 } else {
4476                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4477                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4478                                                                                                 payment_secret: payment_data.payment_secret,
4479                                                                                         };
4480                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4481                                                                                         if payment_claimable_generated {
4482                                                                                                 inbound_payment.remove_entry();
4483                                                                                         }
4484                                                                                 }
4485                                                                         },
4486                                                                 };
4487                                                         },
4488                                                         HTLCForwardInfo::FailHTLC { .. } => {
4489                                                                 panic!("Got pending fail of our own HTLC");
4490                                                         }
4491                                                 }
4492                                         }
4493                                 }
4494                         }
4495                 }
4496
4497                 let best_block_height = self.best_block.read().unwrap().height();
4498                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4499                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4500                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4501
4502                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4503                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4504                 }
4505                 self.forward_htlcs(&mut phantom_receives);
4506
4507                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4508                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4509                 // nice to do the work now if we can rather than while we're trying to get messages in the
4510                 // network stack.
4511                 self.check_free_holding_cells();
4512
4513                 if new_events.is_empty() { return }
4514                 let mut events = self.pending_events.lock().unwrap();
4515                 events.append(&mut new_events);
4516         }
4517
4518         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4519         ///
4520         /// Expects the caller to have a total_consistency_lock read lock.
4521         fn process_background_events(&self) -> NotifyOption {
4522                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4523
4524                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4525
4526                 let mut background_events = Vec::new();
4527                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4528                 if background_events.is_empty() {
4529                         return NotifyOption::SkipPersistNoEvents;
4530                 }
4531
4532                 for event in background_events.drain(..) {
4533                         match event {
4534                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4535                                         // The channel has already been closed, so no use bothering to care about the
4536                                         // monitor updating completing.
4537                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4538                                 },
4539                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4540                                         let mut updated_chan = false;
4541                                         {
4542                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4543                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4544                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4545                                                         let peer_state = &mut *peer_state_lock;
4546                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4547                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4548                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4549                                                                                 updated_chan = true;
4550                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4551                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4552                                                                         } else {
4553                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4554                                                                         }
4555                                                                 },
4556                                                                 hash_map::Entry::Vacant(_) => {},
4557                                                         }
4558                                                 }
4559                                         }
4560                                         if !updated_chan {
4561                                                 // TODO: Track this as in-flight even though the channel is closed.
4562                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4563                                         }
4564                                 },
4565                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4566                                         let per_peer_state = self.per_peer_state.read().unwrap();
4567                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4568                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4569                                                 let peer_state = &mut *peer_state_lock;
4570                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4571                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4572                                                 } else {
4573                                                         let update_actions = peer_state.monitor_update_blocked_actions
4574                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4575                                                         mem::drop(peer_state_lock);
4576                                                         mem::drop(per_peer_state);
4577                                                         self.handle_monitor_update_completion_actions(update_actions);
4578                                                 }
4579                                         }
4580                                 },
4581                         }
4582                 }
4583                 NotifyOption::DoPersist
4584         }
4585
4586         #[cfg(any(test, feature = "_test_utils"))]
4587         /// Process background events, for functional testing
4588         pub fn test_process_background_events(&self) {
4589                 let _lck = self.total_consistency_lock.read().unwrap();
4590                 let _ = self.process_background_events();
4591         }
4592
4593         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4594                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4595                 // If the feerate has decreased by less than half, don't bother
4596                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4597                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4598                                 log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4599                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4600                         }
4601                         return NotifyOption::SkipPersistNoEvents;
4602                 }
4603                 if !chan.context.is_live() {
4604                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
4605                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4606                         return NotifyOption::SkipPersistNoEvents;
4607                 }
4608                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4609                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4610
4611                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4612                 NotifyOption::DoPersist
4613         }
4614
4615         #[cfg(fuzzing)]
4616         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4617         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4618         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4619         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4620         pub fn maybe_update_chan_fees(&self) {
4621                 PersistenceNotifierGuard::optionally_notify(self, || {
4622                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4623
4624                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4625                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4626
4627                         let per_peer_state = self.per_peer_state.read().unwrap();
4628                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4629                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4630                                 let peer_state = &mut *peer_state_lock;
4631                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4632                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4633                                 ) {
4634                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4635                                                 anchor_feerate
4636                                         } else {
4637                                                 non_anchor_feerate
4638                                         };
4639                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4640                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4641                                 }
4642                         }
4643
4644                         should_persist
4645                 });
4646         }
4647
4648         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4649         ///
4650         /// This currently includes:
4651         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4652         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4653         ///    than a minute, informing the network that they should no longer attempt to route over
4654         ///    the channel.
4655         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4656         ///    with the current [`ChannelConfig`].
4657         ///  * Removing peers which have disconnected but and no longer have any channels.
4658         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4659         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4660         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4661         ///    The latter is determined using the system clock in `std` and the highest seen block time
4662         ///    minus two hours in `no-std`.
4663         ///
4664         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4665         /// estimate fetches.
4666         ///
4667         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4668         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4669         pub fn timer_tick_occurred(&self) {
4670                 PersistenceNotifierGuard::optionally_notify(self, || {
4671                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4672
4673                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4674                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4675
4676                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4677                         let mut timed_out_mpp_htlcs = Vec::new();
4678                         let mut pending_peers_awaiting_removal = Vec::new();
4679                         let mut shutdown_channels = Vec::new();
4680
4681                         let mut process_unfunded_channel_tick = |
4682                                 chan_id: &ChannelId,
4683                                 context: &mut ChannelContext<SP>,
4684                                 unfunded_context: &mut UnfundedChannelContext,
4685                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4686                                 counterparty_node_id: PublicKey,
4687                         | {
4688                                 context.maybe_expire_prev_config();
4689                                 if unfunded_context.should_expire_unfunded_channel() {
4690                                         log_error!(self.logger,
4691                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4692                                         update_maps_on_chan_removal!(self, &context);
4693                                         self.issue_channel_close_events(&context, ClosureReason::HolderForceClosed);
4694                                         shutdown_channels.push(context.force_shutdown(false));
4695                                         pending_msg_events.push(MessageSendEvent::HandleError {
4696                                                 node_id: counterparty_node_id,
4697                                                 action: msgs::ErrorAction::SendErrorMessage {
4698                                                         msg: msgs::ErrorMessage {
4699                                                                 channel_id: *chan_id,
4700                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4701                                                         },
4702                                                 },
4703                                         });
4704                                         false
4705                                 } else {
4706                                         true
4707                                 }
4708                         };
4709
4710                         {
4711                                 let per_peer_state = self.per_peer_state.read().unwrap();
4712                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4713                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4714                                         let peer_state = &mut *peer_state_lock;
4715                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4716                                         let counterparty_node_id = *counterparty_node_id;
4717                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4718                                                 match phase {
4719                                                         ChannelPhase::Funded(chan) => {
4720                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4721                                                                         anchor_feerate
4722                                                                 } else {
4723                                                                         non_anchor_feerate
4724                                                                 };
4725                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4726                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4727
4728                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4729                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4730                                                                         handle_errors.push((Err(err), counterparty_node_id));
4731                                                                         if needs_close { return false; }
4732                                                                 }
4733
4734                                                                 match chan.channel_update_status() {
4735                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4736                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4737                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4738                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4739                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4740                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4741                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4742                                                                                 n += 1;
4743                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4744                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4745                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4746                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4747                                                                                                         msg: update
4748                                                                                                 });
4749                                                                                         }
4750                                                                                         should_persist = NotifyOption::DoPersist;
4751                                                                                 } else {
4752                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4753                                                                                 }
4754                                                                         },
4755                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4756                                                                                 n += 1;
4757                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4758                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4759                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4760                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4761                                                                                                         msg: update
4762                                                                                                 });
4763                                                                                         }
4764                                                                                         should_persist = NotifyOption::DoPersist;
4765                                                                                 } else {
4766                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4767                                                                                 }
4768                                                                         },
4769                                                                         _ => {},
4770                                                                 }
4771
4772                                                                 chan.context.maybe_expire_prev_config();
4773
4774                                                                 if chan.should_disconnect_peer_awaiting_response() {
4775                                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4776                                                                                         counterparty_node_id, chan_id);
4777                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4778                                                                                 node_id: counterparty_node_id,
4779                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4780                                                                                         msg: msgs::WarningMessage {
4781                                                                                                 channel_id: *chan_id,
4782                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4783                                                                                         },
4784                                                                                 },
4785                                                                         });
4786                                                                 }
4787
4788                                                                 true
4789                                                         },
4790                                                         ChannelPhase::UnfundedInboundV1(chan) => {
4791                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4792                                                                         pending_msg_events, counterparty_node_id)
4793                                                         },
4794                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
4795                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4796                                                                         pending_msg_events, counterparty_node_id)
4797                                                         },
4798                                                 }
4799                                         });
4800
4801                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4802                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4803                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
4804                                                         peer_state.pending_msg_events.push(
4805                                                                 events::MessageSendEvent::HandleError {
4806                                                                         node_id: counterparty_node_id,
4807                                                                         action: msgs::ErrorAction::SendErrorMessage {
4808                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4809                                                                         },
4810                                                                 }
4811                                                         );
4812                                                 }
4813                                         }
4814                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4815
4816                                         if peer_state.ok_to_remove(true) {
4817                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4818                                         }
4819                                 }
4820                         }
4821
4822                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4823                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4824                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4825                         // we therefore need to remove the peer from `peer_state` separately.
4826                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4827                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4828                         // negative effects on parallelism as much as possible.
4829                         if pending_peers_awaiting_removal.len() > 0 {
4830                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4831                                 for counterparty_node_id in pending_peers_awaiting_removal {
4832                                         match per_peer_state.entry(counterparty_node_id) {
4833                                                 hash_map::Entry::Occupied(entry) => {
4834                                                         // Remove the entry if the peer is still disconnected and we still
4835                                                         // have no channels to the peer.
4836                                                         let remove_entry = {
4837                                                                 let peer_state = entry.get().lock().unwrap();
4838                                                                 peer_state.ok_to_remove(true)
4839                                                         };
4840                                                         if remove_entry {
4841                                                                 entry.remove_entry();
4842                                                         }
4843                                                 },
4844                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
4845                                         }
4846                                 }
4847                         }
4848
4849                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
4850                                 if payment.htlcs.is_empty() {
4851                                         // This should be unreachable
4852                                         debug_assert!(false);
4853                                         return false;
4854                                 }
4855                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
4856                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
4857                                         // In this case we're not going to handle any timeouts of the parts here.
4858                                         // This condition determining whether the MPP is complete here must match
4859                                         // exactly the condition used in `process_pending_htlc_forwards`.
4860                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
4861                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
4862                                         {
4863                                                 return true;
4864                                         } else if payment.htlcs.iter_mut().any(|htlc| {
4865                                                 htlc.timer_ticks += 1;
4866                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
4867                                         }) {
4868                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
4869                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
4870                                                 return false;
4871                                         }
4872                                 }
4873                                 true
4874                         });
4875
4876                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
4877                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
4878                                 let reason = HTLCFailReason::from_failure_code(23);
4879                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
4880                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
4881                         }
4882
4883                         for (err, counterparty_node_id) in handle_errors.drain(..) {
4884                                 let _ = handle_error!(self, err, counterparty_node_id);
4885                         }
4886
4887                         for shutdown_res in shutdown_channels {
4888                                 self.finish_close_channel(shutdown_res);
4889                         }
4890
4891                         #[cfg(feature = "std")]
4892                         let duration_since_epoch = std::time::SystemTime::now()
4893                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
4894                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
4895                         #[cfg(not(feature = "std"))]
4896                         let duration_since_epoch = Duration::from_secs(
4897                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
4898                         );
4899
4900                         self.pending_outbound_payments.remove_stale_payments(
4901                                 duration_since_epoch, &self.pending_events
4902                         );
4903
4904                         // Technically we don't need to do this here, but if we have holding cell entries in a
4905                         // channel that need freeing, it's better to do that here and block a background task
4906                         // than block the message queueing pipeline.
4907                         if self.check_free_holding_cells() {
4908                                 should_persist = NotifyOption::DoPersist;
4909                         }
4910
4911                         should_persist
4912                 });
4913         }
4914
4915         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
4916         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
4917         /// along the path (including in our own channel on which we received it).
4918         ///
4919         /// Note that in some cases around unclean shutdown, it is possible the payment may have
4920         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
4921         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
4922         /// may have already been failed automatically by LDK if it was nearing its expiration time.
4923         ///
4924         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
4925         /// [`ChannelManager::claim_funds`]), you should still monitor for
4926         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
4927         /// startup during which time claims that were in-progress at shutdown may be replayed.
4928         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
4929                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
4930         }
4931
4932         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
4933         /// reason for the failure.
4934         ///
4935         /// See [`FailureCode`] for valid failure codes.
4936         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
4937                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4938
4939                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
4940                 if let Some(payment) = removed_source {
4941                         for htlc in payment.htlcs {
4942                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
4943                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4944                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
4945                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4946                         }
4947                 }
4948         }
4949
4950         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
4951         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
4952                 match failure_code {
4953                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
4954                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
4955                         FailureCode::IncorrectOrUnknownPaymentDetails => {
4956                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4957                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4958                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
4959                         },
4960                         FailureCode::InvalidOnionPayload(data) => {
4961                                 let fail_data = match data {
4962                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
4963                                         None => Vec::new(),
4964                                 };
4965                                 HTLCFailReason::reason(failure_code.into(), fail_data)
4966                         }
4967                 }
4968         }
4969
4970         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4971         /// that we want to return and a channel.
4972         ///
4973         /// This is for failures on the channel on which the HTLC was *received*, not failures
4974         /// forwarding
4975         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
4976                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
4977                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
4978                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
4979                 // an inbound SCID alias before the real SCID.
4980                 let scid_pref = if chan.context.should_announce() {
4981                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
4982                 } else {
4983                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
4984                 };
4985                 if let Some(scid) = scid_pref {
4986                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
4987                 } else {
4988                         (0x4000|10, Vec::new())
4989                 }
4990         }
4991
4992
4993         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4994         /// that we want to return and a channel.
4995         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
4996                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
4997                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
4998                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
4999                         if desired_err_code == 0x1000 | 20 {
5000                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5001                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5002                                 0u16.write(&mut enc).expect("Writes cannot fail");
5003                         }
5004                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5005                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5006                         upd.write(&mut enc).expect("Writes cannot fail");
5007                         (desired_err_code, enc.0)
5008                 } else {
5009                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5010                         // which means we really shouldn't have gotten a payment to be forwarded over this
5011                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5012                         // PERM|no_such_channel should be fine.
5013                         (0x4000|10, Vec::new())
5014                 }
5015         }
5016
5017         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5018         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5019         // be surfaced to the user.
5020         fn fail_holding_cell_htlcs(
5021                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5022                 counterparty_node_id: &PublicKey
5023         ) {
5024                 let (failure_code, onion_failure_data) = {
5025                         let per_peer_state = self.per_peer_state.read().unwrap();
5026                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5027                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5028                                 let peer_state = &mut *peer_state_lock;
5029                                 match peer_state.channel_by_id.entry(channel_id) {
5030                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5031                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5032                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5033                                                 } else {
5034                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5035                                                         debug_assert!(false);
5036                                                         (0x4000|10, Vec::new())
5037                                                 }
5038                                         },
5039                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5040                                 }
5041                         } else { (0x4000|10, Vec::new()) }
5042                 };
5043
5044                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5045                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5046                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5047                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5048                 }
5049         }
5050
5051         /// Fails an HTLC backwards to the sender of it to us.
5052         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5053         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5054                 // Ensure that no peer state channel storage lock is held when calling this function.
5055                 // This ensures that future code doesn't introduce a lock-order requirement for
5056                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5057                 // this function with any `per_peer_state` peer lock acquired would.
5058                 #[cfg(debug_assertions)]
5059                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5060                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5061                 }
5062
5063                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5064                 //identify whether we sent it or not based on the (I presume) very different runtime
5065                 //between the branches here. We should make this async and move it into the forward HTLCs
5066                 //timer handling.
5067
5068                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5069                 // from block_connected which may run during initialization prior to the chain_monitor
5070                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5071                 match source {
5072                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5073                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5074                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5075                                         &self.pending_events, &self.logger)
5076                                 { self.push_pending_forwards_ev(); }
5077                         },
5078                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint, .. }) => {
5079                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", &payment_hash, onion_error);
5080                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
5081
5082                                 let mut push_forward_ev = false;
5083                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5084                                 if forward_htlcs.is_empty() {
5085                                         push_forward_ev = true;
5086                                 }
5087                                 match forward_htlcs.entry(*short_channel_id) {
5088                                         hash_map::Entry::Occupied(mut entry) => {
5089                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
5090                                         },
5091                                         hash_map::Entry::Vacant(entry) => {
5092                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
5093                                         }
5094                                 }
5095                                 mem::drop(forward_htlcs);
5096                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5097                                 let mut pending_events = self.pending_events.lock().unwrap();
5098                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5099                                         prev_channel_id: outpoint.to_channel_id(),
5100                                         failed_next_destination: destination,
5101                                 }, None));
5102                         },
5103                 }
5104         }
5105
5106         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5107         /// [`MessageSendEvent`]s needed to claim the payment.
5108         ///
5109         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5110         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5111         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5112         /// successful. It will generally be available in the next [`process_pending_events`] call.
5113         ///
5114         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5115         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5116         /// event matches your expectation. If you fail to do so and call this method, you may provide
5117         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5118         ///
5119         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5120         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5121         /// [`claim_funds_with_known_custom_tlvs`].
5122         ///
5123         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5124         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5125         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5126         /// [`process_pending_events`]: EventsProvider::process_pending_events
5127         /// [`create_inbound_payment`]: Self::create_inbound_payment
5128         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5129         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5130         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5131                 self.claim_payment_internal(payment_preimage, false);
5132         }
5133
5134         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5135         /// even type numbers.
5136         ///
5137         /// # Note
5138         ///
5139         /// You MUST check you've understood all even TLVs before using this to
5140         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5141         ///
5142         /// [`claim_funds`]: Self::claim_funds
5143         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5144                 self.claim_payment_internal(payment_preimage, true);
5145         }
5146
5147         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5148                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5149
5150                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5151
5152                 let mut sources = {
5153                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5154                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5155                                 let mut receiver_node_id = self.our_network_pubkey;
5156                                 for htlc in payment.htlcs.iter() {
5157                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5158                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5159                                                         .expect("Failed to get node_id for phantom node recipient");
5160                                                 receiver_node_id = phantom_pubkey;
5161                                                 break;
5162                                         }
5163                                 }
5164
5165                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5166                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5167                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5168                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5169                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5170                                 });
5171                                 if dup_purpose.is_some() {
5172                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5173                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5174                                                 &payment_hash);
5175                                 }
5176
5177                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5178                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5179                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5180                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5181                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5182                                                 mem::drop(claimable_payments);
5183                                                 for htlc in payment.htlcs {
5184                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5185                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5186                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5187                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5188                                                 }
5189                                                 return;
5190                                         }
5191                                 }
5192
5193                                 payment.htlcs
5194                         } else { return; }
5195                 };
5196                 debug_assert!(!sources.is_empty());
5197
5198                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5199                 // and when we got here we need to check that the amount we're about to claim matches the
5200                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5201                 // the MPP parts all have the same `total_msat`.
5202                 let mut claimable_amt_msat = 0;
5203                 let mut prev_total_msat = None;
5204                 let mut expected_amt_msat = None;
5205                 let mut valid_mpp = true;
5206                 let mut errs = Vec::new();
5207                 let per_peer_state = self.per_peer_state.read().unwrap();
5208                 for htlc in sources.iter() {
5209                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5210                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5211                                 debug_assert!(false);
5212                                 valid_mpp = false;
5213                                 break;
5214                         }
5215                         prev_total_msat = Some(htlc.total_msat);
5216
5217                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5218                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5219                                 debug_assert!(false);
5220                                 valid_mpp = false;
5221                                 break;
5222                         }
5223                         expected_amt_msat = htlc.total_value_received;
5224                         claimable_amt_msat += htlc.value;
5225                 }
5226                 mem::drop(per_peer_state);
5227                 if sources.is_empty() || expected_amt_msat.is_none() {
5228                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5229                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5230                         return;
5231                 }
5232                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5233                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5234                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5235                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5236                         return;
5237                 }
5238                 if valid_mpp {
5239                         for htlc in sources.drain(..) {
5240                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5241                                         htlc.prev_hop, payment_preimage,
5242                                         |_, definitely_duplicate| {
5243                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5244                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5245                                         }
5246                                 ) {
5247                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5248                                                 // We got a temporary failure updating monitor, but will claim the
5249                                                 // HTLC when the monitor updating is restored (or on chain).
5250                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5251                                         } else { errs.push((pk, err)); }
5252                                 }
5253                         }
5254                 }
5255                 if !valid_mpp {
5256                         for htlc in sources.drain(..) {
5257                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5258                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5259                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5260                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5261                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5262                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5263                         }
5264                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5265                 }
5266
5267                 // Now we can handle any errors which were generated.
5268                 for (counterparty_node_id, err) in errs.drain(..) {
5269                         let res: Result<(), _> = Err(err);
5270                         let _ = handle_error!(self, res, counterparty_node_id);
5271                 }
5272         }
5273
5274         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5275                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5276         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5277                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5278
5279                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5280                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5281                 // `BackgroundEvent`s.
5282                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5283
5284                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5285                 // the required mutexes are not held before we start.
5286                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5287                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5288
5289                 {
5290                         let per_peer_state = self.per_peer_state.read().unwrap();
5291                         let chan_id = prev_hop.outpoint.to_channel_id();
5292                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5293                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5294                                 None => None
5295                         };
5296
5297                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5298                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5299                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5300                         ).unwrap_or(None);
5301
5302                         if peer_state_opt.is_some() {
5303                                 let mut peer_state_lock = peer_state_opt.unwrap();
5304                                 let peer_state = &mut *peer_state_lock;
5305                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5306                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5307                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5308                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5309
5310                                                 match fulfill_res {
5311                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5312                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5313                                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5314                                                                                 chan_id, action);
5315                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5316                                                                 }
5317                                                                 if !during_init {
5318                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5319                                                                                 peer_state, per_peer_state, chan);
5320                                                                 } else {
5321                                                                         // If we're running during init we cannot update a monitor directly -
5322                                                                         // they probably haven't actually been loaded yet. Instead, push the
5323                                                                         // monitor update as a background event.
5324                                                                         self.pending_background_events.lock().unwrap().push(
5325                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5326                                                                                         counterparty_node_id,
5327                                                                                         funding_txo: prev_hop.outpoint,
5328                                                                                         update: monitor_update.clone(),
5329                                                                                 });
5330                                                                 }
5331                                                         }
5332                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5333                                                                 let action = if let Some(action) = completion_action(None, true) {
5334                                                                         action
5335                                                                 } else {
5336                                                                         return Ok(());
5337                                                                 };
5338                                                                 mem::drop(peer_state_lock);
5339
5340                                                                 log_trace!(self.logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5341                                                                         chan_id, action);
5342                                                                 let (node_id, funding_outpoint, blocker) =
5343                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5344                                                                         downstream_counterparty_node_id: node_id,
5345                                                                         downstream_funding_outpoint: funding_outpoint,
5346                                                                         blocking_action: blocker,
5347                                                                 } = action {
5348                                                                         (node_id, funding_outpoint, blocker)
5349                                                                 } else {
5350                                                                         debug_assert!(false,
5351                                                                                 "Duplicate claims should always free another channel immediately");
5352                                                                         return Ok(());
5353                                                                 };
5354                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5355                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5356                                                                         if let Some(blockers) = peer_state
5357                                                                                 .actions_blocking_raa_monitor_updates
5358                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5359                                                                         {
5360                                                                                 let mut found_blocker = false;
5361                                                                                 blockers.retain(|iter| {
5362                                                                                         // Note that we could actually be blocked, in
5363                                                                                         // which case we need to only remove the one
5364                                                                                         // blocker which was added duplicatively.
5365                                                                                         let first_blocker = !found_blocker;
5366                                                                                         if *iter == blocker { found_blocker = true; }
5367                                                                                         *iter != blocker || !first_blocker
5368                                                                                 });
5369                                                                                 debug_assert!(found_blocker);
5370                                                                         }
5371                                                                 } else {
5372                                                                         debug_assert!(false);
5373                                                                 }
5374                                                         }
5375                                                 }
5376                                         }
5377                                         return Ok(());
5378                                 }
5379                         }
5380                 }
5381                 let preimage_update = ChannelMonitorUpdate {
5382                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5383                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5384                                 payment_preimage,
5385                         }],
5386                 };
5387
5388                 if !during_init {
5389                         // We update the ChannelMonitor on the backward link, after
5390                         // receiving an `update_fulfill_htlc` from the forward link.
5391                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5392                         if update_res != ChannelMonitorUpdateStatus::Completed {
5393                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5394                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5395                                 // channel, or we must have an ability to receive the same event and try
5396                                 // again on restart.
5397                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5398                                         payment_preimage, update_res);
5399                         }
5400                 } else {
5401                         // If we're running during init we cannot update a monitor directly - they probably
5402                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5403                         // event.
5404                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5405                         // channel is already closed) we need to ultimately handle the monitor update
5406                         // completion action only after we've completed the monitor update. This is the only
5407                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5408                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5409                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5410                         // complete the monitor update completion action from `completion_action`.
5411                         self.pending_background_events.lock().unwrap().push(
5412                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5413                                         prev_hop.outpoint, preimage_update,
5414                                 )));
5415                 }
5416                 // Note that we do process the completion action here. This totally could be a
5417                 // duplicate claim, but we have no way of knowing without interrogating the
5418                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5419                 // generally always allowed to be duplicative (and it's specifically noted in
5420                 // `PaymentForwarded`).
5421                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5422                 Ok(())
5423         }
5424
5425         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5426                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5427         }
5428
5429         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5430                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5431                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5432         ) {
5433                 match source {
5434                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5435                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5436                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5437                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5438                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5439                                 }
5440                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5441                                         channel_funding_outpoint: next_channel_outpoint,
5442                                         counterparty_node_id: path.hops[0].pubkey,
5443                                 };
5444                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5445                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5446                                         &self.logger);
5447                         },
5448                         HTLCSource::PreviousHopData(hop_data) => {
5449                                 let prev_outpoint = hop_data.outpoint;
5450                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5451                                 #[cfg(debug_assertions)]
5452                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5453                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5454                                         |htlc_claim_value_msat, definitely_duplicate| {
5455                                                 let chan_to_release =
5456                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5457                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5458                                                         } else {
5459                                                                 // We can only get `None` here if we are processing a
5460                                                                 // `ChannelMonitor`-originated event, in which case we
5461                                                                 // don't care about ensuring we wake the downstream
5462                                                                 // channel's monitor updating - the channel is already
5463                                                                 // closed.
5464                                                                 None
5465                                                         };
5466
5467                                                 if definitely_duplicate && startup_replay {
5468                                                         // On startup we may get redundant claims which are related to
5469                                                         // monitor updates still in flight. In that case, we shouldn't
5470                                                         // immediately free, but instead let that monitor update complete
5471                                                         // in the background.
5472                                                         #[cfg(debug_assertions)] {
5473                                                                 let background_events = self.pending_background_events.lock().unwrap();
5474                                                                 // There should be a `BackgroundEvent` pending...
5475                                                                 assert!(background_events.iter().any(|ev| {
5476                                                                         match ev {
5477                                                                                 // to apply a monitor update that blocked the claiming channel,
5478                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5479                                                                                         funding_txo, update, ..
5480                                                                                 } => {
5481                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5482                                                                                                 assert!(update.updates.iter().any(|upd|
5483                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5484                                                                                                                 payment_preimage: update_preimage
5485                                                                                                         } = upd {
5486                                                                                                                 payment_preimage == *update_preimage
5487                                                                                                         } else { false }
5488                                                                                                 ), "{:?}", update);
5489                                                                                                 true
5490                                                                                         } else { false }
5491                                                                                 },
5492                                                                                 // or the channel we'd unblock is already closed,
5493                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5494                                                                                         (funding_txo, monitor_update)
5495                                                                                 ) => {
5496                                                                                         if *funding_txo == next_channel_outpoint {
5497                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5498                                                                                                 assert!(matches!(
5499                                                                                                         monitor_update.updates[0],
5500                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5501                                                                                                 ));
5502                                                                                                 true
5503                                                                                         } else { false }
5504                                                                                 },
5505                                                                                 // or the monitor update has completed and will unblock
5506                                                                                 // immediately once we get going.
5507                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5508                                                                                         channel_id, ..
5509                                                                                 } =>
5510                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5511                                                                         }
5512                                                                 }), "{:?}", *background_events);
5513                                                         }
5514                                                         None
5515                                                 } else if definitely_duplicate {
5516                                                         if let Some(other_chan) = chan_to_release {
5517                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5518                                                                         downstream_counterparty_node_id: other_chan.0,
5519                                                                         downstream_funding_outpoint: other_chan.1,
5520                                                                         blocking_action: other_chan.2,
5521                                                                 })
5522                                                         } else { None }
5523                                                 } else {
5524                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5525                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5526                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5527                                                                 } else { None }
5528                                                         } else { None };
5529                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5530                                                                 event: events::Event::PaymentForwarded {
5531                                                                         fee_earned_msat,
5532                                                                         claim_from_onchain_tx: from_onchain,
5533                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5534                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5535                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5536                                                                 },
5537                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5538                                                         })
5539                                                 }
5540                                         });
5541                                 if let Err((pk, err)) = res {
5542                                         let result: Result<(), _> = Err(err);
5543                                         let _ = handle_error!(self, result, pk);
5544                                 }
5545                         },
5546                 }
5547         }
5548
5549         /// Gets the node_id held by this ChannelManager
5550         pub fn get_our_node_id(&self) -> PublicKey {
5551                 self.our_network_pubkey.clone()
5552         }
5553
5554         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5555                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5556                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5557                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5558
5559                 for action in actions.into_iter() {
5560                         match action {
5561                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5562                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5563                                         if let Some(ClaimingPayment {
5564                                                 amount_msat,
5565                                                 payment_purpose: purpose,
5566                                                 receiver_node_id,
5567                                                 htlcs,
5568                                                 sender_intended_value: sender_intended_total_msat,
5569                                         }) = payment {
5570                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5571                                                         payment_hash,
5572                                                         purpose,
5573                                                         amount_msat,
5574                                                         receiver_node_id: Some(receiver_node_id),
5575                                                         htlcs,
5576                                                         sender_intended_total_msat,
5577                                                 }, None));
5578                                         }
5579                                 },
5580                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5581                                         event, downstream_counterparty_and_funding_outpoint
5582                                 } => {
5583                                         self.pending_events.lock().unwrap().push_back((event, None));
5584                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5585                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5586                                         }
5587                                 },
5588                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5589                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5590                                 } => {
5591                                         self.handle_monitor_update_release(
5592                                                 downstream_counterparty_node_id,
5593                                                 downstream_funding_outpoint,
5594                                                 Some(blocking_action),
5595                                         );
5596                                 },
5597                         }
5598                 }
5599         }
5600
5601         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5602         /// update completion.
5603         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5604                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5605                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5606                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5607                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5608         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5609                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5610                         &channel.context.channel_id(),
5611                         if raa.is_some() { "an" } else { "no" },
5612                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5613                         if funding_broadcastable.is_some() { "" } else { "not " },
5614                         if channel_ready.is_some() { "sending" } else { "without" },
5615                         if announcement_sigs.is_some() { "sending" } else { "without" });
5616
5617                 let mut htlc_forwards = None;
5618
5619                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5620                 if !pending_forwards.is_empty() {
5621                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5622                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5623                 }
5624
5625                 if let Some(msg) = channel_ready {
5626                         send_channel_ready!(self, pending_msg_events, channel, msg);
5627                 }
5628                 if let Some(msg) = announcement_sigs {
5629                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5630                                 node_id: counterparty_node_id,
5631                                 msg,
5632                         });
5633                 }
5634
5635                 macro_rules! handle_cs { () => {
5636                         if let Some(update) = commitment_update {
5637                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5638                                         node_id: counterparty_node_id,
5639                                         updates: update,
5640                                 });
5641                         }
5642                 } }
5643                 macro_rules! handle_raa { () => {
5644                         if let Some(revoke_and_ack) = raa {
5645                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5646                                         node_id: counterparty_node_id,
5647                                         msg: revoke_and_ack,
5648                                 });
5649                         }
5650                 } }
5651                 match order {
5652                         RAACommitmentOrder::CommitmentFirst => {
5653                                 handle_cs!();
5654                                 handle_raa!();
5655                         },
5656                         RAACommitmentOrder::RevokeAndACKFirst => {
5657                                 handle_raa!();
5658                                 handle_cs!();
5659                         },
5660                 }
5661
5662                 if let Some(tx) = funding_broadcastable {
5663                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5664                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5665                 }
5666
5667                 {
5668                         let mut pending_events = self.pending_events.lock().unwrap();
5669                         emit_channel_pending_event!(pending_events, channel);
5670                         emit_channel_ready_event!(pending_events, channel);
5671                 }
5672
5673                 htlc_forwards
5674         }
5675
5676         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5677                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5678
5679                 let counterparty_node_id = match counterparty_node_id {
5680                         Some(cp_id) => cp_id.clone(),
5681                         None => {
5682                                 // TODO: Once we can rely on the counterparty_node_id from the
5683                                 // monitor event, this and the id_to_peer map should be removed.
5684                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5685                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5686                                         Some(cp_id) => cp_id.clone(),
5687                                         None => return,
5688                                 }
5689                         }
5690                 };
5691                 let per_peer_state = self.per_peer_state.read().unwrap();
5692                 let mut peer_state_lock;
5693                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5694                 if peer_state_mutex_opt.is_none() { return }
5695                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5696                 let peer_state = &mut *peer_state_lock;
5697                 let channel =
5698                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5699                                 chan
5700                         } else {
5701                                 let update_actions = peer_state.monitor_update_blocked_actions
5702                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5703                                 mem::drop(peer_state_lock);
5704                                 mem::drop(per_peer_state);
5705                                 self.handle_monitor_update_completion_actions(update_actions);
5706                                 return;
5707                         };
5708                 let remaining_in_flight =
5709                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5710                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5711                                 pending.len()
5712                         } else { 0 };
5713                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5714                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5715                         remaining_in_flight);
5716                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5717                         return;
5718                 }
5719                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5720         }
5721
5722         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5723         ///
5724         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5725         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5726         /// the channel.
5727         ///
5728         /// The `user_channel_id` parameter will be provided back in
5729         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5730         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5731         ///
5732         /// Note that this method will return an error and reject the channel, if it requires support
5733         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5734         /// used to accept such channels.
5735         ///
5736         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5737         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5738         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5739                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5740         }
5741
5742         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5743         /// it as confirmed immediately.
5744         ///
5745         /// The `user_channel_id` parameter will be provided back in
5746         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5747         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5748         ///
5749         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5750         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5751         ///
5752         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5753         /// transaction and blindly assumes that it will eventually confirm.
5754         ///
5755         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5756         /// does not pay to the correct script the correct amount, *you will lose funds*.
5757         ///
5758         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5759         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5760         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5761                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5762         }
5763
5764         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5765                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5766
5767                 let peers_without_funded_channels =
5768                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5769                 let per_peer_state = self.per_peer_state.read().unwrap();
5770                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5771                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5772                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5773                 let peer_state = &mut *peer_state_lock;
5774                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5775
5776                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5777                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5778                 // that we can delay allocating the SCID until after we're sure that the checks below will
5779                 // succeed.
5780                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5781                         Some(unaccepted_channel) => {
5782                                 let best_block_height = self.best_block.read().unwrap().height();
5783                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5784                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5785                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5786                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5787                         }
5788                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5789                 }?;
5790
5791                 if accept_0conf {
5792                         // This should have been correctly configured by the call to InboundV1Channel::new.
5793                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5794                 } else if channel.context.get_channel_type().requires_zero_conf() {
5795                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5796                                 node_id: channel.context.get_counterparty_node_id(),
5797                                 action: msgs::ErrorAction::SendErrorMessage{
5798                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5799                                 }
5800                         };
5801                         peer_state.pending_msg_events.push(send_msg_err_event);
5802                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5803                 } else {
5804                         // If this peer already has some channels, a new channel won't increase our number of peers
5805                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5806                         // channels per-peer we can accept channels from a peer with existing ones.
5807                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5808                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5809                                         node_id: channel.context.get_counterparty_node_id(),
5810                                         action: msgs::ErrorAction::SendErrorMessage{
5811                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5812                                         }
5813                                 };
5814                                 peer_state.pending_msg_events.push(send_msg_err_event);
5815                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5816                         }
5817                 }
5818
5819                 // Now that we know we have a channel, assign an outbound SCID alias.
5820                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5821                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5822
5823                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5824                         node_id: channel.context.get_counterparty_node_id(),
5825                         msg: channel.accept_inbound_channel(),
5826                 });
5827
5828                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
5829
5830                 Ok(())
5831         }
5832
5833         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5834         /// or 0-conf channels.
5835         ///
5836         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
5837         /// non-0-conf channels we have with the peer.
5838         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
5839         where Filter: Fn(&PeerState<SP>) -> bool {
5840                 let mut peers_without_funded_channels = 0;
5841                 let best_block_height = self.best_block.read().unwrap().height();
5842                 {
5843                         let peer_state_lock = self.per_peer_state.read().unwrap();
5844                         for (_, peer_mtx) in peer_state_lock.iter() {
5845                                 let peer = peer_mtx.lock().unwrap();
5846                                 if !maybe_count_peer(&*peer) { continue; }
5847                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
5848                                 if num_unfunded_channels == peer.total_channel_count() {
5849                                         peers_without_funded_channels += 1;
5850                                 }
5851                         }
5852                 }
5853                 return peers_without_funded_channels;
5854         }
5855
5856         fn unfunded_channel_count(
5857                 peer: &PeerState<SP>, best_block_height: u32
5858         ) -> usize {
5859                 let mut num_unfunded_channels = 0;
5860                 for (_, phase) in peer.channel_by_id.iter() {
5861                         match phase {
5862                                 ChannelPhase::Funded(chan) => {
5863                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
5864                                         // which have not yet had any confirmations on-chain.
5865                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
5866                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
5867                                         {
5868                                                 num_unfunded_channels += 1;
5869                                         }
5870                                 },
5871                                 ChannelPhase::UnfundedInboundV1(chan) => {
5872                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
5873                                                 num_unfunded_channels += 1;
5874                                         }
5875                                 },
5876                                 ChannelPhase::UnfundedOutboundV1(_) => {
5877                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
5878                                         continue;
5879                                 }
5880                         }
5881                 }
5882                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
5883         }
5884
5885         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
5886                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
5887                 // likely to be lost on restart!
5888                 if msg.chain_hash != self.chain_hash {
5889                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
5890                 }
5891
5892                 if !self.default_configuration.accept_inbound_channels {
5893                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5894                 }
5895
5896                 // Get the number of peers with channels, but without funded ones. We don't care too much
5897                 // about peers that never open a channel, so we filter by peers that have at least one
5898                 // channel, and then limit the number of those with unfunded channels.
5899                 let channeled_peers_without_funding =
5900                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
5901
5902                 let per_peer_state = self.per_peer_state.read().unwrap();
5903                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5904                     .ok_or_else(|| {
5905                                 debug_assert!(false);
5906                                 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())
5907                         })?;
5908                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5909                 let peer_state = &mut *peer_state_lock;
5910
5911                 // If this peer already has some channels, a new channel won't increase our number of peers
5912                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5913                 // channels per-peer we can accept channels from a peer with existing ones.
5914                 if peer_state.total_channel_count() == 0 &&
5915                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
5916                         !self.default_configuration.manually_accept_inbound_channels
5917                 {
5918                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5919                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
5920                                 msg.temporary_channel_id.clone()));
5921                 }
5922
5923                 let best_block_height = self.best_block.read().unwrap().height();
5924                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
5925                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5926                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
5927                                 msg.temporary_channel_id.clone()));
5928                 }
5929
5930                 let channel_id = msg.temporary_channel_id;
5931                 let channel_exists = peer_state.has_channel(&channel_id);
5932                 if channel_exists {
5933                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
5934                 }
5935
5936                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
5937                 if self.default_configuration.manually_accept_inbound_channels {
5938                         let mut pending_events = self.pending_events.lock().unwrap();
5939                         pending_events.push_back((events::Event::OpenChannelRequest {
5940                                 temporary_channel_id: msg.temporary_channel_id.clone(),
5941                                 counterparty_node_id: counterparty_node_id.clone(),
5942                                 funding_satoshis: msg.funding_satoshis,
5943                                 push_msat: msg.push_msat,
5944                                 channel_type: msg.channel_type.clone().unwrap(),
5945                         }, None));
5946                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
5947                                 open_channel_msg: msg.clone(),
5948                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
5949                         });
5950                         return Ok(());
5951                 }
5952
5953                 // Otherwise create the channel right now.
5954                 let mut random_bytes = [0u8; 16];
5955                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
5956                 let user_channel_id = u128::from_be_bytes(random_bytes);
5957                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5958                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
5959                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
5960                 {
5961                         Err(e) => {
5962                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
5963                         },
5964                         Ok(res) => res
5965                 };
5966
5967                 let channel_type = channel.context.get_channel_type();
5968                 if channel_type.requires_zero_conf() {
5969                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5970                 }
5971                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
5972                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
5973                 }
5974
5975                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5976                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5977
5978                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5979                         node_id: counterparty_node_id.clone(),
5980                         msg: channel.accept_inbound_channel(),
5981                 });
5982                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
5983                 Ok(())
5984         }
5985
5986         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
5987                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
5988                 // likely to be lost on restart!
5989                 let (value, output_script, user_id) = {
5990                         let per_peer_state = self.per_peer_state.read().unwrap();
5991                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5992                                 .ok_or_else(|| {
5993                                         debug_assert!(false);
5994                                         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)
5995                                 })?;
5996                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5997                         let peer_state = &mut *peer_state_lock;
5998                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
5999                                 hash_map::Entry::Occupied(mut phase) => {
6000                                         match phase.get_mut() {
6001                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6002                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6003                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6004                                                 },
6005                                                 _ => {
6006                                                         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));
6007                                                 }
6008                                         }
6009                                 },
6010                                 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))
6011                         }
6012                 };
6013                 let mut pending_events = self.pending_events.lock().unwrap();
6014                 pending_events.push_back((events::Event::FundingGenerationReady {
6015                         temporary_channel_id: msg.temporary_channel_id,
6016                         counterparty_node_id: *counterparty_node_id,
6017                         channel_value_satoshis: value,
6018                         output_script,
6019                         user_channel_id: user_id,
6020                 }, None));
6021                 Ok(())
6022         }
6023
6024         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6025                 let best_block = *self.best_block.read().unwrap();
6026
6027                 let per_peer_state = self.per_peer_state.read().unwrap();
6028                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6029                         .ok_or_else(|| {
6030                                 debug_assert!(false);
6031                                 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)
6032                         })?;
6033
6034                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6035                 let peer_state = &mut *peer_state_lock;
6036                 let (chan, funding_msg, monitor) =
6037                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6038                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6039                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
6040                                                 Ok(res) => res,
6041                                                 Err((mut inbound_chan, err)) => {
6042                                                         // We've already removed this inbound channel from the map in `PeerState`
6043                                                         // above so at this point we just need to clean up any lingering entries
6044                                                         // concerning this channel as it is safe to do so.
6045                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
6046                                                         let user_id = inbound_chan.context.get_user_id();
6047                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
6048                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
6049                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
6050                                                 },
6051                                         }
6052                                 },
6053                                 Some(ChannelPhase::Funded(_)) | Some(ChannelPhase::UnfundedOutboundV1(_)) => {
6054                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id));
6055                                 },
6056                                 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))
6057                         };
6058
6059                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
6060                         hash_map::Entry::Occupied(_) => {
6061                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
6062                         },
6063                         hash_map::Entry::Vacant(e) => {
6064                                 let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
6065                                 match id_to_peer_lock.entry(chan.context.channel_id()) {
6066                                         hash_map::Entry::Occupied(_) => {
6067                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
6068                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6069                                                         funding_msg.channel_id))
6070                                         },
6071                                         hash_map::Entry::Vacant(i_e) => {
6072                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6073                                                 if let Ok(persist_state) = monitor_res {
6074                                                         i_e.insert(chan.context.get_counterparty_node_id());
6075                                                         mem::drop(id_to_peer_lock);
6076
6077                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6078                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6079                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6080                                                         // until we have persisted our monitor.
6081                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6082                                                                 node_id: counterparty_node_id.clone(),
6083                                                                 msg: funding_msg,
6084                                                         });
6085
6086                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6087                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6088                                                                         per_peer_state, chan, INITIAL_MONITOR);
6089                                                         } else {
6090                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6091                                                         }
6092                                                         Ok(())
6093                                                 } else {
6094                                                         log_error!(self.logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6095                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6096                                                                 "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6097                                                                 funding_msg.channel_id));
6098                                                 }
6099                                         }
6100                                 }
6101                         }
6102                 }
6103         }
6104
6105         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6106                 let best_block = *self.best_block.read().unwrap();
6107                 let per_peer_state = self.per_peer_state.read().unwrap();
6108                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6109                         .ok_or_else(|| {
6110                                 debug_assert!(false);
6111                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6112                         })?;
6113
6114                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6115                 let peer_state = &mut *peer_state_lock;
6116                 match peer_state.channel_by_id.entry(msg.channel_id) {
6117                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6118                                 match chan_phase_entry.get_mut() {
6119                                         ChannelPhase::Funded(ref mut chan) => {
6120                                                 let monitor = try_chan_phase_entry!(self,
6121                                                         chan.funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan_phase_entry);
6122                                                 if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6123                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6124                                                         Ok(())
6125                                                 } else {
6126                                                         try_chan_phase_entry!(self, Err(ChannelError::Close("Channel funding outpoint was a duplicate".to_owned())), chan_phase_entry)
6127                                                 }
6128                                         },
6129                                         _ => {
6130                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6131                                         },
6132                                 }
6133                         },
6134                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6135                 }
6136         }
6137
6138         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6139                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6140                 // closing a channel), so any changes are likely to be lost on restart!
6141                 let per_peer_state = self.per_peer_state.read().unwrap();
6142                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6143                         .ok_or_else(|| {
6144                                 debug_assert!(false);
6145                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6146                         })?;
6147                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6148                 let peer_state = &mut *peer_state_lock;
6149                 match peer_state.channel_by_id.entry(msg.channel_id) {
6150                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6151                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6152                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6153                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
6154                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6155                                                 log_trace!(self.logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6156                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6157                                                         node_id: counterparty_node_id.clone(),
6158                                                         msg: announcement_sigs,
6159                                                 });
6160                                         } else if chan.context.is_usable() {
6161                                                 // If we're sending an announcement_signatures, we'll send the (public)
6162                                                 // channel_update after sending a channel_announcement when we receive our
6163                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6164                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6165                                                 // announcement_signatures.
6166                                                 log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6167                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6168                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6169                                                                 node_id: counterparty_node_id.clone(),
6170                                                                 msg,
6171                                                         });
6172                                                 }
6173                                         }
6174
6175                                         {
6176                                                 let mut pending_events = self.pending_events.lock().unwrap();
6177                                                 emit_channel_ready_event!(pending_events, chan);
6178                                         }
6179
6180                                         Ok(())
6181                                 } else {
6182                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6183                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6184                                 }
6185                         },
6186                         hash_map::Entry::Vacant(_) => {
6187                                 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))
6188                         }
6189                 }
6190         }
6191
6192         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6193                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6194                 let mut finish_shutdown = None;
6195                 {
6196                         let per_peer_state = self.per_peer_state.read().unwrap();
6197                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6198                                 .ok_or_else(|| {
6199                                         debug_assert!(false);
6200                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6201                                 })?;
6202                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6203                         let peer_state = &mut *peer_state_lock;
6204                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6205                                 let phase = chan_phase_entry.get_mut();
6206                                 match phase {
6207                                         ChannelPhase::Funded(chan) => {
6208                                                 if !chan.received_shutdown() {
6209                                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
6210                                                                 msg.channel_id,
6211                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6212                                                 }
6213
6214                                                 let funding_txo_opt = chan.context.get_funding_txo();
6215                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6216                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6217                                                 dropped_htlcs = htlcs;
6218
6219                                                 if let Some(msg) = shutdown {
6220                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6221                                                         // here as we don't need the monitor update to complete until we send a
6222                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6223                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6224                                                                 node_id: *counterparty_node_id,
6225                                                                 msg,
6226                                                         });
6227                                                 }
6228                                                 // Update the monitor with the shutdown script if necessary.
6229                                                 if let Some(monitor_update) = monitor_update_opt {
6230                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6231                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6232                                                 }
6233                                         },
6234                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6235                                                 let context = phase.context_mut();
6236                                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6237                                                 self.issue_channel_close_events(&context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
6238                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6239                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false));
6240                                         },
6241                                 }
6242                         } else {
6243                                 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))
6244                         }
6245                 }
6246                 for htlc_source in dropped_htlcs.drain(..) {
6247                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6248                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6249                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6250                 }
6251                 if let Some(shutdown_res) = finish_shutdown {
6252                         self.finish_close_channel(shutdown_res);
6253                 }
6254
6255                 Ok(())
6256         }
6257
6258         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6259                 let per_peer_state = self.per_peer_state.read().unwrap();
6260                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6261                         .ok_or_else(|| {
6262                                 debug_assert!(false);
6263                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6264                         })?;
6265                 let (tx, chan_option, shutdown_result) = {
6266                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6267                         let peer_state = &mut *peer_state_lock;
6268                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6269                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6270                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6271                                                 let (closing_signed, tx, shutdown_result) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6272                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
6273                                                 if let Some(msg) = closing_signed {
6274                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6275                                                                 node_id: counterparty_node_id.clone(),
6276                                                                 msg,
6277                                                         });
6278                                                 }
6279                                                 if tx.is_some() {
6280                                                         // We're done with this channel, we've got a signed closing transaction and
6281                                                         // will send the closing_signed back to the remote peer upon return. This
6282                                                         // also implies there are no pending HTLCs left on the channel, so we can
6283                                                         // fully delete it from tracking (the channel monitor is still around to
6284                                                         // watch for old state broadcasts)!
6285                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)), shutdown_result)
6286                                                 } else { (tx, None, shutdown_result) }
6287                                         } else {
6288                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6289                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6290                                         }
6291                                 },
6292                                 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))
6293                         }
6294                 };
6295                 if let Some(broadcast_tx) = tx {
6296                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
6297                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6298                 }
6299                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6300                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6301                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6302                                 let peer_state = &mut *peer_state_lock;
6303                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6304                                         msg: update
6305                                 });
6306                         }
6307                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6308                 }
6309                 mem::drop(per_peer_state);
6310                 if let Some(shutdown_result) = shutdown_result {
6311                         self.finish_close_channel(shutdown_result);
6312                 }
6313                 Ok(())
6314         }
6315
6316         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6317                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6318                 //determine the state of the payment based on our response/if we forward anything/the time
6319                 //we take to respond. We should take care to avoid allowing such an attack.
6320                 //
6321                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6322                 //us repeatedly garbled in different ways, and compare our error messages, which are
6323                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6324                 //but we should prevent it anyway.
6325
6326                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6327                 // closing a channel), so any changes are likely to be lost on restart!
6328
6329                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
6330                 let per_peer_state = self.per_peer_state.read().unwrap();
6331                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6332                         .ok_or_else(|| {
6333                                 debug_assert!(false);
6334                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6335                         })?;
6336                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6337                 let peer_state = &mut *peer_state_lock;
6338                 match peer_state.channel_by_id.entry(msg.channel_id) {
6339                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6340                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6341                                         let pending_forward_info = match decoded_hop_res {
6342                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6343                                                         self.construct_pending_htlc_status(msg, shared_secret, next_hop,
6344                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt),
6345                                                 Err(e) => PendingHTLCStatus::Fail(e)
6346                                         };
6347                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6348                                                 // If the update_add is completely bogus, the call will Err and we will close,
6349                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6350                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6351                                                 match pending_forward_info {
6352                                                         PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
6353                                                                 let reason = if (error_code & 0x1000) != 0 {
6354                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6355                                                                         HTLCFailReason::reason(real_code, error_data)
6356                                                                 } else {
6357                                                                         HTLCFailReason::from_failure_code(error_code)
6358                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6359                                                                 let msg = msgs::UpdateFailHTLC {
6360                                                                         channel_id: msg.channel_id,
6361                                                                         htlc_id: msg.htlc_id,
6362                                                                         reason
6363                                                                 };
6364                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6365                                                         },
6366                                                         _ => pending_forward_info
6367                                                 }
6368                                         };
6369                                         try_chan_phase_entry!(self, chan.update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &self.logger), chan_phase_entry);
6370                                 } else {
6371                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6372                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6373                                 }
6374                         },
6375                         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))
6376                 }
6377                 Ok(())
6378         }
6379
6380         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6381                 let funding_txo;
6382                 let (htlc_source, forwarded_htlc_value) = {
6383                         let per_peer_state = self.per_peer_state.read().unwrap();
6384                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6385                                 .ok_or_else(|| {
6386                                         debug_assert!(false);
6387                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6388                                 })?;
6389                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6390                         let peer_state = &mut *peer_state_lock;
6391                         match peer_state.channel_by_id.entry(msg.channel_id) {
6392                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6393                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6394                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6395                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6396                                                         log_trace!(self.logger,
6397                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6398                                                                 msg.channel_id);
6399                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6400                                                                 .or_insert_with(Vec::new)
6401                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6402                                                 }
6403                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6404                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6405                                                 // We do this instead in the `claim_funds_internal` by attaching a
6406                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6407                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6408                                                 // process the RAA as messages are processed from single peers serially.
6409                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6410                                                 res
6411                                         } else {
6412                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6413                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6414                                         }
6415                                 },
6416                                 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))
6417                         }
6418                 };
6419                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6420                 Ok(())
6421         }
6422
6423         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6424                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6425                 // closing a channel), so any changes are likely to be lost on restart!
6426                 let per_peer_state = self.per_peer_state.read().unwrap();
6427                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6428                         .ok_or_else(|| {
6429                                 debug_assert!(false);
6430                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6431                         })?;
6432                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6433                 let peer_state = &mut *peer_state_lock;
6434                 match peer_state.channel_by_id.entry(msg.channel_id) {
6435                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6436                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6437                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6438                                 } else {
6439                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6440                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6441                                 }
6442                         },
6443                         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))
6444                 }
6445                 Ok(())
6446         }
6447
6448         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6449                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6450                 // closing a channel), so any changes are likely to be lost on restart!
6451                 let per_peer_state = self.per_peer_state.read().unwrap();
6452                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6453                         .ok_or_else(|| {
6454                                 debug_assert!(false);
6455                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6456                         })?;
6457                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6458                 let peer_state = &mut *peer_state_lock;
6459                 match peer_state.channel_by_id.entry(msg.channel_id) {
6460                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6461                                 if (msg.failure_code & 0x8000) == 0 {
6462                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6463                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6464                                 }
6465                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6466                                         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);
6467                                 } else {
6468                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6469                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6470                                 }
6471                                 Ok(())
6472                         },
6473                         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))
6474                 }
6475         }
6476
6477         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6478                 let per_peer_state = self.per_peer_state.read().unwrap();
6479                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6480                         .ok_or_else(|| {
6481                                 debug_assert!(false);
6482                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6483                         })?;
6484                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6485                 let peer_state = &mut *peer_state_lock;
6486                 match peer_state.channel_by_id.entry(msg.channel_id) {
6487                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6488                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6489                                         let funding_txo = chan.context.get_funding_txo();
6490                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &self.logger), chan_phase_entry);
6491                                         if let Some(monitor_update) = monitor_update_opt {
6492                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6493                                                         peer_state, per_peer_state, chan);
6494                                         }
6495                                         Ok(())
6496                                 } else {
6497                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6498                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6499                                 }
6500                         },
6501                         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))
6502                 }
6503         }
6504
6505         #[inline]
6506         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6507                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6508                         let mut push_forward_event = false;
6509                         let mut new_intercept_events = VecDeque::new();
6510                         let mut failed_intercept_forwards = Vec::new();
6511                         if !pending_forwards.is_empty() {
6512                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6513                                         let scid = match forward_info.routing {
6514                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6515                                                 PendingHTLCRouting::Receive { .. } => 0,
6516                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6517                                         };
6518                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6519                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6520
6521                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6522                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6523                                         match forward_htlcs.entry(scid) {
6524                                                 hash_map::Entry::Occupied(mut entry) => {
6525                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6526                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6527                                                 },
6528                                                 hash_map::Entry::Vacant(entry) => {
6529                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6530                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6531                                                         {
6532                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6533                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6534                                                                 match pending_intercepts.entry(intercept_id) {
6535                                                                         hash_map::Entry::Vacant(entry) => {
6536                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6537                                                                                         requested_next_hop_scid: scid,
6538                                                                                         payment_hash: forward_info.payment_hash,
6539                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6540                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6541                                                                                         intercept_id
6542                                                                                 }, None));
6543                                                                                 entry.insert(PendingAddHTLCInfo {
6544                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6545                                                                         },
6546                                                                         hash_map::Entry::Occupied(_) => {
6547                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6548                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6549                                                                                         short_channel_id: prev_short_channel_id,
6550                                                                                         user_channel_id: Some(prev_user_channel_id),
6551                                                                                         outpoint: prev_funding_outpoint,
6552                                                                                         htlc_id: prev_htlc_id,
6553                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6554                                                                                         phantom_shared_secret: None,
6555                                                                                 });
6556
6557                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6558                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6559                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6560                                                                                 ));
6561                                                                         }
6562                                                                 }
6563                                                         } else {
6564                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6565                                                                 // payments are being processed.
6566                                                                 if forward_htlcs_empty {
6567                                                                         push_forward_event = true;
6568                                                                 }
6569                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6570                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6571                                                         }
6572                                                 }
6573                                         }
6574                                 }
6575                         }
6576
6577                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6578                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6579                         }
6580
6581                         if !new_intercept_events.is_empty() {
6582                                 let mut events = self.pending_events.lock().unwrap();
6583                                 events.append(&mut new_intercept_events);
6584                         }
6585                         if push_forward_event { self.push_pending_forwards_ev() }
6586                 }
6587         }
6588
6589         fn push_pending_forwards_ev(&self) {
6590                 let mut pending_events = self.pending_events.lock().unwrap();
6591                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6592                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6593                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6594                 ).count();
6595                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6596                 // events is done in batches and they are not removed until we're done processing each
6597                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6598                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6599                 // payments will need an additional forwarding event before being claimed to make them look
6600                 // real by taking more time.
6601                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6602                         pending_events.push_back((Event::PendingHTLCsForwardable {
6603                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6604                         }, None));
6605                 }
6606         }
6607
6608         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6609         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6610         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6611         /// the [`ChannelMonitorUpdate`] in question.
6612         fn raa_monitor_updates_held(&self,
6613                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6614                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6615         ) -> bool {
6616                 actions_blocking_raa_monitor_updates
6617                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6618                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6619                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6620                                 channel_funding_outpoint,
6621                                 counterparty_node_id,
6622                         })
6623                 })
6624         }
6625
6626         #[cfg(any(test, feature = "_test_utils"))]
6627         pub(crate) fn test_raa_monitor_updates_held(&self,
6628                 counterparty_node_id: PublicKey, channel_id: ChannelId
6629         ) -> bool {
6630                 let per_peer_state = self.per_peer_state.read().unwrap();
6631                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6632                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6633                         let peer_state = &mut *peer_state_lck;
6634
6635                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6636                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6637                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6638                         }
6639                 }
6640                 false
6641         }
6642
6643         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6644                 let htlcs_to_fail = {
6645                         let per_peer_state = self.per_peer_state.read().unwrap();
6646                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6647                                 .ok_or_else(|| {
6648                                         debug_assert!(false);
6649                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6650                                 }).map(|mtx| mtx.lock().unwrap())?;
6651                         let peer_state = &mut *peer_state_lock;
6652                         match peer_state.channel_by_id.entry(msg.channel_id) {
6653                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6654                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6655                                                 let funding_txo_opt = chan.context.get_funding_txo();
6656                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6657                                                         self.raa_monitor_updates_held(
6658                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6659                                                                 *counterparty_node_id)
6660                                                 } else { false };
6661                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
6662                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &self.logger, mon_update_blocked), chan_phase_entry);
6663                                                 if let Some(monitor_update) = monitor_update_opt {
6664                                                         let funding_txo = funding_txo_opt
6665                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
6666                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
6667                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6668                                                 }
6669                                                 htlcs_to_fail
6670                                         } else {
6671                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6672                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
6673                                         }
6674                                 },
6675                                 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))
6676                         }
6677                 };
6678                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6679                 Ok(())
6680         }
6681
6682         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6683                 let per_peer_state = self.per_peer_state.read().unwrap();
6684                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6685                         .ok_or_else(|| {
6686                                 debug_assert!(false);
6687                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6688                         })?;
6689                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6690                 let peer_state = &mut *peer_state_lock;
6691                 match peer_state.channel_by_id.entry(msg.channel_id) {
6692                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6693                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6694                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &self.logger), chan_phase_entry);
6695                                 } else {
6696                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6697                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
6698                                 }
6699                         },
6700                         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))
6701                 }
6702                 Ok(())
6703         }
6704
6705         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6706                 let per_peer_state = self.per_peer_state.read().unwrap();
6707                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6708                         .ok_or_else(|| {
6709                                 debug_assert!(false);
6710                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6711                         })?;
6712                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6713                 let peer_state = &mut *peer_state_lock;
6714                 match peer_state.channel_by_id.entry(msg.channel_id) {
6715                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6716                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6717                                         if !chan.context.is_usable() {
6718                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6719                                         }
6720
6721                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6722                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6723                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
6724                                                         msg, &self.default_configuration
6725                                                 ), chan_phase_entry),
6726                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6727                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6728                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
6729                                         });
6730                                 } else {
6731                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6732                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
6733                                 }
6734                         },
6735                         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))
6736                 }
6737                 Ok(())
6738         }
6739
6740         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
6741         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6742                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6743                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6744                         None => {
6745                                 // It's not a local channel
6746                                 return Ok(NotifyOption::SkipPersistNoEvents)
6747                         }
6748                 };
6749                 let per_peer_state = self.per_peer_state.read().unwrap();
6750                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6751                 if peer_state_mutex_opt.is_none() {
6752                         return Ok(NotifyOption::SkipPersistNoEvents)
6753                 }
6754                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6755                 let peer_state = &mut *peer_state_lock;
6756                 match peer_state.channel_by_id.entry(chan_id) {
6757                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6758                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6759                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
6760                                                 if chan.context.should_announce() {
6761                                                         // If the announcement is about a channel of ours which is public, some
6762                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
6763                                                         // a scary-looking error message and return Ok instead.
6764                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6765                                                 }
6766                                                 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));
6767                                         }
6768                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
6769                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
6770                                         if were_node_one == msg_from_node_one {
6771                                                 return Ok(NotifyOption::SkipPersistNoEvents);
6772                                         } else {
6773                                                 log_debug!(self.logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
6774                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
6775                                                 // If nothing changed after applying their update, we don't need to bother
6776                                                 // persisting.
6777                                                 if !did_change {
6778                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6779                                                 }
6780                                         }
6781                                 } else {
6782                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6783                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
6784                                 }
6785                         },
6786                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
6787                 }
6788                 Ok(NotifyOption::DoPersist)
6789         }
6790
6791         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
6792                 let htlc_forwards;
6793                 let need_lnd_workaround = {
6794                         let per_peer_state = self.per_peer_state.read().unwrap();
6795
6796                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6797                                 .ok_or_else(|| {
6798                                         debug_assert!(false);
6799                                         MsgHandleErrInternal::send_err_msg_no_close(
6800                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6801                                                 msg.channel_id
6802                                         )
6803                                 })?;
6804                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6805                         let peer_state = &mut *peer_state_lock;
6806                         match peer_state.channel_by_id.entry(msg.channel_id) {
6807                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6808                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6809                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
6810                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
6811                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
6812                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6813                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
6814                                                         msg, &self.logger, &self.node_signer, self.chain_hash,
6815                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
6816                                                 let mut channel_update = None;
6817                                                 if let Some(msg) = responses.shutdown_msg {
6818                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6819                                                                 node_id: counterparty_node_id.clone(),
6820                                                                 msg,
6821                                                         });
6822                                                 } else if chan.context.is_usable() {
6823                                                         // If the channel is in a usable state (ie the channel is not being shut
6824                                                         // down), send a unicast channel_update to our counterparty to make sure
6825                                                         // they have the latest channel parameters.
6826                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6827                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
6828                                                                         node_id: chan.context.get_counterparty_node_id(),
6829                                                                         msg,
6830                                                                 });
6831                                                         }
6832                                                 }
6833                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
6834                                                 htlc_forwards = self.handle_channel_resumption(
6835                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
6836                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
6837                                                 if let Some(upd) = channel_update {
6838                                                         peer_state.pending_msg_events.push(upd);
6839                                                 }
6840                                                 need_lnd_workaround
6841                                         } else {
6842                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6843                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
6844                                         }
6845                                 },
6846                                 hash_map::Entry::Vacant(_) => {
6847                                         log_debug!(self.logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
6848                                                 log_bytes!(msg.channel_id.0));
6849                                         // Unfortunately, lnd doesn't force close on errors
6850                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
6851                                         // One of the few ways to get an lnd counterparty to force close is by
6852                                         // replicating what they do when restoring static channel backups (SCBs). They
6853                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
6854                                         // invalid `your_last_per_commitment_secret`.
6855                                         //
6856                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
6857                                         // can assume it's likely the channel closed from our point of view, but it
6858                                         // remains open on the counterparty's side. By sending this bogus
6859                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
6860                                         // force close broadcasting their latest state. If the closing transaction from
6861                                         // our point of view remains unconfirmed, it'll enter a race with the
6862                                         // counterparty's to-be-broadcast latest commitment transaction.
6863                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
6864                                                 node_id: *counterparty_node_id,
6865                                                 msg: msgs::ChannelReestablish {
6866                                                         channel_id: msg.channel_id,
6867                                                         next_local_commitment_number: 0,
6868                                                         next_remote_commitment_number: 0,
6869                                                         your_last_per_commitment_secret: [1u8; 32],
6870                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
6871                                                         next_funding_txid: None,
6872                                                 },
6873                                         });
6874                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6875                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
6876                                                         counterparty_node_id), msg.channel_id)
6877                                         )
6878                                 }
6879                         }
6880                 };
6881
6882                 let mut persist = NotifyOption::SkipPersistHandleEvents;
6883                 if let Some(forwards) = htlc_forwards {
6884                         self.forward_htlcs(&mut [forwards][..]);
6885                         persist = NotifyOption::DoPersist;
6886                 }
6887
6888                 if let Some(channel_ready_msg) = need_lnd_workaround {
6889                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
6890                 }
6891                 Ok(persist)
6892         }
6893
6894         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
6895         fn process_pending_monitor_events(&self) -> bool {
6896                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
6897
6898                 let mut failed_channels = Vec::new();
6899                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
6900                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
6901                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
6902                         for monitor_event in monitor_events.drain(..) {
6903                                 match monitor_event {
6904                                         MonitorEvent::HTLCEvent(htlc_update) => {
6905                                                 if let Some(preimage) = htlc_update.payment_preimage {
6906                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", preimage);
6907                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
6908                                                 } else {
6909                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
6910                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
6911                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6912                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
6913                                                 }
6914                                         },
6915                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
6916                                                 let counterparty_node_id_opt = match counterparty_node_id {
6917                                                         Some(cp_id) => Some(cp_id),
6918                                                         None => {
6919                                                                 // TODO: Once we can rely on the counterparty_node_id from the
6920                                                                 // monitor event, this and the id_to_peer map should be removed.
6921                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
6922                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
6923                                                         }
6924                                                 };
6925                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
6926                                                         let per_peer_state = self.per_peer_state.read().unwrap();
6927                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
6928                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6929                                                                 let peer_state = &mut *peer_state_lock;
6930                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6931                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
6932                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
6933                                                                                 failed_channels.push(chan.context.force_shutdown(false));
6934                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6935                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6936                                                                                                 msg: update
6937                                                                                         });
6938                                                                                 }
6939                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
6940                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
6941                                                                                         node_id: chan.context.get_counterparty_node_id(),
6942                                                                                         action: msgs::ErrorAction::DisconnectPeer {
6943                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
6944                                                                                         },
6945                                                                                 });
6946                                                                         }
6947                                                                 }
6948                                                         }
6949                                                 }
6950                                         },
6951                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
6952                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
6953                                         },
6954                                 }
6955                         }
6956                 }
6957
6958                 for failure in failed_channels.drain(..) {
6959                         self.finish_close_channel(failure);
6960                 }
6961
6962                 has_pending_monitor_events
6963         }
6964
6965         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
6966         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
6967         /// update events as a separate process method here.
6968         #[cfg(fuzzing)]
6969         pub fn process_monitor_events(&self) {
6970                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6971                 self.process_pending_monitor_events();
6972         }
6973
6974         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
6975         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
6976         /// update was applied.
6977         fn check_free_holding_cells(&self) -> bool {
6978                 let mut has_monitor_update = false;
6979                 let mut failed_htlcs = Vec::new();
6980
6981                 // Walk our list of channels and find any that need to update. Note that when we do find an
6982                 // update, if it includes actions that must be taken afterwards, we have to drop the
6983                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
6984                 // manage to go through all our peers without finding a single channel to update.
6985                 'peer_loop: loop {
6986                         let per_peer_state = self.per_peer_state.read().unwrap();
6987                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6988                                 'chan_loop: loop {
6989                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6990                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
6991                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
6992                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
6993                                         ) {
6994                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
6995                                                 let funding_txo = chan.context.get_funding_txo();
6996                                                 let (monitor_opt, holding_cell_failed_htlcs) =
6997                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
6998                                                 if !holding_cell_failed_htlcs.is_empty() {
6999                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7000                                                 }
7001                                                 if let Some(monitor_update) = monitor_opt {
7002                                                         has_monitor_update = true;
7003
7004                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7005                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7006                                                         continue 'peer_loop;
7007                                                 }
7008                                         }
7009                                         break 'chan_loop;
7010                                 }
7011                         }
7012                         break 'peer_loop;
7013                 }
7014
7015                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7016                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7017                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7018                 }
7019
7020                 has_update
7021         }
7022
7023         /// Check whether any channels have finished removing all pending updates after a shutdown
7024         /// exchange and can now send a closing_signed.
7025         /// Returns whether any closing_signed messages were generated.
7026         fn maybe_generate_initial_closing_signed(&self) -> bool {
7027                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7028                 let mut has_update = false;
7029                 let mut shutdown_results = Vec::new();
7030                 {
7031                         let per_peer_state = self.per_peer_state.read().unwrap();
7032
7033                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7034                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7035                                 let peer_state = &mut *peer_state_lock;
7036                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7037                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7038                                         match phase {
7039                                                 ChannelPhase::Funded(chan) => {
7040                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
7041                                                                 Ok((msg_opt, tx_opt, shutdown_result_opt)) => {
7042                                                                         if let Some(msg) = msg_opt {
7043                                                                                 has_update = true;
7044                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7045                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7046                                                                                 });
7047                                                                         }
7048                                                                         debug_assert_eq!(shutdown_result_opt.is_some(), chan.is_shutdown());
7049                                                                         if let Some(shutdown_result) = shutdown_result_opt {
7050                                                                                 shutdown_results.push(shutdown_result);
7051                                                                         }
7052                                                                         if let Some(tx) = tx_opt {
7053                                                                                 // We're done with this channel. We got a closing_signed and sent back
7054                                                                                 // a closing_signed with a closing transaction to broadcast.
7055                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7056                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7057                                                                                                 msg: update
7058                                                                                         });
7059                                                                                 }
7060
7061                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
7062
7063                                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
7064                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7065                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7066                                                                                 false
7067                                                                         } else { true }
7068                                                                 },
7069                                                                 Err(e) => {
7070                                                                         has_update = true;
7071                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7072                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7073                                                                         !close_channel
7074                                                                 }
7075                                                         }
7076                                                 },
7077                                                 _ => true, // Retain unfunded channels if present.
7078                                         }
7079                                 });
7080                         }
7081                 }
7082
7083                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7084                         let _ = handle_error!(self, err, counterparty_node_id);
7085                 }
7086
7087                 for shutdown_result in shutdown_results.drain(..) {
7088                         self.finish_close_channel(shutdown_result);
7089                 }
7090
7091                 has_update
7092         }
7093
7094         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7095         /// pushing the channel monitor update (if any) to the background events queue and removing the
7096         /// Channel object.
7097         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7098                 for mut failure in failed_channels.drain(..) {
7099                         // Either a commitment transactions has been confirmed on-chain or
7100                         // Channel::block_disconnected detected that the funding transaction has been
7101                         // reorganized out of the main chain.
7102                         // We cannot broadcast our latest local state via monitor update (as
7103                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7104                         // so we track the update internally and handle it when the user next calls
7105                         // timer_tick_occurred, guaranteeing we're running normally.
7106                         if let Some((counterparty_node_id, funding_txo, update)) = failure.monitor_update.take() {
7107                                 assert_eq!(update.updates.len(), 1);
7108                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7109                                         assert!(should_broadcast);
7110                                 } else { unreachable!(); }
7111                                 self.pending_background_events.lock().unwrap().push(
7112                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7113                                                 counterparty_node_id, funding_txo, update
7114                                         });
7115                         }
7116                         self.finish_close_channel(failure);
7117                 }
7118         }
7119
7120         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7121         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7122         /// not have an expiration unless otherwise set on the builder.
7123         ///
7124         /// # Privacy
7125         ///
7126         /// Uses a one-hop [`BlindedPath`] for the offer with [`ChannelManager::get_our_node_id`] as the
7127         /// introduction node and a derived signing pubkey for recipient privacy. As such, currently,
7128         /// the node must be announced. Otherwise, there is no way to find a path to the introduction
7129         /// node in order to send the [`InvoiceRequest`].
7130         ///
7131         /// # Limitations
7132         ///
7133         /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
7134         /// reply path.
7135         ///
7136         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7137         ///
7138         /// [`Offer`]: crate::offers::offer::Offer
7139         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7140         pub fn create_offer_builder(
7141                 &self, description: String
7142         ) -> OfferBuilder<DerivedMetadata, secp256k1::All> {
7143                 let node_id = self.get_our_node_id();
7144                 let expanded_key = &self.inbound_payment_key;
7145                 let entropy = &*self.entropy_source;
7146                 let secp_ctx = &self.secp_ctx;
7147                 let path = self.create_one_hop_blinded_path();
7148
7149                 OfferBuilder::deriving_signing_pubkey(description, node_id, expanded_key, entropy, secp_ctx)
7150                         .chain_hash(self.chain_hash)
7151                         .path(path)
7152         }
7153
7154         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7155         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7156         ///
7157         /// # Payment
7158         ///
7159         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7160         /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
7161         ///
7162         /// The builder will have the provided expiration set. Any changes to the expiration on the
7163         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7164         /// block time minus two hours is used for the current time when determining if the refund has
7165         /// expired.
7166         ///
7167         /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
7168         /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
7169         /// with an [`Event::InvoiceRequestFailed`].
7170         ///
7171         /// If `max_total_routing_fee_msat` is not specified, The default from
7172         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7173         ///
7174         /// # Privacy
7175         ///
7176         /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
7177         /// the introduction node and a derived payer id for payer privacy. As such, currently, the
7178         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7179         /// in order to send the [`Bolt12Invoice`].
7180         ///
7181         /// # Limitations
7182         ///
7183         /// Requires a direct connection to an introduction node in the responding
7184         /// [`Bolt12Invoice::payment_paths`].
7185         ///
7186         /// # Errors
7187         ///
7188         /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link
7189         /// or if `amount_msats` is invalid.
7190         ///
7191         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7192         ///
7193         /// [`Refund`]: crate::offers::refund::Refund
7194         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7195         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7196         pub fn create_refund_builder(
7197                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7198                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7199         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7200                 let node_id = self.get_our_node_id();
7201                 let expanded_key = &self.inbound_payment_key;
7202                 let entropy = &*self.entropy_source;
7203                 let secp_ctx = &self.secp_ctx;
7204                 let path = self.create_one_hop_blinded_path();
7205
7206                 let builder = RefundBuilder::deriving_payer_id(
7207                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7208                 )?
7209                         .chain_hash(self.chain_hash)
7210                         .absolute_expiry(absolute_expiry)
7211                         .path(path);
7212
7213                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7214                 self.pending_outbound_payments
7215                         .add_new_awaiting_invoice(
7216                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7217                         )
7218                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7219
7220                 Ok(builder)
7221         }
7222
7223         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7224         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7225         /// [`Bolt12Invoice`] once it is received.
7226         ///
7227         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7228         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7229         /// The optional parameters are used in the builder, if `Some`:
7230         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7231         ///   [`Offer::expects_quantity`] is `true`.
7232         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7233         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7234         ///
7235         /// If `max_total_routing_fee_msat` is not specified, The default from
7236         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7237         ///
7238         /// # Payment
7239         ///
7240         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7241         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7242         /// been sent.
7243         ///
7244         /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
7245         /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
7246         /// payment will fail with an [`Event::InvoiceRequestFailed`].
7247         ///
7248         /// # Privacy
7249         ///
7250         /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
7251         /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
7252         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7253         /// in order to send the [`Bolt12Invoice`].
7254         ///
7255         /// # Limitations
7256         ///
7257         /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
7258         /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
7259         /// [`Bolt12Invoice::payment_paths`].
7260         ///
7261         /// # Errors
7262         ///
7263         /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link
7264         /// or if the provided parameters are invalid for the offer.
7265         ///
7266         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7267         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7268         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7269         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7270         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7271         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7272         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7273         pub fn pay_for_offer(
7274                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7275                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7276                 max_total_routing_fee_msat: Option<u64>
7277         ) -> Result<(), Bolt12SemanticError> {
7278                 let expanded_key = &self.inbound_payment_key;
7279                 let entropy = &*self.entropy_source;
7280                 let secp_ctx = &self.secp_ctx;
7281
7282                 let builder = offer
7283                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7284                         .chain_hash(self.chain_hash)?;
7285                 let builder = match quantity {
7286                         None => builder,
7287                         Some(quantity) => builder.quantity(quantity)?,
7288                 };
7289                 let builder = match amount_msats {
7290                         None => builder,
7291                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7292                 };
7293                 let builder = match payer_note {
7294                         None => builder,
7295                         Some(payer_note) => builder.payer_note(payer_note),
7296                 };
7297
7298                 let invoice_request = builder.build_and_sign()?;
7299                 let reply_path = self.create_one_hop_blinded_path();
7300
7301                 let expiration = StaleExpiration::TimerTicks(1);
7302                 self.pending_outbound_payments
7303                         .add_new_awaiting_invoice(
7304                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7305                         )
7306                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7307
7308                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7309                 if offer.paths().is_empty() {
7310                         let message = new_pending_onion_message(
7311                                 OffersMessage::InvoiceRequest(invoice_request),
7312                                 Destination::Node(offer.signing_pubkey()),
7313                                 Some(reply_path),
7314                         );
7315                         pending_offers_messages.push(message);
7316                 } else {
7317                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7318                         // Using only one path could result in a failure if the path no longer exists. But only
7319                         // one invoice for a given payment id will be paid, even if more than one is received.
7320                         const REQUEST_LIMIT: usize = 10;
7321                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7322                                 let message = new_pending_onion_message(
7323                                         OffersMessage::InvoiceRequest(invoice_request.clone()),
7324                                         Destination::BlindedPath(path.clone()),
7325                                         Some(reply_path.clone()),
7326                                 );
7327                                 pending_offers_messages.push(message);
7328                         }
7329                 }
7330
7331                 Ok(())
7332         }
7333
7334         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7335         /// message.
7336         ///
7337         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7338         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7339         /// [`PaymentPreimage`].
7340         ///
7341         /// # Limitations
7342         ///
7343         /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
7344         /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
7345         /// node meeting the aforementioned criteria, but there's no guarantee that they will be
7346         /// received and no retries will be made.
7347         ///
7348         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7349         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7350                 let expanded_key = &self.inbound_payment_key;
7351                 let entropy = &*self.entropy_source;
7352                 let secp_ctx = &self.secp_ctx;
7353
7354                 let amount_msats = refund.amount_msats();
7355                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7356
7357                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7358                         Ok((payment_hash, payment_secret)) => {
7359                                 let payment_paths = vec![
7360                                         self.create_one_hop_blinded_payment_path(payment_secret),
7361                                 ];
7362                                 #[cfg(not(feature = "no-std"))]
7363                                 let builder = refund.respond_using_derived_keys(
7364                                         payment_paths, payment_hash, expanded_key, entropy
7365                                 )?;
7366                                 #[cfg(feature = "no-std")]
7367                                 let created_at = Duration::from_secs(
7368                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7369                                 );
7370                                 #[cfg(feature = "no-std")]
7371                                 let builder = refund.respond_using_derived_keys_no_std(
7372                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7373                                 )?;
7374                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7375                                 let reply_path = self.create_one_hop_blinded_path();
7376
7377                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7378                                 if refund.paths().is_empty() {
7379                                         let message = new_pending_onion_message(
7380                                                 OffersMessage::Invoice(invoice),
7381                                                 Destination::Node(refund.payer_id()),
7382                                                 Some(reply_path),
7383                                         );
7384                                         pending_offers_messages.push(message);
7385                                 } else {
7386                                         for path in refund.paths() {
7387                                                 let message = new_pending_onion_message(
7388                                                         OffersMessage::Invoice(invoice.clone()),
7389                                                         Destination::BlindedPath(path.clone()),
7390                                                         Some(reply_path.clone()),
7391                                                 );
7392                                                 pending_offers_messages.push(message);
7393                                         }
7394                                 }
7395
7396                                 Ok(())
7397                         },
7398                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7399                 }
7400         }
7401
7402         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7403         /// to pay us.
7404         ///
7405         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7406         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7407         ///
7408         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7409         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7410         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7411         /// passed directly to [`claim_funds`].
7412         ///
7413         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7414         ///
7415         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7416         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7417         ///
7418         /// # Note
7419         ///
7420         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7421         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7422         ///
7423         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7424         ///
7425         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7426         /// on versions of LDK prior to 0.0.114.
7427         ///
7428         /// [`claim_funds`]: Self::claim_funds
7429         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7430         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7431         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7432         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7433         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7434         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7435                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7436                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7437                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7438                         min_final_cltv_expiry_delta)
7439         }
7440
7441         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7442         /// stored external to LDK.
7443         ///
7444         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7445         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7446         /// the `min_value_msat` provided here, if one is provided.
7447         ///
7448         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7449         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7450         /// payments.
7451         ///
7452         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7453         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7454         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7455         /// sender "proof-of-payment" unless they have paid the required amount.
7456         ///
7457         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7458         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7459         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7460         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7461         /// invoices when no timeout is set.
7462         ///
7463         /// Note that we use block header time to time-out pending inbound payments (with some margin
7464         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7465         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7466         /// If you need exact expiry semantics, you should enforce them upon receipt of
7467         /// [`PaymentClaimable`].
7468         ///
7469         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7470         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7471         ///
7472         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7473         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7474         ///
7475         /// # Note
7476         ///
7477         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7478         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7479         ///
7480         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7481         ///
7482         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7483         /// on versions of LDK prior to 0.0.114.
7484         ///
7485         /// [`create_inbound_payment`]: Self::create_inbound_payment
7486         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7487         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7488                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7489                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7490                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7491                         min_final_cltv_expiry)
7492         }
7493
7494         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7495         /// previously returned from [`create_inbound_payment`].
7496         ///
7497         /// [`create_inbound_payment`]: Self::create_inbound_payment
7498         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7499                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7500         }
7501
7502         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7503         /// node.
7504         fn create_one_hop_blinded_path(&self) -> BlindedPath {
7505                 let entropy_source = self.entropy_source.deref();
7506                 let secp_ctx = &self.secp_ctx;
7507                 BlindedPath::one_hop_for_message(self.get_our_node_id(), entropy_source, secp_ctx).unwrap()
7508         }
7509
7510         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7511         /// node.
7512         fn create_one_hop_blinded_payment_path(
7513                 &self, payment_secret: PaymentSecret
7514         ) -> (BlindedPayInfo, BlindedPath) {
7515                 let entropy_source = self.entropy_source.deref();
7516                 let secp_ctx = &self.secp_ctx;
7517
7518                 let payee_node_id = self.get_our_node_id();
7519                 let max_cltv_expiry = self.best_block.read().unwrap().height() + LATENCY_GRACE_PERIOD_BLOCKS;
7520                 let payee_tlvs = ReceiveTlvs {
7521                         payment_secret,
7522                         payment_constraints: PaymentConstraints {
7523                                 max_cltv_expiry,
7524                                 htlc_minimum_msat: 1,
7525                         },
7526                 };
7527                 // TODO: Err for overflow?
7528                 BlindedPath::one_hop_for_payment(
7529                         payee_node_id, payee_tlvs, entropy_source, secp_ctx
7530                 ).unwrap()
7531         }
7532
7533         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
7534         /// are used when constructing the phantom invoice's route hints.
7535         ///
7536         /// [phantom node payments]: crate::sign::PhantomKeysManager
7537         pub fn get_phantom_scid(&self) -> u64 {
7538                 let best_block_height = self.best_block.read().unwrap().height();
7539                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7540                 loop {
7541                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7542                         // Ensure the generated scid doesn't conflict with a real channel.
7543                         match short_to_chan_info.get(&scid_candidate) {
7544                                 Some(_) => continue,
7545                                 None => return scid_candidate
7546                         }
7547                 }
7548         }
7549
7550         /// Gets route hints for use in receiving [phantom node payments].
7551         ///
7552         /// [phantom node payments]: crate::sign::PhantomKeysManager
7553         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
7554                 PhantomRouteHints {
7555                         channels: self.list_usable_channels(),
7556                         phantom_scid: self.get_phantom_scid(),
7557                         real_node_pubkey: self.get_our_node_id(),
7558                 }
7559         }
7560
7561         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
7562         /// used when constructing the route hints for HTLCs intended to be intercepted. See
7563         /// [`ChannelManager::forward_intercepted_htlc`].
7564         ///
7565         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
7566         /// times to get a unique scid.
7567         pub fn get_intercept_scid(&self) -> u64 {
7568                 let best_block_height = self.best_block.read().unwrap().height();
7569                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7570                 loop {
7571                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7572                         // Ensure the generated scid doesn't conflict with a real channel.
7573                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
7574                         return scid_candidate
7575                 }
7576         }
7577
7578         /// Gets inflight HTLC information by processing pending outbound payments that are in
7579         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
7580         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
7581                 let mut inflight_htlcs = InFlightHtlcs::new();
7582
7583                 let per_peer_state = self.per_peer_state.read().unwrap();
7584                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7585                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7586                         let peer_state = &mut *peer_state_lock;
7587                         for chan in peer_state.channel_by_id.values().filter_map(
7588                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7589                         ) {
7590                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
7591                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
7592                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
7593                                         }
7594                                 }
7595                         }
7596                 }
7597
7598                 inflight_htlcs
7599         }
7600
7601         #[cfg(any(test, feature = "_test_utils"))]
7602         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
7603                 let events = core::cell::RefCell::new(Vec::new());
7604                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
7605                 self.process_pending_events(&event_handler);
7606                 events.into_inner()
7607         }
7608
7609         #[cfg(feature = "_test_utils")]
7610         pub fn push_pending_event(&self, event: events::Event) {
7611                 let mut events = self.pending_events.lock().unwrap();
7612                 events.push_back((event, None));
7613         }
7614
7615         #[cfg(test)]
7616         pub fn pop_pending_event(&self) -> Option<events::Event> {
7617                 let mut events = self.pending_events.lock().unwrap();
7618                 events.pop_front().map(|(e, _)| e)
7619         }
7620
7621         #[cfg(test)]
7622         pub fn has_pending_payments(&self) -> bool {
7623                 self.pending_outbound_payments.has_pending_payments()
7624         }
7625
7626         #[cfg(test)]
7627         pub fn clear_pending_payments(&self) {
7628                 self.pending_outbound_payments.clear_pending_payments()
7629         }
7630
7631         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
7632         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
7633         /// operation. It will double-check that nothing *else* is also blocking the same channel from
7634         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
7635         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
7636                 loop {
7637                         let per_peer_state = self.per_peer_state.read().unwrap();
7638                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7639                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7640                                 let peer_state = &mut *peer_state_lck;
7641
7642                                 if let Some(blocker) = completed_blocker.take() {
7643                                         // Only do this on the first iteration of the loop.
7644                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
7645                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
7646                                         {
7647                                                 blockers.retain(|iter| iter != &blocker);
7648                                         }
7649                                 }
7650
7651                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7652                                         channel_funding_outpoint, counterparty_node_id) {
7653                                         // Check that, while holding the peer lock, we don't have anything else
7654                                         // blocking monitor updates for this channel. If we do, release the monitor
7655                                         // update(s) when those blockers complete.
7656                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
7657                                                 &channel_funding_outpoint.to_channel_id());
7658                                         break;
7659                                 }
7660
7661                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
7662                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7663                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
7664                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
7665                                                         log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
7666                                                                 channel_funding_outpoint.to_channel_id());
7667                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
7668                                                                 peer_state_lck, peer_state, per_peer_state, chan);
7669                                                         if further_update_exists {
7670                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
7671                                                                 // top of the loop.
7672                                                                 continue;
7673                                                         }
7674                                                 } else {
7675                                                         log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
7676                                                                 channel_funding_outpoint.to_channel_id());
7677                                                 }
7678                                         }
7679                                 }
7680                         } else {
7681                                 log_debug!(self.logger,
7682                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
7683                                         log_pubkey!(counterparty_node_id));
7684                         }
7685                         break;
7686                 }
7687         }
7688
7689         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
7690                 for action in actions {
7691                         match action {
7692                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7693                                         channel_funding_outpoint, counterparty_node_id
7694                                 } => {
7695                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
7696                                 }
7697                         }
7698                 }
7699         }
7700
7701         /// Processes any events asynchronously in the order they were generated since the last call
7702         /// using the given event handler.
7703         ///
7704         /// See the trait-level documentation of [`EventsProvider`] for requirements.
7705         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
7706                 &self, handler: H
7707         ) {
7708                 let mut ev;
7709                 process_events_body!(self, ev, { handler(ev).await });
7710         }
7711 }
7712
7713 fn create_fwd_pending_htlc_info(
7714         msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
7715         new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
7716         next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
7717 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
7718         debug_assert!(next_packet_pubkey_opt.is_some());
7719         let outgoing_packet = msgs::OnionPacket {
7720                 version: 0,
7721                 public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
7722                 hop_data: new_packet_bytes,
7723                 hmac: hop_hmac,
7724         };
7725
7726         let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
7727                 msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
7728                         (short_channel_id, amt_to_forward, outgoing_cltv_value),
7729                 msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
7730                         return Err(InboundOnionErr {
7731                                 msg: "Final Node OnionHopData provided for us as an intermediary node",
7732                                 err_code: 0x4000 | 22,
7733                                 err_data: Vec::new(),
7734                         }),
7735         };
7736
7737         Ok(PendingHTLCInfo {
7738                 routing: PendingHTLCRouting::Forward {
7739                         onion_packet: outgoing_packet,
7740                         short_channel_id,
7741                 },
7742                 payment_hash: msg.payment_hash,
7743                 incoming_shared_secret: shared_secret,
7744                 incoming_amt_msat: Some(msg.amount_msat),
7745                 outgoing_amt_msat: amt_to_forward,
7746                 outgoing_cltv_value,
7747                 skimmed_fee_msat: None,
7748         })
7749 }
7750
7751 fn create_recv_pending_htlc_info(
7752         hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
7753         amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
7754         counterparty_skimmed_fee_msat: Option<u64>, current_height: u32, accept_mpp_keysend: bool,
7755 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
7756         let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
7757                 msgs::InboundOnionPayload::Receive {
7758                         payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
7759                 } =>
7760                         (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
7761                 msgs::InboundOnionPayload::BlindedReceive {
7762                         amt_msat, total_msat, outgoing_cltv_value, payment_secret, ..
7763                 } => {
7764                         let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
7765                         (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
7766                 }
7767                 msgs::InboundOnionPayload::Forward { .. } => {
7768                         return Err(InboundOnionErr {
7769                                 err_code: 0x4000|22,
7770                                 err_data: Vec::new(),
7771                                 msg: "Got non final data with an HMAC of 0",
7772                         })
7773                 },
7774         };
7775         // final_incorrect_cltv_expiry
7776         if outgoing_cltv_value > cltv_expiry {
7777                 return Err(InboundOnionErr {
7778                         msg: "Upstream node set CLTV to less than the CLTV set by the sender",
7779                         err_code: 18,
7780                         err_data: cltv_expiry.to_be_bytes().to_vec()
7781                 })
7782         }
7783         // final_expiry_too_soon
7784         // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
7785         // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
7786         //
7787         // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
7788         // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
7789         // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
7790         if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
7791                 let mut err_data = Vec::with_capacity(12);
7792                 err_data.extend_from_slice(&amt_msat.to_be_bytes());
7793                 err_data.extend_from_slice(&current_height.to_be_bytes());
7794                 return Err(InboundOnionErr {
7795                         err_code: 0x4000 | 15, err_data,
7796                         msg: "The final CLTV expiry is too soon to handle",
7797                 });
7798         }
7799         if (!allow_underpay && onion_amt_msat > amt_msat) ||
7800                 (allow_underpay && onion_amt_msat >
7801                  amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
7802         {
7803                 return Err(InboundOnionErr {
7804                         err_code: 19,
7805                         err_data: amt_msat.to_be_bytes().to_vec(),
7806                         msg: "Upstream node sent less than we were supposed to receive in payment",
7807                 });
7808         }
7809
7810         let routing = if let Some(payment_preimage) = keysend_preimage {
7811                 // We need to check that the sender knows the keysend preimage before processing this
7812                 // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
7813                 // could discover the final destination of X, by probing the adjacent nodes on the route
7814                 // with a keysend payment of identical payment hash to X and observing the processing
7815                 // time discrepancies due to a hash collision with X.
7816                 let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
7817                 if hashed_preimage != payment_hash {
7818                         return Err(InboundOnionErr {
7819                                 err_code: 0x4000|22,
7820                                 err_data: Vec::new(),
7821                                 msg: "Payment preimage didn't match payment hash",
7822                         });
7823                 }
7824                 if !accept_mpp_keysend && payment_data.is_some() {
7825                         return Err(InboundOnionErr {
7826                                 err_code: 0x4000|22,
7827                                 err_data: Vec::new(),
7828                                 msg: "We don't support MPP keysend payments",
7829                         });
7830                 }
7831                 PendingHTLCRouting::ReceiveKeysend {
7832                         payment_data,
7833                         payment_preimage,
7834                         payment_metadata,
7835                         incoming_cltv_expiry: outgoing_cltv_value,
7836                         custom_tlvs,
7837                 }
7838         } else if let Some(data) = payment_data {
7839                 PendingHTLCRouting::Receive {
7840                         payment_data: data,
7841                         payment_metadata,
7842                         incoming_cltv_expiry: outgoing_cltv_value,
7843                         phantom_shared_secret,
7844                         custom_tlvs,
7845                 }
7846         } else {
7847                 return Err(InboundOnionErr {
7848                         err_code: 0x4000|0x2000|3,
7849                         err_data: Vec::new(),
7850                         msg: "We require payment_secrets",
7851                 });
7852         };
7853         Ok(PendingHTLCInfo {
7854                 routing,
7855                 payment_hash,
7856                 incoming_shared_secret: shared_secret,
7857                 incoming_amt_msat: Some(amt_msat),
7858                 outgoing_amt_msat: onion_amt_msat,
7859                 outgoing_cltv_value,
7860                 skimmed_fee_msat: counterparty_skimmed_fee_msat,
7861         })
7862 }
7863
7864 /// Peel one layer off an incoming onion, returning [`PendingHTLCInfo`] (either Forward or Receive).
7865 /// This does all the relevant context-free checks that LDK requires for payment relay or
7866 /// acceptance. If the payment is to be received, and the amount matches the expected amount for
7867 /// a given invoice, this indicates the [`msgs::UpdateAddHTLC`], once fully committed in the
7868 /// channel, will generate an [`Event::PaymentClaimable`].
7869 pub fn peel_payment_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
7870         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
7871         cur_height: u32, accept_mpp_keysend: bool,
7872 ) -> Result<PendingHTLCInfo, InboundOnionErr>
7873 where
7874         NS::Target: NodeSigner,
7875         L::Target: Logger,
7876 {
7877         let (hop, shared_secret, next_packet_details_opt) =
7878                 decode_incoming_update_add_htlc_onion(msg, node_signer, logger, secp_ctx
7879         ).map_err(|e| {
7880                 let (err_code, err_data) = match e {
7881                         HTLCFailureMsg::Malformed(m) => (m.failure_code, Vec::new()),
7882                         HTLCFailureMsg::Relay(r) => (0x4000 | 22, r.reason.data),
7883                 };
7884                 let msg = "Failed to decode update add htlc onion";
7885                 InboundOnionErr { msg, err_code, err_data }
7886         })?;
7887         Ok(match hop {
7888                 onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
7889                         let NextPacketDetails {
7890                                 next_packet_pubkey, outgoing_amt_msat: _, outgoing_scid: _, outgoing_cltv_value
7891                         } = match next_packet_details_opt {
7892                                 Some(next_packet_details) => next_packet_details,
7893                                 // Forward should always include the next hop details
7894                                 None => return Err(InboundOnionErr {
7895                                         msg: "Failed to decode update add htlc onion",
7896                                         err_code: 0x4000 | 22,
7897                                         err_data: Vec::new(),
7898                                 }),
7899                         };
7900
7901                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
7902                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
7903                         ) {
7904                                 return Err(InboundOnionErr {
7905                                         msg: err_msg,
7906                                         err_code: code,
7907                                         err_data: Vec::new(),
7908                                 });
7909                         }
7910                         create_fwd_pending_htlc_info(
7911                                 msg, next_hop_data, next_hop_hmac, new_packet_bytes, shared_secret,
7912                                 Some(next_packet_pubkey)
7913                         )?
7914                 },
7915                 onion_utils::Hop::Receive(received_data) => {
7916                         create_recv_pending_htlc_info(
7917                                 received_data, shared_secret, msg.payment_hash, msg.amount_msat, msg.cltv_expiry,
7918                                 None, false, msg.skimmed_fee_msat, cur_height, accept_mpp_keysend,
7919                         )?
7920                 }
7921         })
7922 }
7923
7924 struct NextPacketDetails {
7925         next_packet_pubkey: Result<PublicKey, secp256k1::Error>,
7926         outgoing_scid: u64,
7927         outgoing_amt_msat: u64,
7928         outgoing_cltv_value: u32,
7929 }
7930
7931 fn decode_incoming_update_add_htlc_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
7932         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
7933 ) -> Result<(onion_utils::Hop, [u8; 32], Option<NextPacketDetails>), HTLCFailureMsg>
7934 where
7935         NS::Target: NodeSigner,
7936         L::Target: Logger,
7937 {
7938         macro_rules! return_malformed_err {
7939                 ($msg: expr, $err_code: expr) => {
7940                         {
7941                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
7942                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7943                                         channel_id: msg.channel_id,
7944                                         htlc_id: msg.htlc_id,
7945                                         sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
7946                                         failure_code: $err_code,
7947                                 }));
7948                         }
7949                 }
7950         }
7951
7952         if let Err(_) = msg.onion_routing_packet.public_key {
7953                 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
7954         }
7955
7956         let shared_secret = node_signer.ecdh(
7957                 Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
7958         ).unwrap().secret_bytes();
7959
7960         if msg.onion_routing_packet.version != 0 {
7961                 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
7962                 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
7963                 //the hash doesn't really serve any purpose - in the case of hashing all data, the
7964                 //receiving node would have to brute force to figure out which version was put in the
7965                 //packet by the node that send us the message, in the case of hashing the hop_data, the
7966                 //node knows the HMAC matched, so they already know what is there...
7967                 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
7968         }
7969         macro_rules! return_err {
7970                 ($msg: expr, $err_code: expr, $data: expr) => {
7971                         {
7972                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
7973                                 return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
7974                                         channel_id: msg.channel_id,
7975                                         htlc_id: msg.htlc_id,
7976                                         reason: HTLCFailReason::reason($err_code, $data.to_vec())
7977                                                 .get_encrypted_failure_packet(&shared_secret, &None),
7978                                 }));
7979                         }
7980                 }
7981         }
7982
7983         let next_hop = match onion_utils::decode_next_payment_hop(
7984                 shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
7985                 msg.payment_hash, node_signer
7986         ) {
7987                 Ok(res) => res,
7988                 Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
7989                         return_malformed_err!(err_msg, err_code);
7990                 },
7991                 Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
7992                         return_err!(err_msg, err_code, &[0; 0]);
7993                 },
7994         };
7995
7996         let next_packet_details = match next_hop {
7997                 onion_utils::Hop::Forward {
7998                         next_hop_data: msgs::InboundOnionPayload::Forward {
7999                                 short_channel_id, amt_to_forward, outgoing_cltv_value
8000                         }, ..
8001                 } => {
8002                         let next_packet_pubkey = onion_utils::next_hop_pubkey(secp_ctx,
8003                                 msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
8004                         NextPacketDetails {
8005                                 next_packet_pubkey, outgoing_scid: short_channel_id,
8006                                 outgoing_amt_msat: amt_to_forward, outgoing_cltv_value
8007                         }
8008                 },
8009                 // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
8010                 // inbound channel's state.
8011                 onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
8012                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
8013                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
8014                 {
8015                         return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
8016                 }
8017         };
8018
8019         Ok((next_hop, shared_secret, Some(next_packet_details)))
8020 }
8021
8022 fn check_incoming_htlc_cltv(
8023         cur_height: u32, outgoing_cltv_value: u32, cltv_expiry: u32
8024 ) -> Result<(), (&'static str, u16)> {
8025         if (cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
8026                 return Err((
8027                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
8028                         0x1000 | 13, // incorrect_cltv_expiry
8029                 ));
8030         }
8031         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
8032         // but we want to be robust wrt to counterparty packet sanitization (see
8033         // HTLC_FAIL_BACK_BUFFER rationale).
8034         if cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
8035                 return Err(("CLTV expiry is too close", 0x1000 | 14));
8036         }
8037         if cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
8038                 return Err(("CLTV expiry is too far in the future", 21));
8039         }
8040         // If the HTLC expires ~now, don't bother trying to forward it to our
8041         // counterparty. They should fail it anyway, but we don't want to bother with
8042         // the round-trips or risk them deciding they definitely want the HTLC and
8043         // force-closing to ensure they get it if we're offline.
8044         // We previously had a much more aggressive check here which tried to ensure
8045         // our counterparty receives an HTLC which has *our* risk threshold met on it,
8046         // but there is no need to do that, and since we're a bit conservative with our
8047         // risk threshold it just results in failing to forward payments.
8048         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
8049                 return Err(("Outgoing CLTV value is too soon", 0x1000 | 14));
8050         }
8051
8052         Ok(())
8053 }
8054
8055 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>
8056 where
8057         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8058         T::Target: BroadcasterInterface,
8059         ES::Target: EntropySource,
8060         NS::Target: NodeSigner,
8061         SP::Target: SignerProvider,
8062         F::Target: FeeEstimator,
8063         R::Target: Router,
8064         L::Target: Logger,
8065 {
8066         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
8067         /// The returned array will contain `MessageSendEvent`s for different peers if
8068         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
8069         /// is always placed next to each other.
8070         ///
8071         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
8072         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
8073         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
8074         /// will randomly be placed first or last in the returned array.
8075         ///
8076         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
8077         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
8078         /// the `MessageSendEvent`s to the specific peer they were generated under.
8079         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
8080                 let events = RefCell::new(Vec::new());
8081                 PersistenceNotifierGuard::optionally_notify(self, || {
8082                         let mut result = NotifyOption::SkipPersistNoEvents;
8083
8084                         // TODO: This behavior should be documented. It's unintuitive that we query
8085                         // ChannelMonitors when clearing other events.
8086                         if self.process_pending_monitor_events() {
8087                                 result = NotifyOption::DoPersist;
8088                         }
8089
8090                         if self.check_free_holding_cells() {
8091                                 result = NotifyOption::DoPersist;
8092                         }
8093                         if self.maybe_generate_initial_closing_signed() {
8094                                 result = NotifyOption::DoPersist;
8095                         }
8096
8097                         let mut pending_events = Vec::new();
8098                         let per_peer_state = self.per_peer_state.read().unwrap();
8099                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8100                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8101                                 let peer_state = &mut *peer_state_lock;
8102                                 if peer_state.pending_msg_events.len() > 0 {
8103                                         pending_events.append(&mut peer_state.pending_msg_events);
8104                                 }
8105                         }
8106
8107                         if !pending_events.is_empty() {
8108                                 events.replace(pending_events);
8109                         }
8110
8111                         result
8112                 });
8113                 events.into_inner()
8114         }
8115 }
8116
8117 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>
8118 where
8119         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8120         T::Target: BroadcasterInterface,
8121         ES::Target: EntropySource,
8122         NS::Target: NodeSigner,
8123         SP::Target: SignerProvider,
8124         F::Target: FeeEstimator,
8125         R::Target: Router,
8126         L::Target: Logger,
8127 {
8128         /// Processes events that must be periodically handled.
8129         ///
8130         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
8131         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
8132         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
8133                 let mut ev;
8134                 process_events_body!(self, ev, handler.handle_event(ev));
8135         }
8136 }
8137
8138 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>
8139 where
8140         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8141         T::Target: BroadcasterInterface,
8142         ES::Target: EntropySource,
8143         NS::Target: NodeSigner,
8144         SP::Target: SignerProvider,
8145         F::Target: FeeEstimator,
8146         R::Target: Router,
8147         L::Target: Logger,
8148 {
8149         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
8150                 {
8151                         let best_block = self.best_block.read().unwrap();
8152                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
8153                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
8154                         assert_eq!(best_block.height(), height - 1,
8155                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
8156                 }
8157
8158                 self.transactions_confirmed(header, txdata, height);
8159                 self.best_block_updated(header, height);
8160         }
8161
8162         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
8163                 let _persistence_guard =
8164                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8165                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8166                 let new_height = height - 1;
8167                 {
8168                         let mut best_block = self.best_block.write().unwrap();
8169                         assert_eq!(best_block.block_hash(), header.block_hash(),
8170                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
8171                         assert_eq!(best_block.height(), height,
8172                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
8173                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
8174                 }
8175
8176                 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, &self.logger));
8177         }
8178 }
8179
8180 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>
8181 where
8182         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8183         T::Target: BroadcasterInterface,
8184         ES::Target: EntropySource,
8185         NS::Target: NodeSigner,
8186         SP::Target: SignerProvider,
8187         F::Target: FeeEstimator,
8188         R::Target: Router,
8189         L::Target: Logger,
8190 {
8191         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
8192                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8193                 // during initialization prior to the chain_monitor being fully configured in some cases.
8194                 // See the docs for `ChannelManagerReadArgs` for more.
8195
8196                 let block_hash = header.block_hash();
8197                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
8198
8199                 let _persistence_guard =
8200                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8201                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8202                 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger)
8203                         .map(|(a, b)| (a, Vec::new(), b)));
8204
8205                 let last_best_block_height = self.best_block.read().unwrap().height();
8206                 if height < last_best_block_height {
8207                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
8208                         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, &self.logger));
8209                 }
8210         }
8211
8212         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
8213                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8214                 // during initialization prior to the chain_monitor being fully configured in some cases.
8215                 // See the docs for `ChannelManagerReadArgs` for more.
8216
8217                 let block_hash = header.block_hash();
8218                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
8219
8220                 let _persistence_guard =
8221                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8222                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8223                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
8224
8225                 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger));
8226
8227                 macro_rules! max_time {
8228                         ($timestamp: expr) => {
8229                                 loop {
8230                                         // Update $timestamp to be the max of its current value and the block
8231                                         // timestamp. This should keep us close to the current time without relying on
8232                                         // having an explicit local time source.
8233                                         // Just in case we end up in a race, we loop until we either successfully
8234                                         // update $timestamp or decide we don't need to.
8235                                         let old_serial = $timestamp.load(Ordering::Acquire);
8236                                         if old_serial >= header.time as usize { break; }
8237                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8238                                                 break;
8239                                         }
8240                                 }
8241                         }
8242                 }
8243                 max_time!(self.highest_seen_timestamp);
8244                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8245                 payment_secrets.retain(|_, inbound_payment| {
8246                         inbound_payment.expiry_time > header.time as u64
8247                 });
8248         }
8249
8250         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
8251                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8252                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8253                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8254                         let peer_state = &mut *peer_state_lock;
8255                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8256                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
8257                                         res.push((funding_txo.txid, Some(block_hash)));
8258                                 }
8259                         }
8260                 }
8261                 res
8262         }
8263
8264         fn transaction_unconfirmed(&self, txid: &Txid) {
8265                 let _persistence_guard =
8266                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8267                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8268                 self.do_chain_event(None, |channel| {
8269                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8270                                 if funding_txo.txid == *txid {
8271                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
8272                                 } else { Ok((None, Vec::new(), None)) }
8273                         } else { Ok((None, Vec::new(), None)) }
8274                 });
8275         }
8276 }
8277
8278 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>
8279 where
8280         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8281         T::Target: BroadcasterInterface,
8282         ES::Target: EntropySource,
8283         NS::Target: NodeSigner,
8284         SP::Target: SignerProvider,
8285         F::Target: FeeEstimator,
8286         R::Target: Router,
8287         L::Target: Logger,
8288 {
8289         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8290         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8291         /// the function.
8292         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8293                         (&self, height_opt: Option<u32>, f: FN) {
8294                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8295                 // during initialization prior to the chain_monitor being fully configured in some cases.
8296                 // See the docs for `ChannelManagerReadArgs` for more.
8297
8298                 let mut failed_channels = Vec::new();
8299                 let mut timed_out_htlcs = Vec::new();
8300                 {
8301                         let per_peer_state = self.per_peer_state.read().unwrap();
8302                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8303                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8304                                 let peer_state = &mut *peer_state_lock;
8305                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8306                                 peer_state.channel_by_id.retain(|_, phase| {
8307                                         match phase {
8308                                                 // Retain unfunded channels.
8309                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8310                                                 ChannelPhase::Funded(channel) => {
8311                                                         let res = f(channel);
8312                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8313                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8314                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8315                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8316                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8317                                                                 }
8318                                                                 if let Some(channel_ready) = channel_ready_opt {
8319                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8320                                                                         if channel.context.is_usable() {
8321                                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8322                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8323                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8324                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8325                                                                                                 msg,
8326                                                                                         });
8327                                                                                 }
8328                                                                         } else {
8329                                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8330                                                                         }
8331                                                                 }
8332
8333                                                                 {
8334                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8335                                                                         emit_channel_ready_event!(pending_events, channel);
8336                                                                 }
8337
8338                                                                 if let Some(announcement_sigs) = announcement_sigs {
8339                                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8340                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8341                                                                                 node_id: channel.context.get_counterparty_node_id(),
8342                                                                                 msg: announcement_sigs,
8343                                                                         });
8344                                                                         if let Some(height) = height_opt {
8345                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8346                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8347                                                                                                 msg: announcement,
8348                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8349                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8350                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8351                                                                                         });
8352                                                                                 }
8353                                                                         }
8354                                                                 }
8355                                                                 if channel.is_our_channel_ready() {
8356                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8357                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8358                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8359                                                                                 // can relay using the real SCID at relay-time (i.e.
8360                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8361                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8362                                                                                 // is always consistent.
8363                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8364                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8365                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8366                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8367                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8368                                                                         }
8369                                                                 }
8370                                                         } else if let Err(reason) = res {
8371                                                                 update_maps_on_chan_removal!(self, &channel.context);
8372                                                                 // It looks like our counterparty went on-chain or funding transaction was
8373                                                                 // reorged out of the main chain. Close the channel.
8374                                                                 failed_channels.push(channel.context.force_shutdown(true));
8375                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8376                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
8377                                                                                 msg: update
8378                                                                         });
8379                                                                 }
8380                                                                 let reason_message = format!("{}", reason);
8381                                                                 self.issue_channel_close_events(&channel.context, reason);
8382                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8383                                                                         node_id: channel.context.get_counterparty_node_id(),
8384                                                                         action: msgs::ErrorAction::DisconnectPeer {
8385                                                                                 msg: Some(msgs::ErrorMessage {
8386                                                                                         channel_id: channel.context.channel_id(),
8387                                                                                         data: reason_message,
8388                                                                                 })
8389                                                                         },
8390                                                                 });
8391                                                                 return false;
8392                                                         }
8393                                                         true
8394                                                 }
8395                                         }
8396                                 });
8397                         }
8398                 }
8399
8400                 if let Some(height) = height_opt {
8401                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8402                                 payment.htlcs.retain(|htlc| {
8403                                         // If height is approaching the number of blocks we think it takes us to get
8404                                         // our commitment transaction confirmed before the HTLC expires, plus the
8405                                         // number of blocks we generally consider it to take to do a commitment update,
8406                                         // just give up on it and fail the HTLC.
8407                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8408                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8409                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8410
8411                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8412                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8413                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8414                                                 false
8415                                         } else { true }
8416                                 });
8417                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8418                         });
8419
8420                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8421                         intercepted_htlcs.retain(|_, htlc| {
8422                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8423                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8424                                                 short_channel_id: htlc.prev_short_channel_id,
8425                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8426                                                 htlc_id: htlc.prev_htlc_id,
8427                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8428                                                 phantom_shared_secret: None,
8429                                                 outpoint: htlc.prev_funding_outpoint,
8430                                         });
8431
8432                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8433                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8434                                                 _ => unreachable!(),
8435                                         };
8436                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8437                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8438                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8439                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8440                                         false
8441                                 } else { true }
8442                         });
8443                 }
8444
8445                 self.handle_init_event_channel_failures(failed_channels);
8446
8447                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8448                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8449                 }
8450         }
8451
8452         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8453         /// may have events that need processing.
8454         ///
8455         /// In order to check if this [`ChannelManager`] needs persisting, call
8456         /// [`Self::get_and_clear_needs_persistence`].
8457         ///
8458         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8459         /// [`ChannelManager`] and should instead register actions to be taken later.
8460         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8461                 self.event_persist_notifier.get_future()
8462         }
8463
8464         /// Returns true if this [`ChannelManager`] needs to be persisted.
8465         pub fn get_and_clear_needs_persistence(&self) -> bool {
8466                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8467         }
8468
8469         #[cfg(any(test, feature = "_test_utils"))]
8470         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8471                 self.event_persist_notifier.notify_pending()
8472         }
8473
8474         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8475         /// [`chain::Confirm`] interfaces.
8476         pub fn current_best_block(&self) -> BestBlock {
8477                 self.best_block.read().unwrap().clone()
8478         }
8479
8480         /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
8481         /// [`ChannelManager`].
8482         pub fn node_features(&self) -> NodeFeatures {
8483                 provided_node_features(&self.default_configuration)
8484         }
8485
8486         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
8487         /// [`ChannelManager`].
8488         ///
8489         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8490         /// or not. Thus, this method is not public.
8491         #[cfg(any(feature = "_test_utils", test))]
8492         pub fn bolt11_invoice_features(&self) -> Bolt11InvoiceFeatures {
8493                 provided_bolt11_invoice_features(&self.default_configuration)
8494         }
8495
8496         /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
8497         /// [`ChannelManager`].
8498         fn bolt12_invoice_features(&self) -> Bolt12InvoiceFeatures {
8499                 provided_bolt12_invoice_features(&self.default_configuration)
8500         }
8501
8502         /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
8503         /// [`ChannelManager`].
8504         pub fn channel_features(&self) -> ChannelFeatures {
8505                 provided_channel_features(&self.default_configuration)
8506         }
8507
8508         /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
8509         /// [`ChannelManager`].
8510         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8511                 provided_channel_type_features(&self.default_configuration)
8512         }
8513
8514         /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
8515         /// [`ChannelManager`].
8516         pub fn init_features(&self) -> InitFeatures {
8517                 provided_init_features(&self.default_configuration)
8518         }
8519 }
8520
8521 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8522         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8523 where
8524         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8525         T::Target: BroadcasterInterface,
8526         ES::Target: EntropySource,
8527         NS::Target: NodeSigner,
8528         SP::Target: SignerProvider,
8529         F::Target: FeeEstimator,
8530         R::Target: Router,
8531         L::Target: Logger,
8532 {
8533         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8534                 // Note that we never need to persist the updated ChannelManager for an inbound
8535                 // open_channel message - pre-funded channels are never written so there should be no
8536                 // change to the contents.
8537                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8538                         let res = self.internal_open_channel(counterparty_node_id, msg);
8539                         let persist = match &res {
8540                                 Err(e) if e.closes_channel() => {
8541                                         debug_assert!(false, "We shouldn't close a new channel");
8542                                         NotifyOption::DoPersist
8543                                 },
8544                                 _ => NotifyOption::SkipPersistHandleEvents,
8545                         };
8546                         let _ = handle_error!(self, res, *counterparty_node_id);
8547                         persist
8548                 });
8549         }
8550
8551         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8552                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8553                         "Dual-funded channels not supported".to_owned(),
8554                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8555         }
8556
8557         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8558                 // Note that we never need to persist the updated ChannelManager for an inbound
8559                 // accept_channel message - pre-funded channels are never written so there should be no
8560                 // change to the contents.
8561                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8562                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8563                         NotifyOption::SkipPersistHandleEvents
8564                 });
8565         }
8566
8567         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8568                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8569                         "Dual-funded channels not supported".to_owned(),
8570                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8571         }
8572
8573         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8574                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8575                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8576         }
8577
8578         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8579                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8580                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8581         }
8582
8583         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8584                 // Note that we never need to persist the updated ChannelManager for an inbound
8585                 // channel_ready message - while the channel's state will change, any channel_ready message
8586                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8587                 // will not force-close the channel on startup.
8588                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8589                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8590                         let persist = match &res {
8591                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8592                                 _ => NotifyOption::SkipPersistHandleEvents,
8593                         };
8594                         let _ = handle_error!(self, res, *counterparty_node_id);
8595                         persist
8596                 });
8597         }
8598
8599         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8600                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8601                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8602         }
8603
8604         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8605                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8606                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8607         }
8608
8609         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8610                 // Note that we never need to persist the updated ChannelManager for an inbound
8611                 // update_add_htlc message - the message itself doesn't change our channel state only the
8612                 // `commitment_signed` message afterwards will.
8613                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8614                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8615                         let persist = match &res {
8616                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8617                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8618                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8619                         };
8620                         let _ = handle_error!(self, res, *counterparty_node_id);
8621                         persist
8622                 });
8623         }
8624
8625         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8626                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8627                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8628         }
8629
8630         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8631                 // Note that we never need to persist the updated ChannelManager for an inbound
8632                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8633                 // `commitment_signed` message afterwards will.
8634                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8635                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8636                         let persist = match &res {
8637                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8638                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8639                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8640                         };
8641                         let _ = handle_error!(self, res, *counterparty_node_id);
8642                         persist
8643                 });
8644         }
8645
8646         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8647                 // Note that we never need to persist the updated ChannelManager for an inbound
8648                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8649                 // only the `commitment_signed` message afterwards will.
8650                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8651                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8652                         let persist = match &res {
8653                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8654                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8655                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8656                         };
8657                         let _ = handle_error!(self, res, *counterparty_node_id);
8658                         persist
8659                 });
8660         }
8661
8662         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8663                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8664                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8665         }
8666
8667         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8668                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8669                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8670         }
8671
8672         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8673                 // Note that we never need to persist the updated ChannelManager for an inbound
8674                 // update_fee message - the message itself doesn't change our channel state only the
8675                 // `commitment_signed` message afterwards will.
8676                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8677                         let res = self.internal_update_fee(counterparty_node_id, msg);
8678                         let persist = match &res {
8679                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8680                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8681                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8682                         };
8683                         let _ = handle_error!(self, res, *counterparty_node_id);
8684                         persist
8685                 });
8686         }
8687
8688         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8689                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8690                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8691         }
8692
8693         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8694                 PersistenceNotifierGuard::optionally_notify(self, || {
8695                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8696                                 persist
8697                         } else {
8698                                 NotifyOption::DoPersist
8699                         }
8700                 });
8701         }
8702
8703         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8704                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8705                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8706                         let persist = match &res {
8707                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8708                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8709                                 Ok(persist) => *persist,
8710                         };
8711                         let _ = handle_error!(self, res, *counterparty_node_id);
8712                         persist
8713                 });
8714         }
8715
8716         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8717                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8718                         self, || NotifyOption::SkipPersistHandleEvents);
8719                 let mut failed_channels = Vec::new();
8720                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8721                 let remove_peer = {
8722                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
8723                                 log_pubkey!(counterparty_node_id));
8724                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8725                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8726                                 let peer_state = &mut *peer_state_lock;
8727                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8728                                 peer_state.channel_by_id.retain(|_, phase| {
8729                                         let context = match phase {
8730                                                 ChannelPhase::Funded(chan) => {
8731                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger).is_ok() {
8732                                                                 // We only retain funded channels that are not shutdown.
8733                                                                 return true;
8734                                                         }
8735                                                         &mut chan.context
8736                                                 },
8737                                                 // Unfunded channels will always be removed.
8738                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8739                                                         &mut chan.context
8740                                                 },
8741                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8742                                                         &mut chan.context
8743                                                 },
8744                                         };
8745                                         // Clean up for removal.
8746                                         update_maps_on_chan_removal!(self, &context);
8747                                         self.issue_channel_close_events(&context, ClosureReason::DisconnectedPeer);
8748                                         failed_channels.push(context.force_shutdown(false));
8749                                         false
8750                                 });
8751                                 // Note that we don't bother generating any events for pre-accept channels -
8752                                 // they're not considered "channels" yet from the PoV of our events interface.
8753                                 peer_state.inbound_channel_request_by_id.clear();
8754                                 pending_msg_events.retain(|msg| {
8755                                         match msg {
8756                                                 // V1 Channel Establishment
8757                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8758                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8759                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8760                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8761                                                 // V2 Channel Establishment
8762                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8763                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8764                                                 // Common Channel Establishment
8765                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8766                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8767                                                 // Interactive Transaction Construction
8768                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8769                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8770                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8771                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8772                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8773                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8774                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8775                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8776                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8777                                                 // Channel Operations
8778                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8779                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8780                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8781                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8782                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8783                                                 &events::MessageSendEvent::HandleError { .. } => false,
8784                                                 // Gossip
8785                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8786                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8787                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8788                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8789                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8790                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8791                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8792                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8793                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8794                                         }
8795                                 });
8796                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8797                                 peer_state.is_connected = false;
8798                                 peer_state.ok_to_remove(true)
8799                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8800                 };
8801                 if remove_peer {
8802                         per_peer_state.remove(counterparty_node_id);
8803                 }
8804                 mem::drop(per_peer_state);
8805
8806                 for failure in failed_channels.drain(..) {
8807                         self.finish_close_channel(failure);
8808                 }
8809         }
8810
8811         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8812                 if !init_msg.features.supports_static_remote_key() {
8813                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8814                         return Err(());
8815                 }
8816
8817                 let mut res = Ok(());
8818
8819                 PersistenceNotifierGuard::optionally_notify(self, || {
8820                         // If we have too many peers connected which don't have funded channels, disconnect the
8821                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8822                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8823                         // peers connect, but we'll reject new channels from them.
8824                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8825                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8826
8827                         {
8828                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8829                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8830                                         hash_map::Entry::Vacant(e) => {
8831                                                 if inbound_peer_limited {
8832                                                         res = Err(());
8833                                                         return NotifyOption::SkipPersistNoEvents;
8834                                                 }
8835                                                 e.insert(Mutex::new(PeerState {
8836                                                         channel_by_id: HashMap::new(),
8837                                                         inbound_channel_request_by_id: HashMap::new(),
8838                                                         latest_features: init_msg.features.clone(),
8839                                                         pending_msg_events: Vec::new(),
8840                                                         in_flight_monitor_updates: BTreeMap::new(),
8841                                                         monitor_update_blocked_actions: BTreeMap::new(),
8842                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
8843                                                         is_connected: true,
8844                                                 }));
8845                                         },
8846                                         hash_map::Entry::Occupied(e) => {
8847                                                 let mut peer_state = e.get().lock().unwrap();
8848                                                 peer_state.latest_features = init_msg.features.clone();
8849
8850                                                 let best_block_height = self.best_block.read().unwrap().height();
8851                                                 if inbound_peer_limited &&
8852                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
8853                                                         peer_state.channel_by_id.len()
8854                                                 {
8855                                                         res = Err(());
8856                                                         return NotifyOption::SkipPersistNoEvents;
8857                                                 }
8858
8859                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
8860                                                 peer_state.is_connected = true;
8861                                         },
8862                                 }
8863                         }
8864
8865                         log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
8866
8867                         let per_peer_state = self.per_peer_state.read().unwrap();
8868                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8869                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8870                                 let peer_state = &mut *peer_state_lock;
8871                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8872
8873                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
8874                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else {
8875                                                 // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
8876                                                 // (so won't be recovered after a crash), they shouldn't exist here and we would never need to
8877                                                 // worry about closing and removing them.
8878                                                 debug_assert!(false);
8879                                                 None
8880                                         }
8881                                 ).for_each(|chan| {
8882                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
8883                                                 node_id: chan.context.get_counterparty_node_id(),
8884                                                 msg: chan.get_channel_reestablish(&self.logger),
8885                                         });
8886                                 });
8887                         }
8888
8889                         return NotifyOption::SkipPersistHandleEvents;
8890                         //TODO: Also re-broadcast announcement_signatures
8891                 });
8892                 res
8893         }
8894
8895         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
8896                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8897
8898                 match &msg.data as &str {
8899                         "cannot co-op close channel w/ active htlcs"|
8900                         "link failed to shutdown" =>
8901                         {
8902                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
8903                                 // send one while HTLCs are still present. The issue is tracked at
8904                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
8905                                 // to fix it but none so far have managed to land upstream. The issue appears to be
8906                                 // very low priority for the LND team despite being marked "P1".
8907                                 // We're not going to bother handling this in a sensible way, instead simply
8908                                 // repeating the Shutdown message on repeat until morale improves.
8909                                 if !msg.channel_id.is_zero() {
8910                                         let per_peer_state = self.per_peer_state.read().unwrap();
8911                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8912                                         if peer_state_mutex_opt.is_none() { return; }
8913                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
8914                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
8915                                                 if let Some(msg) = chan.get_outbound_shutdown() {
8916                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
8917                                                                 node_id: *counterparty_node_id,
8918                                                                 msg,
8919                                                         });
8920                                                 }
8921                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
8922                                                         node_id: *counterparty_node_id,
8923                                                         action: msgs::ErrorAction::SendWarningMessage {
8924                                                                 msg: msgs::WarningMessage {
8925                                                                         channel_id: msg.channel_id,
8926                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
8927                                                                 },
8928                                                                 log_level: Level::Trace,
8929                                                         }
8930                                                 });
8931                                         }
8932                                 }
8933                                 return;
8934                         }
8935                         _ => {}
8936                 }
8937
8938                 if msg.channel_id.is_zero() {
8939                         let channel_ids: Vec<ChannelId> = {
8940                                 let per_peer_state = self.per_peer_state.read().unwrap();
8941                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8942                                 if peer_state_mutex_opt.is_none() { return; }
8943                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8944                                 let peer_state = &mut *peer_state_lock;
8945                                 // Note that we don't bother generating any events for pre-accept channels -
8946                                 // they're not considered "channels" yet from the PoV of our events interface.
8947                                 peer_state.inbound_channel_request_by_id.clear();
8948                                 peer_state.channel_by_id.keys().cloned().collect()
8949                         };
8950                         for channel_id in channel_ids {
8951                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8952                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
8953                         }
8954                 } else {
8955                         {
8956                                 // First check if we can advance the channel type and try again.
8957                                 let per_peer_state = self.per_peer_state.read().unwrap();
8958                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8959                                 if peer_state_mutex_opt.is_none() { return; }
8960                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8961                                 let peer_state = &mut *peer_state_lock;
8962                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8963                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
8964                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
8965                                                         node_id: *counterparty_node_id,
8966                                                         msg,
8967                                                 });
8968                                                 return;
8969                                         }
8970                                 }
8971                         }
8972
8973                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8974                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
8975                 }
8976         }
8977
8978         fn provided_node_features(&self) -> NodeFeatures {
8979                 provided_node_features(&self.default_configuration)
8980         }
8981
8982         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
8983                 provided_init_features(&self.default_configuration)
8984         }
8985
8986         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8987                 Some(vec![self.chain_hash])
8988         }
8989
8990         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
8991                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8992                         "Dual-funded channels not supported".to_owned(),
8993                          msg.channel_id.clone())), *counterparty_node_id);
8994         }
8995
8996         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
8997                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8998                         "Dual-funded channels not supported".to_owned(),
8999                          msg.channel_id.clone())), *counterparty_node_id);
9000         }
9001
9002         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
9003                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9004                         "Dual-funded channels not supported".to_owned(),
9005                          msg.channel_id.clone())), *counterparty_node_id);
9006         }
9007
9008         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
9009                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9010                         "Dual-funded channels not supported".to_owned(),
9011                          msg.channel_id.clone())), *counterparty_node_id);
9012         }
9013
9014         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
9015                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9016                         "Dual-funded channels not supported".to_owned(),
9017                          msg.channel_id.clone())), *counterparty_node_id);
9018         }
9019
9020         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
9021                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9022                         "Dual-funded channels not supported".to_owned(),
9023                          msg.channel_id.clone())), *counterparty_node_id);
9024         }
9025
9026         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
9027                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9028                         "Dual-funded channels not supported".to_owned(),
9029                          msg.channel_id.clone())), *counterparty_node_id);
9030         }
9031
9032         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
9033                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9034                         "Dual-funded channels not supported".to_owned(),
9035                          msg.channel_id.clone())), *counterparty_node_id);
9036         }
9037
9038         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
9039                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9040                         "Dual-funded channels not supported".to_owned(),
9041                          msg.channel_id.clone())), *counterparty_node_id);
9042         }
9043 }
9044
9045 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9046 OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
9047 where
9048         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9049         T::Target: BroadcasterInterface,
9050         ES::Target: EntropySource,
9051         NS::Target: NodeSigner,
9052         SP::Target: SignerProvider,
9053         F::Target: FeeEstimator,
9054         R::Target: Router,
9055         L::Target: Logger,
9056 {
9057         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
9058                 let secp_ctx = &self.secp_ctx;
9059                 let expanded_key = &self.inbound_payment_key;
9060
9061                 match message {
9062                         OffersMessage::InvoiceRequest(invoice_request) => {
9063                                 let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
9064                                         &invoice_request
9065                                 ) {
9066                                         Ok(amount_msats) => Some(amount_msats),
9067                                         Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
9068                                 };
9069                                 let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
9070                                         Ok(invoice_request) => invoice_request,
9071                                         Err(()) => {
9072                                                 let error = Bolt12SemanticError::InvalidMetadata;
9073                                                 return Some(OffersMessage::InvoiceError(error.into()));
9074                                         },
9075                                 };
9076                                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9077
9078                                 match self.create_inbound_payment(amount_msats, relative_expiry, None) {
9079                                         Ok((payment_hash, payment_secret)) if invoice_request.keys.is_some() => {
9080                                                 let payment_paths = vec![
9081                                                         self.create_one_hop_blinded_payment_path(payment_secret),
9082                                                 ];
9083                                                 #[cfg(not(feature = "no-std"))]
9084                                                 let builder = invoice_request.respond_using_derived_keys(
9085                                                         payment_paths, payment_hash
9086                                                 );
9087                                                 #[cfg(feature = "no-std")]
9088                                                 let created_at = Duration::from_secs(
9089                                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9090                                                 );
9091                                                 #[cfg(feature = "no-std")]
9092                                                 let builder = invoice_request.respond_using_derived_keys_no_std(
9093                                                         payment_paths, payment_hash, created_at
9094                                                 );
9095                                                 match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
9096                                                         Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
9097                                                         Err(error) => Some(OffersMessage::InvoiceError(error.into())),
9098                                                 }
9099                                         },
9100                                         Ok((payment_hash, payment_secret)) => {
9101                                                 let payment_paths = vec![
9102                                                         self.create_one_hop_blinded_payment_path(payment_secret),
9103                                                 ];
9104                                                 #[cfg(not(feature = "no-std"))]
9105                                                 let builder = invoice_request.respond_with(payment_paths, payment_hash);
9106                                                 #[cfg(feature = "no-std")]
9107                                                 let created_at = Duration::from_secs(
9108                                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9109                                                 );
9110                                                 #[cfg(feature = "no-std")]
9111                                                 let builder = invoice_request.respond_with_no_std(
9112                                                         payment_paths, payment_hash, created_at
9113                                                 );
9114                                                 let response = builder.and_then(|builder| builder.allow_mpp().build())
9115                                                         .map_err(|e| OffersMessage::InvoiceError(e.into()))
9116                                                         .and_then(|invoice|
9117                                                                 match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
9118                                                                         Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
9119                                                                         Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
9120                                                                                         InvoiceError::from_string("Failed signing invoice".to_string())
9121                                                                         )),
9122                                                                         Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
9123                                                                                         InvoiceError::from_string("Failed invoice signature verification".to_string())
9124                                                                         )),
9125                                                                 });
9126                                                 match response {
9127                                                         Ok(invoice) => Some(invoice),
9128                                                         Err(error) => Some(error),
9129                                                 }
9130                                         },
9131                                         Err(()) => {
9132                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::InvalidAmount.into()))
9133                                         },
9134                                 }
9135                         },
9136                         OffersMessage::Invoice(invoice) => {
9137                                 match invoice.verify(expanded_key, secp_ctx) {
9138                                         Err(()) => {
9139                                                 Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
9140                                         },
9141                                         Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
9142                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
9143                                         },
9144                                         Ok(payment_id) => {
9145                                                 if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
9146                                                         log_trace!(self.logger, "Failed paying invoice: {:?}", e);
9147                                                         Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
9148                                                 } else {
9149                                                         None
9150                                                 }
9151                                         },
9152                                 }
9153                         },
9154                         OffersMessage::InvoiceError(invoice_error) => {
9155                                 log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
9156                                 None
9157                         },
9158                 }
9159         }
9160
9161         fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> {
9162                 core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
9163         }
9164 }
9165
9166 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
9167 /// [`ChannelManager`].
9168 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
9169         let mut node_features = provided_init_features(config).to_context();
9170         node_features.set_keysend_optional();
9171         node_features
9172 }
9173
9174 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
9175 /// [`ChannelManager`].
9176 ///
9177 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
9178 /// or not. Thus, this method is not public.
9179 #[cfg(any(feature = "_test_utils", test))]
9180 pub(crate) fn provided_bolt11_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
9181         provided_init_features(config).to_context()
9182 }
9183
9184 /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
9185 /// [`ChannelManager`].
9186 pub(crate) fn provided_bolt12_invoice_features(config: &UserConfig) -> Bolt12InvoiceFeatures {
9187         provided_init_features(config).to_context()
9188 }
9189
9190 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
9191 /// [`ChannelManager`].
9192 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
9193         provided_init_features(config).to_context()
9194 }
9195
9196 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
9197 /// [`ChannelManager`].
9198 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
9199         ChannelTypeFeatures::from_init(&provided_init_features(config))
9200 }
9201
9202 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
9203 /// [`ChannelManager`].
9204 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
9205         // Note that if new features are added here which other peers may (eventually) require, we
9206         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
9207         // [`ErroringMessageHandler`].
9208         let mut features = InitFeatures::empty();
9209         features.set_data_loss_protect_required();
9210         features.set_upfront_shutdown_script_optional();
9211         features.set_variable_length_onion_required();
9212         features.set_static_remote_key_required();
9213         features.set_payment_secret_required();
9214         features.set_basic_mpp_optional();
9215         features.set_wumbo_optional();
9216         features.set_shutdown_any_segwit_optional();
9217         features.set_channel_type_optional();
9218         features.set_scid_privacy_optional();
9219         features.set_zero_conf_optional();
9220         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
9221                 features.set_anchors_zero_fee_htlc_tx_optional();
9222         }
9223         features
9224 }
9225
9226 const SERIALIZATION_VERSION: u8 = 1;
9227 const MIN_SERIALIZATION_VERSION: u8 = 1;
9228
9229 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
9230         (2, fee_base_msat, required),
9231         (4, fee_proportional_millionths, required),
9232         (6, cltv_expiry_delta, required),
9233 });
9234
9235 impl_writeable_tlv_based!(ChannelCounterparty, {
9236         (2, node_id, required),
9237         (4, features, required),
9238         (6, unspendable_punishment_reserve, required),
9239         (8, forwarding_info, option),
9240         (9, outbound_htlc_minimum_msat, option),
9241         (11, outbound_htlc_maximum_msat, option),
9242 });
9243
9244 impl Writeable for ChannelDetails {
9245         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9246                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9247                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9248                 let user_channel_id_low = self.user_channel_id as u64;
9249                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
9250                 write_tlv_fields!(writer, {
9251                         (1, self.inbound_scid_alias, option),
9252                         (2, self.channel_id, required),
9253                         (3, self.channel_type, option),
9254                         (4, self.counterparty, required),
9255                         (5, self.outbound_scid_alias, option),
9256                         (6, self.funding_txo, option),
9257                         (7, self.config, option),
9258                         (8, self.short_channel_id, option),
9259                         (9, self.confirmations, option),
9260                         (10, self.channel_value_satoshis, required),
9261                         (12, self.unspendable_punishment_reserve, option),
9262                         (14, user_channel_id_low, required),
9263                         (16, self.balance_msat, required),
9264                         (18, self.outbound_capacity_msat, required),
9265                         (19, self.next_outbound_htlc_limit_msat, required),
9266                         (20, self.inbound_capacity_msat, required),
9267                         (21, self.next_outbound_htlc_minimum_msat, required),
9268                         (22, self.confirmations_required, option),
9269                         (24, self.force_close_spend_delay, option),
9270                         (26, self.is_outbound, required),
9271                         (28, self.is_channel_ready, required),
9272                         (30, self.is_usable, required),
9273                         (32, self.is_public, required),
9274                         (33, self.inbound_htlc_minimum_msat, option),
9275                         (35, self.inbound_htlc_maximum_msat, option),
9276                         (37, user_channel_id_high_opt, option),
9277                         (39, self.feerate_sat_per_1000_weight, option),
9278                         (41, self.channel_shutdown_state, option),
9279                 });
9280                 Ok(())
9281         }
9282 }
9283
9284 impl Readable for ChannelDetails {
9285         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9286                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9287                         (1, inbound_scid_alias, option),
9288                         (2, channel_id, required),
9289                         (3, channel_type, option),
9290                         (4, counterparty, required),
9291                         (5, outbound_scid_alias, option),
9292                         (6, funding_txo, option),
9293                         (7, config, option),
9294                         (8, short_channel_id, option),
9295                         (9, confirmations, option),
9296                         (10, channel_value_satoshis, required),
9297                         (12, unspendable_punishment_reserve, option),
9298                         (14, user_channel_id_low, required),
9299                         (16, balance_msat, required),
9300                         (18, outbound_capacity_msat, required),
9301                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
9302                         // filled in, so we can safely unwrap it here.
9303                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
9304                         (20, inbound_capacity_msat, required),
9305                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
9306                         (22, confirmations_required, option),
9307                         (24, force_close_spend_delay, option),
9308                         (26, is_outbound, required),
9309                         (28, is_channel_ready, required),
9310                         (30, is_usable, required),
9311                         (32, is_public, required),
9312                         (33, inbound_htlc_minimum_msat, option),
9313                         (35, inbound_htlc_maximum_msat, option),
9314                         (37, user_channel_id_high_opt, option),
9315                         (39, feerate_sat_per_1000_weight, option),
9316                         (41, channel_shutdown_state, option),
9317                 });
9318
9319                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9320                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9321                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
9322                 let user_channel_id = user_channel_id_low as u128 +
9323                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
9324
9325                 Ok(Self {
9326                         inbound_scid_alias,
9327                         channel_id: channel_id.0.unwrap(),
9328                         channel_type,
9329                         counterparty: counterparty.0.unwrap(),
9330                         outbound_scid_alias,
9331                         funding_txo,
9332                         config,
9333                         short_channel_id,
9334                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
9335                         unspendable_punishment_reserve,
9336                         user_channel_id,
9337                         balance_msat: balance_msat.0.unwrap(),
9338                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
9339                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
9340                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
9341                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
9342                         confirmations_required,
9343                         confirmations,
9344                         force_close_spend_delay,
9345                         is_outbound: is_outbound.0.unwrap(),
9346                         is_channel_ready: is_channel_ready.0.unwrap(),
9347                         is_usable: is_usable.0.unwrap(),
9348                         is_public: is_public.0.unwrap(),
9349                         inbound_htlc_minimum_msat,
9350                         inbound_htlc_maximum_msat,
9351                         feerate_sat_per_1000_weight,
9352                         channel_shutdown_state,
9353                 })
9354         }
9355 }
9356
9357 impl_writeable_tlv_based!(PhantomRouteHints, {
9358         (2, channels, required_vec),
9359         (4, phantom_scid, required),
9360         (6, real_node_pubkey, required),
9361 });
9362
9363 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
9364         (0, Forward) => {
9365                 (0, onion_packet, required),
9366                 (2, short_channel_id, required),
9367         },
9368         (1, Receive) => {
9369                 (0, payment_data, required),
9370                 (1, phantom_shared_secret, option),
9371                 (2, incoming_cltv_expiry, required),
9372                 (3, payment_metadata, option),
9373                 (5, custom_tlvs, optional_vec),
9374         },
9375         (2, ReceiveKeysend) => {
9376                 (0, payment_preimage, required),
9377                 (2, incoming_cltv_expiry, required),
9378                 (3, payment_metadata, option),
9379                 (4, payment_data, option), // Added in 0.0.116
9380                 (5, custom_tlvs, optional_vec),
9381         },
9382 ;);
9383
9384 impl_writeable_tlv_based!(PendingHTLCInfo, {
9385         (0, routing, required),
9386         (2, incoming_shared_secret, required),
9387         (4, payment_hash, required),
9388         (6, outgoing_amt_msat, required),
9389         (8, outgoing_cltv_value, required),
9390         (9, incoming_amt_msat, option),
9391         (10, skimmed_fee_msat, option),
9392 });
9393
9394
9395 impl Writeable for HTLCFailureMsg {
9396         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9397                 match self {
9398                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9399                                 0u8.write(writer)?;
9400                                 channel_id.write(writer)?;
9401                                 htlc_id.write(writer)?;
9402                                 reason.write(writer)?;
9403                         },
9404                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9405                                 channel_id, htlc_id, sha256_of_onion, failure_code
9406                         }) => {
9407                                 1u8.write(writer)?;
9408                                 channel_id.write(writer)?;
9409                                 htlc_id.write(writer)?;
9410                                 sha256_of_onion.write(writer)?;
9411                                 failure_code.write(writer)?;
9412                         },
9413                 }
9414                 Ok(())
9415         }
9416 }
9417
9418 impl Readable for HTLCFailureMsg {
9419         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9420                 let id: u8 = Readable::read(reader)?;
9421                 match id {
9422                         0 => {
9423                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9424                                         channel_id: Readable::read(reader)?,
9425                                         htlc_id: Readable::read(reader)?,
9426                                         reason: Readable::read(reader)?,
9427                                 }))
9428                         },
9429                         1 => {
9430                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9431                                         channel_id: Readable::read(reader)?,
9432                                         htlc_id: Readable::read(reader)?,
9433                                         sha256_of_onion: Readable::read(reader)?,
9434                                         failure_code: Readable::read(reader)?,
9435                                 }))
9436                         },
9437                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9438                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9439                         // messages contained in the variants.
9440                         // In version 0.0.101, support for reading the variants with these types was added, and
9441                         // we should migrate to writing these variants when UpdateFailHTLC or
9442                         // UpdateFailMalformedHTLC get TLV fields.
9443                         2 => {
9444                                 let length: BigSize = Readable::read(reader)?;
9445                                 let mut s = FixedLengthReader::new(reader, length.0);
9446                                 let res = Readable::read(&mut s)?;
9447                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9448                                 Ok(HTLCFailureMsg::Relay(res))
9449                         },
9450                         3 => {
9451                                 let length: BigSize = Readable::read(reader)?;
9452                                 let mut s = FixedLengthReader::new(reader, length.0);
9453                                 let res = Readable::read(&mut s)?;
9454                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9455                                 Ok(HTLCFailureMsg::Malformed(res))
9456                         },
9457                         _ => Err(DecodeError::UnknownRequiredFeature),
9458                 }
9459         }
9460 }
9461
9462 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9463         (0, Forward),
9464         (1, Fail),
9465 );
9466
9467 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9468         (0, short_channel_id, required),
9469         (1, phantom_shared_secret, option),
9470         (2, outpoint, required),
9471         (4, htlc_id, required),
9472         (6, incoming_packet_shared_secret, required),
9473         (7, user_channel_id, option),
9474 });
9475
9476 impl Writeable for ClaimableHTLC {
9477         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9478                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9479                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9480                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9481                 };
9482                 write_tlv_fields!(writer, {
9483                         (0, self.prev_hop, required),
9484                         (1, self.total_msat, required),
9485                         (2, self.value, required),
9486                         (3, self.sender_intended_value, required),
9487                         (4, payment_data, option),
9488                         (5, self.total_value_received, option),
9489                         (6, self.cltv_expiry, required),
9490                         (8, keysend_preimage, option),
9491                         (10, self.counterparty_skimmed_fee_msat, option),
9492                 });
9493                 Ok(())
9494         }
9495 }
9496
9497 impl Readable for ClaimableHTLC {
9498         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9499                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9500                         (0, prev_hop, required),
9501                         (1, total_msat, option),
9502                         (2, value_ser, required),
9503                         (3, sender_intended_value, option),
9504                         (4, payment_data_opt, option),
9505                         (5, total_value_received, option),
9506                         (6, cltv_expiry, required),
9507                         (8, keysend_preimage, option),
9508                         (10, counterparty_skimmed_fee_msat, option),
9509                 });
9510                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9511                 let value = value_ser.0.unwrap();
9512                 let onion_payload = match keysend_preimage {
9513                         Some(p) => {
9514                                 if payment_data.is_some() {
9515                                         return Err(DecodeError::InvalidValue)
9516                                 }
9517                                 if total_msat.is_none() {
9518                                         total_msat = Some(value);
9519                                 }
9520                                 OnionPayload::Spontaneous(p)
9521                         },
9522                         None => {
9523                                 if total_msat.is_none() {
9524                                         if payment_data.is_none() {
9525                                                 return Err(DecodeError::InvalidValue)
9526                                         }
9527                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9528                                 }
9529                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9530                         },
9531                 };
9532                 Ok(Self {
9533                         prev_hop: prev_hop.0.unwrap(),
9534                         timer_ticks: 0,
9535                         value,
9536                         sender_intended_value: sender_intended_value.unwrap_or(value),
9537                         total_value_received,
9538                         total_msat: total_msat.unwrap(),
9539                         onion_payload,
9540                         cltv_expiry: cltv_expiry.0.unwrap(),
9541                         counterparty_skimmed_fee_msat,
9542                 })
9543         }
9544 }
9545
9546 impl Readable for HTLCSource {
9547         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9548                 let id: u8 = Readable::read(reader)?;
9549                 match id {
9550                         0 => {
9551                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9552                                 let mut first_hop_htlc_msat: u64 = 0;
9553                                 let mut path_hops = Vec::new();
9554                                 let mut payment_id = None;
9555                                 let mut payment_params: Option<PaymentParameters> = None;
9556                                 let mut blinded_tail: Option<BlindedTail> = None;
9557                                 read_tlv_fields!(reader, {
9558                                         (0, session_priv, required),
9559                                         (1, payment_id, option),
9560                                         (2, first_hop_htlc_msat, required),
9561                                         (4, path_hops, required_vec),
9562                                         (5, payment_params, (option: ReadableArgs, 0)),
9563                                         (6, blinded_tail, option),
9564                                 });
9565                                 if payment_id.is_none() {
9566                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9567                                         // instead.
9568                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9569                                 }
9570                                 let path = Path { hops: path_hops, blinded_tail };
9571                                 if path.hops.len() == 0 {
9572                                         return Err(DecodeError::InvalidValue);
9573                                 }
9574                                 if let Some(params) = payment_params.as_mut() {
9575                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9576                                                 if final_cltv_expiry_delta == &0 {
9577                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9578                                                 }
9579                                         }
9580                                 }
9581                                 Ok(HTLCSource::OutboundRoute {
9582                                         session_priv: session_priv.0.unwrap(),
9583                                         first_hop_htlc_msat,
9584                                         path,
9585                                         payment_id: payment_id.unwrap(),
9586                                 })
9587                         }
9588                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9589                         _ => Err(DecodeError::UnknownRequiredFeature),
9590                 }
9591         }
9592 }
9593
9594 impl Writeable for HTLCSource {
9595         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9596                 match self {
9597                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9598                                 0u8.write(writer)?;
9599                                 let payment_id_opt = Some(payment_id);
9600                                 write_tlv_fields!(writer, {
9601                                         (0, session_priv, required),
9602                                         (1, payment_id_opt, option),
9603                                         (2, first_hop_htlc_msat, required),
9604                                         // 3 was previously used to write a PaymentSecret for the payment.
9605                                         (4, path.hops, required_vec),
9606                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9607                                         (6, path.blinded_tail, option),
9608                                  });
9609                         }
9610                         HTLCSource::PreviousHopData(ref field) => {
9611                                 1u8.write(writer)?;
9612                                 field.write(writer)?;
9613                         }
9614                 }
9615                 Ok(())
9616         }
9617 }
9618
9619 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9620         (0, forward_info, required),
9621         (1, prev_user_channel_id, (default_value, 0)),
9622         (2, prev_short_channel_id, required),
9623         (4, prev_htlc_id, required),
9624         (6, prev_funding_outpoint, required),
9625 });
9626
9627 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
9628         (1, FailHTLC) => {
9629                 (0, htlc_id, required),
9630                 (2, err_packet, required),
9631         };
9632         (0, AddHTLC)
9633 );
9634
9635 impl_writeable_tlv_based!(PendingInboundPayment, {
9636         (0, payment_secret, required),
9637         (2, expiry_time, required),
9638         (4, user_payment_id, required),
9639         (6, payment_preimage, required),
9640         (8, min_value_msat, required),
9641 });
9642
9643 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>
9644 where
9645         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9646         T::Target: BroadcasterInterface,
9647         ES::Target: EntropySource,
9648         NS::Target: NodeSigner,
9649         SP::Target: SignerProvider,
9650         F::Target: FeeEstimator,
9651         R::Target: Router,
9652         L::Target: Logger,
9653 {
9654         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9655                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9656
9657                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9658
9659                 self.chain_hash.write(writer)?;
9660                 {
9661                         let best_block = self.best_block.read().unwrap();
9662                         best_block.height().write(writer)?;
9663                         best_block.block_hash().write(writer)?;
9664                 }
9665
9666                 let mut serializable_peer_count: u64 = 0;
9667                 {
9668                         let per_peer_state = self.per_peer_state.read().unwrap();
9669                         let mut number_of_funded_channels = 0;
9670                         for (_, peer_state_mutex) in per_peer_state.iter() {
9671                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9672                                 let peer_state = &mut *peer_state_lock;
9673                                 if !peer_state.ok_to_remove(false) {
9674                                         serializable_peer_count += 1;
9675                                 }
9676
9677                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9678                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9679                                 ).count();
9680                         }
9681
9682                         (number_of_funded_channels as u64).write(writer)?;
9683
9684                         for (_, peer_state_mutex) in per_peer_state.iter() {
9685                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9686                                 let peer_state = &mut *peer_state_lock;
9687                                 for channel in peer_state.channel_by_id.iter().filter_map(
9688                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9689                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9690                                         } else { None }
9691                                 ) {
9692                                         channel.write(writer)?;
9693                                 }
9694                         }
9695                 }
9696
9697                 {
9698                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9699                         (forward_htlcs.len() as u64).write(writer)?;
9700                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9701                                 short_channel_id.write(writer)?;
9702                                 (pending_forwards.len() as u64).write(writer)?;
9703                                 for forward in pending_forwards {
9704                                         forward.write(writer)?;
9705                                 }
9706                         }
9707                 }
9708
9709                 let per_peer_state = self.per_peer_state.write().unwrap();
9710
9711                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9712                 let claimable_payments = self.claimable_payments.lock().unwrap();
9713                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9714
9715                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9716                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9717                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9718                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9719                         payment_hash.write(writer)?;
9720                         (payment.htlcs.len() as u64).write(writer)?;
9721                         for htlc in payment.htlcs.iter() {
9722                                 htlc.write(writer)?;
9723                         }
9724                         htlc_purposes.push(&payment.purpose);
9725                         htlc_onion_fields.push(&payment.onion_fields);
9726                 }
9727
9728                 let mut monitor_update_blocked_actions_per_peer = None;
9729                 let mut peer_states = Vec::new();
9730                 for (_, peer_state_mutex) in per_peer_state.iter() {
9731                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9732                         // of a lockorder violation deadlock - no other thread can be holding any
9733                         // per_peer_state lock at all.
9734                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9735                 }
9736
9737                 (serializable_peer_count).write(writer)?;
9738                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9739                         // Peers which we have no channels to should be dropped once disconnected. As we
9740                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9741                         // consider all peers as disconnected here. There's therefore no need write peers with
9742                         // no channels.
9743                         if !peer_state.ok_to_remove(false) {
9744                                 peer_pubkey.write(writer)?;
9745                                 peer_state.latest_features.write(writer)?;
9746                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9747                                         monitor_update_blocked_actions_per_peer
9748                                                 .get_or_insert_with(Vec::new)
9749                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9750                                 }
9751                         }
9752                 }
9753
9754                 let events = self.pending_events.lock().unwrap();
9755                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9756                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9757                 // refuse to read the new ChannelManager.
9758                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9759                 if events_not_backwards_compatible {
9760                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9761                         // well save the space and not write any events here.
9762                         0u64.write(writer)?;
9763                 } else {
9764                         (events.len() as u64).write(writer)?;
9765                         for (event, _) in events.iter() {
9766                                 event.write(writer)?;
9767                         }
9768                 }
9769
9770                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
9771                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
9772                 // the closing monitor updates were always effectively replayed on startup (either directly
9773                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
9774                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
9775                 0u64.write(writer)?;
9776
9777                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
9778                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
9779                 // likely to be identical.
9780                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9781                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9782
9783                 (pending_inbound_payments.len() as u64).write(writer)?;
9784                 for (hash, pending_payment) in pending_inbound_payments.iter() {
9785                         hash.write(writer)?;
9786                         pending_payment.write(writer)?;
9787                 }
9788
9789                 // For backwards compat, write the session privs and their total length.
9790                 let mut num_pending_outbounds_compat: u64 = 0;
9791                 for (_, outbound) in pending_outbound_payments.iter() {
9792                         if !outbound.is_fulfilled() && !outbound.abandoned() {
9793                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
9794                         }
9795                 }
9796                 num_pending_outbounds_compat.write(writer)?;
9797                 for (_, outbound) in pending_outbound_payments.iter() {
9798                         match outbound {
9799                                 PendingOutboundPayment::Legacy { session_privs } |
9800                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9801                                         for session_priv in session_privs.iter() {
9802                                                 session_priv.write(writer)?;
9803                                         }
9804                                 }
9805                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
9806                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
9807                                 PendingOutboundPayment::Fulfilled { .. } => {},
9808                                 PendingOutboundPayment::Abandoned { .. } => {},
9809                         }
9810                 }
9811
9812                 // Encode without retry info for 0.0.101 compatibility.
9813                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
9814                 for (id, outbound) in pending_outbound_payments.iter() {
9815                         match outbound {
9816                                 PendingOutboundPayment::Legacy { session_privs } |
9817                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9818                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
9819                                 },
9820                                 _ => {},
9821                         }
9822                 }
9823
9824                 let mut pending_intercepted_htlcs = None;
9825                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
9826                 if our_pending_intercepts.len() != 0 {
9827                         pending_intercepted_htlcs = Some(our_pending_intercepts);
9828                 }
9829
9830                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
9831                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
9832                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
9833                         // map. Thus, if there are no entries we skip writing a TLV for it.
9834                         pending_claiming_payments = None;
9835                 }
9836
9837                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
9838                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9839                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
9840                                 if !updates.is_empty() {
9841                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
9842                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
9843                                 }
9844                         }
9845                 }
9846
9847                 write_tlv_fields!(writer, {
9848                         (1, pending_outbound_payments_no_retry, required),
9849                         (2, pending_intercepted_htlcs, option),
9850                         (3, pending_outbound_payments, required),
9851                         (4, pending_claiming_payments, option),
9852                         (5, self.our_network_pubkey, required),
9853                         (6, monitor_update_blocked_actions_per_peer, option),
9854                         (7, self.fake_scid_rand_bytes, required),
9855                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
9856                         (9, htlc_purposes, required_vec),
9857                         (10, in_flight_monitor_updates, option),
9858                         (11, self.probing_cookie_secret, required),
9859                         (13, htlc_onion_fields, optional_vec),
9860                 });
9861
9862                 Ok(())
9863         }
9864 }
9865
9866 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
9867         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9868                 (self.len() as u64).write(w)?;
9869                 for (event, action) in self.iter() {
9870                         event.write(w)?;
9871                         action.write(w)?;
9872                         #[cfg(debug_assertions)] {
9873                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
9874                                 // be persisted and are regenerated on restart. However, if such an event has a
9875                                 // post-event-handling action we'll write nothing for the event and would have to
9876                                 // either forget the action or fail on deserialization (which we do below). Thus,
9877                                 // check that the event is sane here.
9878                                 let event_encoded = event.encode();
9879                                 let event_read: Option<Event> =
9880                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
9881                                 if action.is_some() { assert!(event_read.is_some()); }
9882                         }
9883                 }
9884                 Ok(())
9885         }
9886 }
9887 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
9888         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9889                 let len: u64 = Readable::read(reader)?;
9890                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
9891                 let mut events: Self = VecDeque::with_capacity(cmp::min(
9892                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
9893                         len) as usize);
9894                 for _ in 0..len {
9895                         let ev_opt = MaybeReadable::read(reader)?;
9896                         let action = Readable::read(reader)?;
9897                         if let Some(ev) = ev_opt {
9898                                 events.push_back((ev, action));
9899                         } else if action.is_some() {
9900                                 return Err(DecodeError::InvalidValue);
9901                         }
9902                 }
9903                 Ok(events)
9904         }
9905 }
9906
9907 impl_writeable_tlv_based_enum!(ChannelShutdownState,
9908         (0, NotShuttingDown) => {},
9909         (2, ShutdownInitiated) => {},
9910         (4, ResolvingHTLCs) => {},
9911         (6, NegotiatingClosingFee) => {},
9912         (8, ShutdownComplete) => {}, ;
9913 );
9914
9915 /// Arguments for the creation of a ChannelManager that are not deserialized.
9916 ///
9917 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
9918 /// is:
9919 /// 1) Deserialize all stored [`ChannelMonitor`]s.
9920 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
9921 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
9922 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
9923 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
9924 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
9925 ///    same way you would handle a [`chain::Filter`] call using
9926 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
9927 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
9928 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
9929 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
9930 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
9931 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
9932 ///    the next step.
9933 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
9934 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
9935 ///
9936 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
9937 /// call any other methods on the newly-deserialized [`ChannelManager`].
9938 ///
9939 /// Note that because some channels may be closed during deserialization, it is critical that you
9940 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
9941 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
9942 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
9943 /// not force-close the same channels but consider them live), you may end up revoking a state for
9944 /// which you've already broadcasted the transaction.
9945 ///
9946 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
9947 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9948 where
9949         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9950         T::Target: BroadcasterInterface,
9951         ES::Target: EntropySource,
9952         NS::Target: NodeSigner,
9953         SP::Target: SignerProvider,
9954         F::Target: FeeEstimator,
9955         R::Target: Router,
9956         L::Target: Logger,
9957 {
9958         /// A cryptographically secure source of entropy.
9959         pub entropy_source: ES,
9960
9961         /// A signer that is able to perform node-scoped cryptographic operations.
9962         pub node_signer: NS,
9963
9964         /// The keys provider which will give us relevant keys. Some keys will be loaded during
9965         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
9966         /// signing data.
9967         pub signer_provider: SP,
9968
9969         /// The fee_estimator for use in the ChannelManager in the future.
9970         ///
9971         /// No calls to the FeeEstimator will be made during deserialization.
9972         pub fee_estimator: F,
9973         /// The chain::Watch for use in the ChannelManager in the future.
9974         ///
9975         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
9976         /// you have deserialized ChannelMonitors separately and will add them to your
9977         /// chain::Watch after deserializing this ChannelManager.
9978         pub chain_monitor: M,
9979
9980         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
9981         /// used to broadcast the latest local commitment transactions of channels which must be
9982         /// force-closed during deserialization.
9983         pub tx_broadcaster: T,
9984         /// The router which will be used in the ChannelManager in the future for finding routes
9985         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
9986         ///
9987         /// No calls to the router will be made during deserialization.
9988         pub router: R,
9989         /// The Logger for use in the ChannelManager and which may be used to log information during
9990         /// deserialization.
9991         pub logger: L,
9992         /// Default settings used for new channels. Any existing channels will continue to use the
9993         /// runtime settings which were stored when the ChannelManager was serialized.
9994         pub default_config: UserConfig,
9995
9996         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
9997         /// value.context.get_funding_txo() should be the key).
9998         ///
9999         /// If a monitor is inconsistent with the channel state during deserialization the channel will
10000         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
10001         /// is true for missing channels as well. If there is a monitor missing for which we find
10002         /// channel data Err(DecodeError::InvalidValue) will be returned.
10003         ///
10004         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
10005         /// this struct.
10006         ///
10007         /// This is not exported to bindings users because we have no HashMap bindings
10008         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
10009 }
10010
10011 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10012                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
10013 where
10014         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
10015         T::Target: BroadcasterInterface,
10016         ES::Target: EntropySource,
10017         NS::Target: NodeSigner,
10018         SP::Target: SignerProvider,
10019         F::Target: FeeEstimator,
10020         R::Target: Router,
10021         L::Target: Logger,
10022 {
10023         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
10024         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
10025         /// populate a HashMap directly from C.
10026         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,
10027                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
10028                 Self {
10029                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
10030                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
10031                 }
10032         }
10033 }
10034
10035 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
10036 // SipmleArcChannelManager type:
10037 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10038         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
10039 where
10040         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
10041         T::Target: BroadcasterInterface,
10042         ES::Target: EntropySource,
10043         NS::Target: NodeSigner,
10044         SP::Target: SignerProvider,
10045         F::Target: FeeEstimator,
10046         R::Target: Router,
10047         L::Target: Logger,
10048 {
10049         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10050                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
10051                 Ok((blockhash, Arc::new(chan_manager)))
10052         }
10053 }
10054
10055 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10056         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
10057 where
10058         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
10059         T::Target: BroadcasterInterface,
10060         ES::Target: EntropySource,
10061         NS::Target: NodeSigner,
10062         SP::Target: SignerProvider,
10063         F::Target: FeeEstimator,
10064         R::Target: Router,
10065         L::Target: Logger,
10066 {
10067         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10068                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
10069
10070                 let chain_hash: ChainHash = Readable::read(reader)?;
10071                 let best_block_height: u32 = Readable::read(reader)?;
10072                 let best_block_hash: BlockHash = Readable::read(reader)?;
10073
10074                 let mut failed_htlcs = Vec::new();
10075
10076                 let channel_count: u64 = Readable::read(reader)?;
10077                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
10078                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10079                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10080                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10081                 let mut channel_closures = VecDeque::new();
10082                 let mut close_background_events = Vec::new();
10083                 for _ in 0..channel_count {
10084                         let mut channel: Channel<SP> = Channel::read(reader, (
10085                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
10086                         ))?;
10087                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10088                         funding_txo_set.insert(funding_txo.clone());
10089                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10090                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
10091                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
10092                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
10093                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10094                                         // But if the channel is behind of the monitor, close the channel:
10095                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
10096                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
10097                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10098                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
10099                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
10100                                         }
10101                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
10102                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
10103                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
10104                                         }
10105                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
10106                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
10107                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
10108                                         }
10109                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
10110                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
10111                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
10112                                         }
10113                                         let mut shutdown_result = channel.context.force_shutdown(true);
10114                                         if shutdown_result.unbroadcasted_batch_funding_txid.is_some() {
10115                                                 return Err(DecodeError::InvalidValue);
10116                                         }
10117                                         if let Some((counterparty_node_id, funding_txo, update)) = shutdown_result.monitor_update {
10118                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10119                                                         counterparty_node_id, funding_txo, update
10120                                                 });
10121                                         }
10122                                         failed_htlcs.append(&mut shutdown_result.dropped_outbound_htlcs);
10123                                         channel_closures.push_back((events::Event::ChannelClosed {
10124                                                 channel_id: channel.context.channel_id(),
10125                                                 user_channel_id: channel.context.get_user_id(),
10126                                                 reason: ClosureReason::OutdatedChannelManager,
10127                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10128                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10129                                         }, None));
10130                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
10131                                                 let mut found_htlc = false;
10132                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
10133                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
10134                                                 }
10135                                                 if !found_htlc {
10136                                                         // If we have some HTLCs in the channel which are not present in the newer
10137                                                         // ChannelMonitor, they have been removed and should be failed back to
10138                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
10139                                                         // were actually claimed we'd have generated and ensured the previous-hop
10140                                                         // claim update ChannelMonitor updates were persisted prior to persising
10141                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
10142                                                         // backwards leg of the HTLC will simply be rejected.
10143                                                         log_info!(args.logger,
10144                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
10145                                                                 &channel.context.channel_id(), &payment_hash);
10146                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10147                                                 }
10148                                         }
10149                                 } else {
10150                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
10151                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
10152                                                 monitor.get_latest_update_id());
10153                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
10154                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10155                                         }
10156                                         if channel.context.is_funding_broadcast() {
10157                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
10158                                         }
10159                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
10160                                                 hash_map::Entry::Occupied(mut entry) => {
10161                                                         let by_id_map = entry.get_mut();
10162                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10163                                                 },
10164                                                 hash_map::Entry::Vacant(entry) => {
10165                                                         let mut by_id_map = HashMap::new();
10166                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10167                                                         entry.insert(by_id_map);
10168                                                 }
10169                                         }
10170                                 }
10171                         } else if channel.is_awaiting_initial_mon_persist() {
10172                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
10173                                 // was in-progress, we never broadcasted the funding transaction and can still
10174                                 // safely discard the channel.
10175                                 let _ = channel.context.force_shutdown(false);
10176                                 channel_closures.push_back((events::Event::ChannelClosed {
10177                                         channel_id: channel.context.channel_id(),
10178                                         user_channel_id: channel.context.get_user_id(),
10179                                         reason: ClosureReason::DisconnectedPeer,
10180                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10181                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10182                                 }, None));
10183                         } else {
10184                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
10185                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10186                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10187                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
10188                                 log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10189                                 return Err(DecodeError::InvalidValue);
10190                         }
10191                 }
10192
10193                 for (funding_txo, _) in args.channel_monitors.iter() {
10194                         if !funding_txo_set.contains(funding_txo) {
10195                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
10196                                         &funding_txo.to_channel_id());
10197                                 let monitor_update = ChannelMonitorUpdate {
10198                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
10199                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
10200                                 };
10201                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
10202                         }
10203                 }
10204
10205                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
10206                 let forward_htlcs_count: u64 = Readable::read(reader)?;
10207                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
10208                 for _ in 0..forward_htlcs_count {
10209                         let short_channel_id = Readable::read(reader)?;
10210                         let pending_forwards_count: u64 = Readable::read(reader)?;
10211                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
10212                         for _ in 0..pending_forwards_count {
10213                                 pending_forwards.push(Readable::read(reader)?);
10214                         }
10215                         forward_htlcs.insert(short_channel_id, pending_forwards);
10216                 }
10217
10218                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
10219                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
10220                 for _ in 0..claimable_htlcs_count {
10221                         let payment_hash = Readable::read(reader)?;
10222                         let previous_hops_len: u64 = Readable::read(reader)?;
10223                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
10224                         for _ in 0..previous_hops_len {
10225                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
10226                         }
10227                         claimable_htlcs_list.push((payment_hash, previous_hops));
10228                 }
10229
10230                 let peer_state_from_chans = |channel_by_id| {
10231                         PeerState {
10232                                 channel_by_id,
10233                                 inbound_channel_request_by_id: HashMap::new(),
10234                                 latest_features: InitFeatures::empty(),
10235                                 pending_msg_events: Vec::new(),
10236                                 in_flight_monitor_updates: BTreeMap::new(),
10237                                 monitor_update_blocked_actions: BTreeMap::new(),
10238                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
10239                                 is_connected: false,
10240                         }
10241                 };
10242
10243                 let peer_count: u64 = Readable::read(reader)?;
10244                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
10245                 for _ in 0..peer_count {
10246                         let peer_pubkey = Readable::read(reader)?;
10247                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
10248                         let mut peer_state = peer_state_from_chans(peer_chans);
10249                         peer_state.latest_features = Readable::read(reader)?;
10250                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
10251                 }
10252
10253                 let event_count: u64 = Readable::read(reader)?;
10254                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
10255                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
10256                 for _ in 0..event_count {
10257                         match MaybeReadable::read(reader)? {
10258                                 Some(event) => pending_events_read.push_back((event, None)),
10259                                 None => continue,
10260                         }
10261                 }
10262
10263                 let background_event_count: u64 = Readable::read(reader)?;
10264                 for _ in 0..background_event_count {
10265                         match <u8 as Readable>::read(reader)? {
10266                                 0 => {
10267                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
10268                                         // however we really don't (and never did) need them - we regenerate all
10269                                         // on-startup monitor updates.
10270                                         let _: OutPoint = Readable::read(reader)?;
10271                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
10272                                 }
10273                                 _ => return Err(DecodeError::InvalidValue),
10274                         }
10275                 }
10276
10277                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
10278                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
10279
10280                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
10281                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
10282                 for _ in 0..pending_inbound_payment_count {
10283                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
10284                                 return Err(DecodeError::InvalidValue);
10285                         }
10286                 }
10287
10288                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
10289                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
10290                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
10291                 for _ in 0..pending_outbound_payments_count_compat {
10292                         let session_priv = Readable::read(reader)?;
10293                         let payment = PendingOutboundPayment::Legacy {
10294                                 session_privs: [session_priv].iter().cloned().collect()
10295                         };
10296                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
10297                                 return Err(DecodeError::InvalidValue)
10298                         };
10299                 }
10300
10301                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
10302                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
10303                 let mut pending_outbound_payments = None;
10304                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
10305                 let mut received_network_pubkey: Option<PublicKey> = None;
10306                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
10307                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
10308                 let mut claimable_htlc_purposes = None;
10309                 let mut claimable_htlc_onion_fields = None;
10310                 let mut pending_claiming_payments = Some(HashMap::new());
10311                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
10312                 let mut events_override = None;
10313                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
10314                 read_tlv_fields!(reader, {
10315                         (1, pending_outbound_payments_no_retry, option),
10316                         (2, pending_intercepted_htlcs, option),
10317                         (3, pending_outbound_payments, option),
10318                         (4, pending_claiming_payments, option),
10319                         (5, received_network_pubkey, option),
10320                         (6, monitor_update_blocked_actions_per_peer, option),
10321                         (7, fake_scid_rand_bytes, option),
10322                         (8, events_override, option),
10323                         (9, claimable_htlc_purposes, optional_vec),
10324                         (10, in_flight_monitor_updates, option),
10325                         (11, probing_cookie_secret, option),
10326                         (13, claimable_htlc_onion_fields, optional_vec),
10327                 });
10328                 if fake_scid_rand_bytes.is_none() {
10329                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
10330                 }
10331
10332                 if probing_cookie_secret.is_none() {
10333                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
10334                 }
10335
10336                 if let Some(events) = events_override {
10337                         pending_events_read = events;
10338                 }
10339
10340                 if !channel_closures.is_empty() {
10341                         pending_events_read.append(&mut channel_closures);
10342                 }
10343
10344                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
10345                         pending_outbound_payments = Some(pending_outbound_payments_compat);
10346                 } else if pending_outbound_payments.is_none() {
10347                         let mut outbounds = HashMap::new();
10348                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
10349                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
10350                         }
10351                         pending_outbound_payments = Some(outbounds);
10352                 }
10353                 let pending_outbounds = OutboundPayments {
10354                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
10355                         retry_lock: Mutex::new(())
10356                 };
10357
10358                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
10359                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
10360                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
10361                 // replayed, and for each monitor update we have to replay we have to ensure there's a
10362                 // `ChannelMonitor` for it.
10363                 //
10364                 // In order to do so we first walk all of our live channels (so that we can check their
10365                 // state immediately after doing the update replays, when we have the `update_id`s
10366                 // available) and then walk any remaining in-flight updates.
10367                 //
10368                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10369                 let mut pending_background_events = Vec::new();
10370                 macro_rules! handle_in_flight_updates {
10371                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10372                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
10373                         ) => { {
10374                                 let mut max_in_flight_update_id = 0;
10375                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10376                                 for update in $chan_in_flight_upds.iter() {
10377                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10378                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
10379                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10380                                         pending_background_events.push(
10381                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10382                                                         counterparty_node_id: $counterparty_node_id,
10383                                                         funding_txo: $funding_txo,
10384                                                         update: update.clone(),
10385                                                 });
10386                                 }
10387                                 if $chan_in_flight_upds.is_empty() {
10388                                         // We had some updates to apply, but it turns out they had completed before we
10389                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10390                                         // the completion actions for any monitor updates, but otherwise are done.
10391                                         pending_background_events.push(
10392                                                 BackgroundEvent::MonitorUpdatesComplete {
10393                                                         counterparty_node_id: $counterparty_node_id,
10394                                                         channel_id: $funding_txo.to_channel_id(),
10395                                                 });
10396                                 }
10397                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10398                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
10399                                         return Err(DecodeError::InvalidValue);
10400                                 }
10401                                 max_in_flight_update_id
10402                         } }
10403                 }
10404
10405                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10406                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10407                         let peer_state = &mut *peer_state_lock;
10408                         for phase in peer_state.channel_by_id.values() {
10409                                 if let ChannelPhase::Funded(chan) = phase {
10410                                         // Channels that were persisted have to be funded, otherwise they should have been
10411                                         // discarded.
10412                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10413                                         let monitor = args.channel_monitors.get(&funding_txo)
10414                                                 .expect("We already checked for monitor presence when loading channels");
10415                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10416                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10417                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10418                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10419                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10420                                                                         funding_txo, monitor, peer_state, ""));
10421                                                 }
10422                                         }
10423                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10424                                                 // If the channel is ahead of the monitor, return InvalidValue:
10425                                                 log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10426                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10427                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10428                                                 log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10429                                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10430                                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10431                                                 log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10432                                                 log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10433                                                 return Err(DecodeError::InvalidValue);
10434                                         }
10435                                 } else {
10436                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10437                                         // created in this `channel_by_id` map.
10438                                         debug_assert!(false);
10439                                         return Err(DecodeError::InvalidValue);
10440                                 }
10441                         }
10442                 }
10443
10444                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10445                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10446                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10447                                         // Now that we've removed all the in-flight monitor updates for channels that are
10448                                         // still open, we need to replay any monitor updates that are for closed channels,
10449                                         // creating the neccessary peer_state entries as we go.
10450                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10451                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
10452                                         });
10453                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10454                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10455                                                 funding_txo, monitor, peer_state, "closed ");
10456                                 } else {
10457                                         log_error!(args.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!");
10458                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
10459                                                 &funding_txo.to_channel_id());
10460                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10461                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10462                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10463                                         log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10464                                         return Err(DecodeError::InvalidValue);
10465                                 }
10466                         }
10467                 }
10468
10469                 // Note that we have to do the above replays before we push new monitor updates.
10470                 pending_background_events.append(&mut close_background_events);
10471
10472                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10473                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10474                 // have a fully-constructed `ChannelManager` at the end.
10475                 let mut pending_claims_to_replay = Vec::new();
10476
10477                 {
10478                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10479                         // ChannelMonitor data for any channels for which we do not have authorative state
10480                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10481                         // corresponding `Channel` at all).
10482                         // This avoids several edge-cases where we would otherwise "forget" about pending
10483                         // payments which are still in-flight via their on-chain state.
10484                         // We only rebuild the pending payments map if we were most recently serialized by
10485                         // 0.0.102+
10486                         for (_, monitor) in args.channel_monitors.iter() {
10487                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
10488                                 if counterparty_opt.is_none() {
10489                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10490                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10491                                                         if path.hops.is_empty() {
10492                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
10493                                                                 return Err(DecodeError::InvalidValue);
10494                                                         }
10495
10496                                                         let path_amt = path.final_value_msat();
10497                                                         let mut session_priv_bytes = [0; 32];
10498                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10499                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10500                                                                 hash_map::Entry::Occupied(mut entry) => {
10501                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10502                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10503                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), &htlc.payment_hash);
10504                                                                 },
10505                                                                 hash_map::Entry::Vacant(entry) => {
10506                                                                         let path_fee = path.fee_msat();
10507                                                                         entry.insert(PendingOutboundPayment::Retryable {
10508                                                                                 retry_strategy: None,
10509                                                                                 attempts: PaymentAttempts::new(),
10510                                                                                 payment_params: None,
10511                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
10512                                                                                 payment_hash: htlc.payment_hash,
10513                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10514                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10515                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10516                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10517                                                                                 pending_amt_msat: path_amt,
10518                                                                                 pending_fee_msat: Some(path_fee),
10519                                                                                 total_msat: path_amt,
10520                                                                                 starting_block_height: best_block_height,
10521                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10522                                                                         });
10523                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10524                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10525                                                                 }
10526                                                         }
10527                                                 }
10528                                         }
10529                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10530                                                 match htlc_source {
10531                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10532                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10533                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10534                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10535                                                                 };
10536                                                                 // The ChannelMonitor is now responsible for this HTLC's
10537                                                                 // failure/success and will let us know what its outcome is. If we
10538                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10539                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10540                                                                 // the monitor was when forwarding the payment.
10541                                                                 forward_htlcs.retain(|_, forwards| {
10542                                                                         forwards.retain(|forward| {
10543                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10544                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10545                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10546                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10547                                                                                                 false
10548                                                                                         } else { true }
10549                                                                                 } else { true }
10550                                                                         });
10551                                                                         !forwards.is_empty()
10552                                                                 });
10553                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10554                                                                         if pending_forward_matches_htlc(&htlc_info) {
10555                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10556                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10557                                                                                 pending_events_read.retain(|(event, _)| {
10558                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10559                                                                                                 intercepted_id != ev_id
10560                                                                                         } else { true }
10561                                                                                 });
10562                                                                                 false
10563                                                                         } else { true }
10564                                                                 });
10565                                                         },
10566                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10567                                                                 if let Some(preimage) = preimage_opt {
10568                                                                         let pending_events = Mutex::new(pending_events_read);
10569                                                                         // Note that we set `from_onchain` to "false" here,
10570                                                                         // deliberately keeping the pending payment around forever.
10571                                                                         // Given it should only occur when we have a channel we're
10572                                                                         // force-closing for being stale that's okay.
10573                                                                         // The alternative would be to wipe the state when claiming,
10574                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10575                                                                         // it and the `PaymentSent` on every restart until the
10576                                                                         // `ChannelMonitor` is removed.
10577                                                                         let compl_action =
10578                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10579                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10580                                                                                         counterparty_node_id: path.hops[0].pubkey,
10581                                                                                 };
10582                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10583                                                                                 path, false, compl_action, &pending_events, &args.logger);
10584                                                                         pending_events_read = pending_events.into_inner().unwrap();
10585                                                                 }
10586                                                         },
10587                                                 }
10588                                         }
10589                                 }
10590
10591                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10592                                 // preimages from it which may be needed in upstream channels for forwarded
10593                                 // payments.
10594                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10595                                         .into_iter()
10596                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10597                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10598                                                         if let Some(payment_preimage) = preimage_opt {
10599                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10600                                                                         // Check if `counterparty_opt.is_none()` to see if the
10601                                                                         // downstream chan is closed (because we don't have a
10602                                                                         // channel_id -> peer map entry).
10603                                                                         counterparty_opt.is_none(),
10604                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10605                                                                         monitor.get_funding_txo().0))
10606                                                         } else { None }
10607                                                 } else {
10608                                                         // If it was an outbound payment, we've handled it above - if a preimage
10609                                                         // came in and we persisted the `ChannelManager` we either handled it and
10610                                                         // are good to go or the channel force-closed - we don't have to handle the
10611                                                         // channel still live case here.
10612                                                         None
10613                                                 }
10614                                         });
10615                                 for tuple in outbound_claimed_htlcs_iter {
10616                                         pending_claims_to_replay.push(tuple);
10617                                 }
10618                         }
10619                 }
10620
10621                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10622                         // If we have pending HTLCs to forward, assume we either dropped a
10623                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10624                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10625                         // constant as enough time has likely passed that we should simply handle the forwards
10626                         // now, or at least after the user gets a chance to reconnect to our peers.
10627                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10628                                 time_forwardable: Duration::from_secs(2),
10629                         }, None));
10630                 }
10631
10632                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10633                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10634
10635                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10636                 if let Some(purposes) = claimable_htlc_purposes {
10637                         if purposes.len() != claimable_htlcs_list.len() {
10638                                 return Err(DecodeError::InvalidValue);
10639                         }
10640                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10641                                 if onion_fields.len() != claimable_htlcs_list.len() {
10642                                         return Err(DecodeError::InvalidValue);
10643                                 }
10644                                 for (purpose, (onion, (payment_hash, htlcs))) in
10645                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10646                                 {
10647                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10648                                                 purpose, htlcs, onion_fields: onion,
10649                                         });
10650                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10651                                 }
10652                         } else {
10653                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10654                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10655                                                 purpose, htlcs, onion_fields: None,
10656                                         });
10657                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10658                                 }
10659                         }
10660                 } else {
10661                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10662                         // include a `_legacy_hop_data` in the `OnionPayload`.
10663                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10664                                 if htlcs.is_empty() {
10665                                         return Err(DecodeError::InvalidValue);
10666                                 }
10667                                 let purpose = match &htlcs[0].onion_payload {
10668                                         OnionPayload::Invoice { _legacy_hop_data } => {
10669                                                 if let Some(hop_data) = _legacy_hop_data {
10670                                                         events::PaymentPurpose::InvoicePayment {
10671                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10672                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10673                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10674                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10675                                                                                 Err(()) => {
10676                                                                                         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);
10677                                                                                         return Err(DecodeError::InvalidValue);
10678                                                                                 }
10679                                                                         }
10680                                                                 },
10681                                                                 payment_secret: hop_data.payment_secret,
10682                                                         }
10683                                                 } else { return Err(DecodeError::InvalidValue); }
10684                                         },
10685                                         OnionPayload::Spontaneous(payment_preimage) =>
10686                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10687                                 };
10688                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10689                                         purpose, htlcs, onion_fields: None,
10690                                 });
10691                         }
10692                 }
10693
10694                 let mut secp_ctx = Secp256k1::new();
10695                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10696
10697                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10698                         Ok(key) => key,
10699                         Err(()) => return Err(DecodeError::InvalidValue)
10700                 };
10701                 if let Some(network_pubkey) = received_network_pubkey {
10702                         if network_pubkey != our_network_pubkey {
10703                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10704                                 return Err(DecodeError::InvalidValue);
10705                         }
10706                 }
10707
10708                 let mut outbound_scid_aliases = HashSet::new();
10709                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10710                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10711                         let peer_state = &mut *peer_state_lock;
10712                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10713                                 if let ChannelPhase::Funded(chan) = phase {
10714                                         if chan.context.outbound_scid_alias() == 0 {
10715                                                 let mut outbound_scid_alias;
10716                                                 loop {
10717                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10718                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10719                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10720                                                 }
10721                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10722                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10723                                                 // Note that in rare cases its possible to hit this while reading an older
10724                                                 // channel if we just happened to pick a colliding outbound alias above.
10725                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10726                                                 return Err(DecodeError::InvalidValue);
10727                                         }
10728                                         if chan.context.is_usable() {
10729                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10730                                                         // Note that in rare cases its possible to hit this while reading an older
10731                                                         // channel if we just happened to pick a colliding outbound alias above.
10732                                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10733                                                         return Err(DecodeError::InvalidValue);
10734                                                 }
10735                                         }
10736                                 } else {
10737                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10738                                         // created in this `channel_by_id` map.
10739                                         debug_assert!(false);
10740                                         return Err(DecodeError::InvalidValue);
10741                                 }
10742                         }
10743                 }
10744
10745                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10746
10747                 for (_, monitor) in args.channel_monitors.iter() {
10748                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10749                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10750                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10751                                         let mut claimable_amt_msat = 0;
10752                                         let mut receiver_node_id = Some(our_network_pubkey);
10753                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
10754                                         if phantom_shared_secret.is_some() {
10755                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
10756                                                         .expect("Failed to get node_id for phantom node recipient");
10757                                                 receiver_node_id = Some(phantom_pubkey)
10758                                         }
10759                                         for claimable_htlc in &payment.htlcs {
10760                                                 claimable_amt_msat += claimable_htlc.value;
10761
10762                                                 // Add a holding-cell claim of the payment to the Channel, which should be
10763                                                 // applied ~immediately on peer reconnection. Because it won't generate a
10764                                                 // new commitment transaction we can just provide the payment preimage to
10765                                                 // the corresponding ChannelMonitor and nothing else.
10766                                                 //
10767                                                 // We do so directly instead of via the normal ChannelMonitor update
10768                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
10769                                                 // we're not allowed to call it directly yet. Further, we do the update
10770                                                 // without incrementing the ChannelMonitor update ID as there isn't any
10771                                                 // reason to.
10772                                                 // If we were to generate a new ChannelMonitor update ID here and then
10773                                                 // crash before the user finishes block connect we'd end up force-closing
10774                                                 // this channel as well. On the flip side, there's no harm in restarting
10775                                                 // without the new monitor persisted - we'll end up right back here on
10776                                                 // restart.
10777                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
10778                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
10779                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
10780                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10781                                                         let peer_state = &mut *peer_state_lock;
10782                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
10783                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
10784                                                         }
10785                                                 }
10786                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
10787                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
10788                                                 }
10789                                         }
10790                                         pending_events_read.push_back((events::Event::PaymentClaimed {
10791                                                 receiver_node_id,
10792                                                 payment_hash,
10793                                                 purpose: payment.purpose,
10794                                                 amount_msat: claimable_amt_msat,
10795                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
10796                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
10797                                         }, None));
10798                                 }
10799                         }
10800                 }
10801
10802                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
10803                         if let Some(peer_state) = per_peer_state.get(&node_id) {
10804                                 for (_, actions) in monitor_update_blocked_actions.iter() {
10805                                         for action in actions.iter() {
10806                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
10807                                                         downstream_counterparty_and_funding_outpoint:
10808                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
10809                                                 } = action {
10810                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
10811                                                                 log_trace!(args.logger,
10812                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
10813                                                                         blocked_channel_outpoint.to_channel_id());
10814                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
10815                                                                         .entry(blocked_channel_outpoint.to_channel_id())
10816                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
10817                                                         } else {
10818                                                                 // If the channel we were blocking has closed, we don't need to
10819                                                                 // worry about it - the blocked monitor update should never have
10820                                                                 // been released from the `Channel` object so it can't have
10821                                                                 // completed, and if the channel closed there's no reason to bother
10822                                                                 // anymore.
10823                                                         }
10824                                                 }
10825                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
10826                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
10827                                                 }
10828                                         }
10829                                 }
10830                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
10831                         } else {
10832                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
10833                                 return Err(DecodeError::InvalidValue);
10834                         }
10835                 }
10836
10837                 let channel_manager = ChannelManager {
10838                         chain_hash,
10839                         fee_estimator: bounded_fee_estimator,
10840                         chain_monitor: args.chain_monitor,
10841                         tx_broadcaster: args.tx_broadcaster,
10842                         router: args.router,
10843
10844                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
10845
10846                         inbound_payment_key: expanded_inbound_key,
10847                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
10848                         pending_outbound_payments: pending_outbounds,
10849                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
10850
10851                         forward_htlcs: Mutex::new(forward_htlcs),
10852                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
10853                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
10854                         id_to_peer: Mutex::new(id_to_peer),
10855                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
10856                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
10857
10858                         probing_cookie_secret: probing_cookie_secret.unwrap(),
10859
10860                         our_network_pubkey,
10861                         secp_ctx,
10862
10863                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
10864
10865                         per_peer_state: FairRwLock::new(per_peer_state),
10866
10867                         pending_events: Mutex::new(pending_events_read),
10868                         pending_events_processor: AtomicBool::new(false),
10869                         pending_background_events: Mutex::new(pending_background_events),
10870                         total_consistency_lock: RwLock::new(()),
10871                         background_events_processed_since_startup: AtomicBool::new(false),
10872
10873                         event_persist_notifier: Notifier::new(),
10874                         needs_persist_flag: AtomicBool::new(false),
10875
10876                         funding_batch_states: Mutex::new(BTreeMap::new()),
10877
10878                         pending_offers_messages: Mutex::new(Vec::new()),
10879
10880                         entropy_source: args.entropy_source,
10881                         node_signer: args.node_signer,
10882                         signer_provider: args.signer_provider,
10883
10884                         logger: args.logger,
10885                         default_configuration: args.default_config,
10886                 };
10887
10888                 for htlc_source in failed_htlcs.drain(..) {
10889                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
10890                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
10891                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
10892                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
10893                 }
10894
10895                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
10896                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
10897                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
10898                         // channel is closed we just assume that it probably came from an on-chain claim.
10899                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
10900                                 downstream_closed, true, downstream_node_id, downstream_funding);
10901                 }
10902
10903                 //TODO: Broadcast channel update for closed channels, but only after we've made a
10904                 //connection or two.
10905
10906                 Ok((best_block_hash.clone(), channel_manager))
10907         }
10908 }
10909
10910 #[cfg(test)]
10911 mod tests {
10912         use bitcoin::hashes::Hash;
10913         use bitcoin::hashes::sha256::Hash as Sha256;
10914         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10915         use core::sync::atomic::Ordering;
10916         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
10917         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
10918         use crate::ln::ChannelId;
10919         use crate::ln::channelmanager::{create_recv_pending_htlc_info, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
10920         use crate::ln::features::{ChannelFeatures, NodeFeatures};
10921         use crate::ln::functional_test_utils::*;
10922         use crate::ln::msgs::{self, ErrorAction};
10923         use crate::ln::msgs::ChannelMessageHandler;
10924         use crate::routing::router::{Path, PaymentParameters, RouteHop, RouteParameters, find_route};
10925         use crate::util::errors::APIError;
10926         use crate::util::test_utils;
10927         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
10928         use crate::sign::EntropySource;
10929
10930         #[test]
10931         fn test_notify_limits() {
10932                 // Check that a few cases which don't require the persistence of a new ChannelManager,
10933                 // indeed, do not cause the persistence of a new ChannelManager.
10934                 let chanmon_cfgs = create_chanmon_cfgs(3);
10935                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10936                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10937                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10938
10939                 // All nodes start with a persistable update pending as `create_network` connects each node
10940                 // with all other nodes to make most tests simpler.
10941                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10942                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10943                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10944
10945                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10946
10947                 // We check that the channel info nodes have doesn't change too early, even though we try
10948                 // to connect messages with new values
10949                 chan.0.contents.fee_base_msat *= 2;
10950                 chan.1.contents.fee_base_msat *= 2;
10951                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
10952                         &nodes[1].node.get_our_node_id()).pop().unwrap();
10953                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
10954                         &nodes[0].node.get_our_node_id()).pop().unwrap();
10955
10956                 // The first two nodes (which opened a channel) should now require fresh persistence
10957                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10958                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10959                 // ... but the last node should not.
10960                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10961                 // After persisting the first two nodes they should no longer need fresh persistence.
10962                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10963                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10964
10965                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
10966                 // about the channel.
10967                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
10968                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
10969                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10970
10971                 // The nodes which are a party to the channel should also ignore messages from unrelated
10972                 // parties.
10973                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10974                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10975                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10976                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10977                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10978                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10979
10980                 // At this point the channel info given by peers should still be the same.
10981                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10982                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10983
10984                 // An earlier version of handle_channel_update didn't check the directionality of the
10985                 // update message and would always update the local fee info, even if our peer was
10986                 // (spuriously) forwarding us our own channel_update.
10987                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
10988                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
10989                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
10990
10991                 // First deliver each peers' own message, checking that the node doesn't need to be
10992                 // persisted and that its channel info remains the same.
10993                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
10994                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
10995                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10996                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10997                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10998                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10999
11000                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
11001                 // the channel info has updated.
11002                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
11003                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
11004                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11005                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11006                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
11007                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
11008         }
11009
11010         #[test]
11011         fn test_keysend_dup_hash_partial_mpp() {
11012                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
11013                 // expected.
11014                 let chanmon_cfgs = create_chanmon_cfgs(2);
11015                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11016                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11017                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11018                 create_announced_chan_between_nodes(&nodes, 0, 1);
11019
11020                 // First, send a partial MPP payment.
11021                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
11022                 let mut mpp_route = route.clone();
11023                 mpp_route.paths.push(mpp_route.paths[0].clone());
11024
11025                 let payment_id = PaymentId([42; 32]);
11026                 // Use the utility function send_payment_along_path to send the payment with MPP data which
11027                 // indicates there are more HTLCs coming.
11028                 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.
11029                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
11030                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
11031                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
11032                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
11033                 check_added_monitors!(nodes[0], 1);
11034                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11035                 assert_eq!(events.len(), 1);
11036                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
11037
11038                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
11039                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11040                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11041                 check_added_monitors!(nodes[0], 1);
11042                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11043                 assert_eq!(events.len(), 1);
11044                 let ev = events.drain(..).next().unwrap();
11045                 let payment_event = SendEvent::from_event(ev);
11046                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11047                 check_added_monitors!(nodes[1], 0);
11048                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11049                 expect_pending_htlcs_forwardable!(nodes[1]);
11050                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
11051                 check_added_monitors!(nodes[1], 1);
11052                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11053                 assert!(updates.update_add_htlcs.is_empty());
11054                 assert!(updates.update_fulfill_htlcs.is_empty());
11055                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11056                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11057                 assert!(updates.update_fee.is_none());
11058                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11059                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11060                 expect_payment_failed!(nodes[0], our_payment_hash, true);
11061
11062                 // Send the second half of the original MPP payment.
11063                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
11064                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
11065                 check_added_monitors!(nodes[0], 1);
11066                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11067                 assert_eq!(events.len(), 1);
11068                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
11069
11070                 // Claim the full MPP payment. Note that we can't use a test utility like
11071                 // claim_funds_along_route because the ordering of the messages causes the second half of the
11072                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
11073                 // lightning messages manually.
11074                 nodes[1].node.claim_funds(payment_preimage);
11075                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
11076                 check_added_monitors!(nodes[1], 2);
11077
11078                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11079                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
11080                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
11081                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
11082                 check_added_monitors!(nodes[0], 1);
11083                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11084                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
11085                 check_added_monitors!(nodes[1], 1);
11086                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11087                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
11088                 check_added_monitors!(nodes[1], 1);
11089                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11090                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
11091                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
11092                 check_added_monitors!(nodes[0], 1);
11093                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
11094                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
11095                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11096                 check_added_monitors!(nodes[0], 1);
11097                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
11098                 check_added_monitors!(nodes[1], 1);
11099                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
11100                 check_added_monitors!(nodes[1], 1);
11101                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11102                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
11103                 check_added_monitors!(nodes[0], 1);
11104
11105                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
11106                 // path's success and a PaymentPathSuccessful event for each path's success.
11107                 let events = nodes[0].node.get_and_clear_pending_events();
11108                 assert_eq!(events.len(), 2);
11109                 match events[0] {
11110                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11111                                 assert_eq!(payment_id, *actual_payment_id);
11112                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11113                                 assert_eq!(route.paths[0], *path);
11114                         },
11115                         _ => panic!("Unexpected event"),
11116                 }
11117                 match events[1] {
11118                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11119                                 assert_eq!(payment_id, *actual_payment_id);
11120                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11121                                 assert_eq!(route.paths[0], *path);
11122                         },
11123                         _ => panic!("Unexpected event"),
11124                 }
11125         }
11126
11127         #[test]
11128         fn test_keysend_dup_payment_hash() {
11129                 do_test_keysend_dup_payment_hash(false);
11130                 do_test_keysend_dup_payment_hash(true);
11131         }
11132
11133         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
11134                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
11135                 //      outbound regular payment fails as expected.
11136                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
11137                 //      fails as expected.
11138                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
11139                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
11140                 //      reject MPP keysend payments, since in this case where the payment has no payment
11141                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
11142                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
11143                 //      payment secrets and reject otherwise.
11144                 let chanmon_cfgs = create_chanmon_cfgs(2);
11145                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11146                 let mut mpp_keysend_cfg = test_default_channel_config();
11147                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
11148                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
11149                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11150                 create_announced_chan_between_nodes(&nodes, 0, 1);
11151                 let scorer = test_utils::TestScorer::new();
11152                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11153
11154                 // To start (1), send a regular payment but don't claim it.
11155                 let expected_route = [&nodes[1]];
11156                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
11157
11158                 // Next, attempt a keysend payment and make sure it fails.
11159                 let route_params = RouteParameters::from_payment_params_and_value(
11160                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
11161                         TEST_FINAL_CLTV, false), 100_000);
11162                 let route = find_route(
11163                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11164                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11165                 ).unwrap();
11166                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11167                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11168                 check_added_monitors!(nodes[0], 1);
11169                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11170                 assert_eq!(events.len(), 1);
11171                 let ev = events.drain(..).next().unwrap();
11172                 let payment_event = SendEvent::from_event(ev);
11173                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11174                 check_added_monitors!(nodes[1], 0);
11175                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11176                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
11177                 // fails), the second will process the resulting failure and fail the HTLC backward
11178                 expect_pending_htlcs_forwardable!(nodes[1]);
11179                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11180                 check_added_monitors!(nodes[1], 1);
11181                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11182                 assert!(updates.update_add_htlcs.is_empty());
11183                 assert!(updates.update_fulfill_htlcs.is_empty());
11184                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11185                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11186                 assert!(updates.update_fee.is_none());
11187                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11188                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11189                 expect_payment_failed!(nodes[0], payment_hash, true);
11190
11191                 // Finally, claim the original payment.
11192                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11193
11194                 // To start (2), send a keysend payment but don't claim it.
11195                 let payment_preimage = PaymentPreimage([42; 32]);
11196                 let route = find_route(
11197                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11198                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11199                 ).unwrap();
11200                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11201                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11202                 check_added_monitors!(nodes[0], 1);
11203                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11204                 assert_eq!(events.len(), 1);
11205                 let event = events.pop().unwrap();
11206                 let path = vec![&nodes[1]];
11207                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11208
11209                 // Next, attempt a regular payment and make sure it fails.
11210                 let payment_secret = PaymentSecret([43; 32]);
11211                 nodes[0].node.send_payment_with_route(&route, payment_hash,
11212                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
11213                 check_added_monitors!(nodes[0], 1);
11214                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11215                 assert_eq!(events.len(), 1);
11216                 let ev = events.drain(..).next().unwrap();
11217                 let payment_event = SendEvent::from_event(ev);
11218                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11219                 check_added_monitors!(nodes[1], 0);
11220                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11221                 expect_pending_htlcs_forwardable!(nodes[1]);
11222                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11223                 check_added_monitors!(nodes[1], 1);
11224                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11225                 assert!(updates.update_add_htlcs.is_empty());
11226                 assert!(updates.update_fulfill_htlcs.is_empty());
11227                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11228                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11229                 assert!(updates.update_fee.is_none());
11230                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11231                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11232                 expect_payment_failed!(nodes[0], payment_hash, true);
11233
11234                 // Finally, succeed the keysend payment.
11235                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11236
11237                 // To start (3), send a keysend payment but don't claim it.
11238                 let payment_id_1 = PaymentId([44; 32]);
11239                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11240                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
11241                 check_added_monitors!(nodes[0], 1);
11242                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11243                 assert_eq!(events.len(), 1);
11244                 let event = events.pop().unwrap();
11245                 let path = vec![&nodes[1]];
11246                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11247
11248                 // Next, attempt a keysend payment and make sure it fails.
11249                 let route_params = RouteParameters::from_payment_params_and_value(
11250                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
11251                         100_000
11252                 );
11253                 let route = find_route(
11254                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11255                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11256                 ).unwrap();
11257                 let payment_id_2 = PaymentId([45; 32]);
11258                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11259                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
11260                 check_added_monitors!(nodes[0], 1);
11261                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11262                 assert_eq!(events.len(), 1);
11263                 let ev = events.drain(..).next().unwrap();
11264                 let payment_event = SendEvent::from_event(ev);
11265                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11266                 check_added_monitors!(nodes[1], 0);
11267                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11268                 expect_pending_htlcs_forwardable!(nodes[1]);
11269                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11270                 check_added_monitors!(nodes[1], 1);
11271                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11272                 assert!(updates.update_add_htlcs.is_empty());
11273                 assert!(updates.update_fulfill_htlcs.is_empty());
11274                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11275                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11276                 assert!(updates.update_fee.is_none());
11277                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11278                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11279                 expect_payment_failed!(nodes[0], payment_hash, true);
11280
11281                 // Finally, claim the original payment.
11282                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11283         }
11284
11285         #[test]
11286         fn test_keysend_hash_mismatch() {
11287                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
11288                 // preimage doesn't match the msg's payment hash.
11289                 let chanmon_cfgs = create_chanmon_cfgs(2);
11290                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11291                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11292                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11293
11294                 let payer_pubkey = nodes[0].node.get_our_node_id();
11295                 let payee_pubkey = nodes[1].node.get_our_node_id();
11296
11297                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11298                 let route_params = RouteParameters::from_payment_params_and_value(
11299                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11300                 let network_graph = nodes[0].network_graph.clone();
11301                 let first_hops = nodes[0].node.list_usable_channels();
11302                 let scorer = test_utils::TestScorer::new();
11303                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11304                 let route = find_route(
11305                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11306                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11307                 ).unwrap();
11308
11309                 let test_preimage = PaymentPreimage([42; 32]);
11310                 let mismatch_payment_hash = PaymentHash([43; 32]);
11311                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
11312                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
11313                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
11314                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
11315                 check_added_monitors!(nodes[0], 1);
11316
11317                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11318                 assert_eq!(updates.update_add_htlcs.len(), 1);
11319                 assert!(updates.update_fulfill_htlcs.is_empty());
11320                 assert!(updates.update_fail_htlcs.is_empty());
11321                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11322                 assert!(updates.update_fee.is_none());
11323                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11324
11325                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
11326         }
11327
11328         #[test]
11329         fn test_keysend_msg_with_secret_err() {
11330                 // Test that we error as expected if we receive a keysend payment that includes a payment
11331                 // secret when we don't support MPP keysend.
11332                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
11333                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
11334                 let chanmon_cfgs = create_chanmon_cfgs(2);
11335                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11336                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
11337                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11338
11339                 let payer_pubkey = nodes[0].node.get_our_node_id();
11340                 let payee_pubkey = nodes[1].node.get_our_node_id();
11341
11342                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11343                 let route_params = RouteParameters::from_payment_params_and_value(
11344                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11345                 let network_graph = nodes[0].network_graph.clone();
11346                 let first_hops = nodes[0].node.list_usable_channels();
11347                 let scorer = test_utils::TestScorer::new();
11348                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11349                 let route = find_route(
11350                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11351                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11352                 ).unwrap();
11353
11354                 let test_preimage = PaymentPreimage([42; 32]);
11355                 let test_secret = PaymentSecret([43; 32]);
11356                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
11357                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
11358                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
11359                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
11360                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
11361                         PaymentId(payment_hash.0), None, session_privs).unwrap();
11362                 check_added_monitors!(nodes[0], 1);
11363
11364                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11365                 assert_eq!(updates.update_add_htlcs.len(), 1);
11366                 assert!(updates.update_fulfill_htlcs.is_empty());
11367                 assert!(updates.update_fail_htlcs.is_empty());
11368                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11369                 assert!(updates.update_fee.is_none());
11370                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11371
11372                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11373         }
11374
11375         #[test]
11376         fn test_multi_hop_missing_secret() {
11377                 let chanmon_cfgs = create_chanmon_cfgs(4);
11378                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11379                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11380                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11381
11382                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11383                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11384                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11385                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11386
11387                 // Marshall an MPP route.
11388                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11389                 let path = route.paths[0].clone();
11390                 route.paths.push(path);
11391                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11392                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11393                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11394                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11395                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11396                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11397
11398                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11399                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11400                 .unwrap_err() {
11401                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11402                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11403                         },
11404                         _ => panic!("unexpected error")
11405                 }
11406         }
11407
11408         #[test]
11409         fn test_drop_disconnected_peers_when_removing_channels() {
11410                 let chanmon_cfgs = create_chanmon_cfgs(2);
11411                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11412                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11413                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11414
11415                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11416
11417                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11418                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11419
11420                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11421                 check_closed_broadcast!(nodes[0], true);
11422                 check_added_monitors!(nodes[0], 1);
11423                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11424
11425                 {
11426                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11427                         // disconnected and the channel between has been force closed.
11428                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11429                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11430                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11431                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11432                 }
11433
11434                 nodes[0].node.timer_tick_occurred();
11435
11436                 {
11437                         // Assert that nodes[1] has now been removed.
11438                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11439                 }
11440         }
11441
11442         #[test]
11443         fn bad_inbound_payment_hash() {
11444                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11445                 let chanmon_cfgs = create_chanmon_cfgs(2);
11446                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11447                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11448                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11449
11450                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11451                 let payment_data = msgs::FinalOnionHopData {
11452                         payment_secret,
11453                         total_msat: 100_000,
11454                 };
11455
11456                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11457                 // payment verification fails as expected.
11458                 let mut bad_payment_hash = payment_hash.clone();
11459                 bad_payment_hash.0[0] += 1;
11460                 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) {
11461                         Ok(_) => panic!("Unexpected ok"),
11462                         Err(()) => {
11463                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11464                         }
11465                 }
11466
11467                 // Check that using the original payment hash succeeds.
11468                 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());
11469         }
11470
11471         #[test]
11472         fn test_id_to_peer_coverage() {
11473                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
11474                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11475                 // the channel is successfully closed.
11476                 let chanmon_cfgs = create_chanmon_cfgs(2);
11477                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11478                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11479                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11480
11481                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
11482                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11483                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11484                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11485                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11486
11487                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11488                 let channel_id = ChannelId::from_bytes(tx.txid().into_inner());
11489                 {
11490                         // Ensure that the `id_to_peer` map is empty until either party has received the
11491                         // funding transaction, and have the real `channel_id`.
11492                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11493                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11494                 }
11495
11496                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11497                 {
11498                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
11499                         // as it has the funding transaction.
11500                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11501                         assert_eq!(nodes_0_lock.len(), 1);
11502                         assert!(nodes_0_lock.contains_key(&channel_id));
11503                 }
11504
11505                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11506
11507                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11508
11509                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11510                 {
11511                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11512                         assert_eq!(nodes_0_lock.len(), 1);
11513                         assert!(nodes_0_lock.contains_key(&channel_id));
11514                 }
11515                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11516
11517                 {
11518                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
11519                         // as it has the funding transaction.
11520                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11521                         assert_eq!(nodes_1_lock.len(), 1);
11522                         assert!(nodes_1_lock.contains_key(&channel_id));
11523                 }
11524                 check_added_monitors!(nodes[1], 1);
11525                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11526                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11527                 check_added_monitors!(nodes[0], 1);
11528                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11529                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11530                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11531                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11532
11533                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11534                 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()));
11535                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11536                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11537
11538                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11539                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11540                 {
11541                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
11542                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11543                         // fee for the closing transaction has been negotiated and the parties has the other
11544                         // party's signature for the fee negotiated closing transaction.)
11545                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11546                         assert_eq!(nodes_0_lock.len(), 1);
11547                         assert!(nodes_0_lock.contains_key(&channel_id));
11548                 }
11549
11550                 {
11551                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11552                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11553                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11554                         // kept in the `nodes[1]`'s `id_to_peer` map.
11555                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11556                         assert_eq!(nodes_1_lock.len(), 1);
11557                         assert!(nodes_1_lock.contains_key(&channel_id));
11558                 }
11559
11560                 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()));
11561                 {
11562                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11563                         // therefore has all it needs to fully close the channel (both signatures for the
11564                         // closing transaction).
11565                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
11566                         // fully closed by `nodes[0]`.
11567                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11568
11569                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
11570                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11571                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11572                         assert_eq!(nodes_1_lock.len(), 1);
11573                         assert!(nodes_1_lock.contains_key(&channel_id));
11574                 }
11575
11576                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11577
11578                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11579                 {
11580                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
11581                         // they both have everything required to fully close the channel.
11582                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11583                 }
11584                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11585
11586                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11587                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11588         }
11589
11590         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11591                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11592                 check_api_error_message(expected_message, res_err)
11593         }
11594
11595         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11596                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11597                 check_api_error_message(expected_message, res_err)
11598         }
11599
11600         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11601                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11602                 check_api_error_message(expected_message, res_err)
11603         }
11604
11605         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11606                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11607                 check_api_error_message(expected_message, res_err)
11608         }
11609
11610         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11611                 match res_err {
11612                         Err(APIError::APIMisuseError { err }) => {
11613                                 assert_eq!(err, expected_err_message);
11614                         },
11615                         Err(APIError::ChannelUnavailable { err }) => {
11616                                 assert_eq!(err, expected_err_message);
11617                         },
11618                         Ok(_) => panic!("Unexpected Ok"),
11619                         Err(_) => panic!("Unexpected Error"),
11620                 }
11621         }
11622
11623         #[test]
11624         fn test_api_calls_with_unkown_counterparty_node() {
11625                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11626                 // expected if the `counterparty_node_id` is an unkown peer in the
11627                 // `ChannelManager::per_peer_state` map.
11628                 let chanmon_cfg = create_chanmon_cfgs(2);
11629                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11630                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11631                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11632
11633                 // Dummy values
11634                 let channel_id = ChannelId::from_bytes([4; 32]);
11635                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11636                 let intercept_id = InterceptId([0; 32]);
11637
11638                 // Test the API functions.
11639                 check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None), unkown_public_key);
11640
11641                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11642
11643                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11644
11645                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11646
11647                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11648
11649                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11650
11651                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11652         }
11653
11654         #[test]
11655         fn test_api_calls_with_unavailable_channel() {
11656                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11657                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11658                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11659                 // the given `channel_id`.
11660                 let chanmon_cfg = create_chanmon_cfgs(2);
11661                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11662                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11663                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11664
11665                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11666
11667                 // Dummy values
11668                 let channel_id = ChannelId::from_bytes([4; 32]);
11669
11670                 // Test the API functions.
11671                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11672
11673                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11674
11675                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11676
11677                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11678
11679                 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);
11680
11681                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11682         }
11683
11684         #[test]
11685         fn test_connection_limiting() {
11686                 // Test that we limit un-channel'd peers and un-funded channels properly.
11687                 let chanmon_cfgs = create_chanmon_cfgs(2);
11688                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11689                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11690                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11691
11692                 // Note that create_network connects the nodes together for us
11693
11694                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11695                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11696
11697                 let mut funding_tx = None;
11698                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11699                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11700                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11701
11702                         if idx == 0 {
11703                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11704                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11705                                 funding_tx = Some(tx.clone());
11706                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11707                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11708
11709                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11710                                 check_added_monitors!(nodes[1], 1);
11711                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11712
11713                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11714
11715                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11716                                 check_added_monitors!(nodes[0], 1);
11717                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11718                         }
11719                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11720                 }
11721
11722                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11723                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11724                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11725                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11726                         open_channel_msg.temporary_channel_id);
11727
11728                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11729                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11730                 // limit.
11731                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11732                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11733                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11734                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11735                         peer_pks.push(random_pk);
11736                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11737                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11738                         }, true).unwrap();
11739                 }
11740                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11741                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11742                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11743                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11744                 }, true).unwrap_err();
11745
11746                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11747                 // them if we have too many un-channel'd peers.
11748                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11749                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11750                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
11751                 for ev in chan_closed_events {
11752                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
11753                 }
11754                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11755                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11756                 }, true).unwrap();
11757                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11758                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11759                 }, true).unwrap_err();
11760
11761                 // but of course if the connection is outbound its allowed...
11762                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11763                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11764                 }, false).unwrap();
11765                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11766
11767                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
11768                 // Even though we accept one more connection from new peers, we won't actually let them
11769                 // open channels.
11770                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
11771                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11772                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
11773                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
11774                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11775                 }
11776                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11777                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11778                         open_channel_msg.temporary_channel_id);
11779
11780                 // Of course, however, outbound channels are always allowed
11781                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
11782                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
11783
11784                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
11785                 // "protected" and can connect again.
11786                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
11787                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11788                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11789                 }, true).unwrap();
11790                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
11791
11792                 // Further, because the first channel was funded, we can open another channel with
11793                 // last_random_pk.
11794                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11795                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11796         }
11797
11798         #[test]
11799         fn test_outbound_chans_unlimited() {
11800                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
11801                 let chanmon_cfgs = create_chanmon_cfgs(2);
11802                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11803                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11804                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11805
11806                 // Note that create_network connects the nodes together for us
11807
11808                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11809                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11810
11811                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11812                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11813                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11814                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11815                 }
11816
11817                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
11818                 // rejected.
11819                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11820                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11821                         open_channel_msg.temporary_channel_id);
11822
11823                 // but we can still open an outbound channel.
11824                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11825                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
11826
11827                 // but even with such an outbound channel, additional inbound channels will still fail.
11828                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11829                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11830                         open_channel_msg.temporary_channel_id);
11831         }
11832
11833         #[test]
11834         fn test_0conf_limiting() {
11835                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11836                 // flag set and (sometimes) accept channels as 0conf.
11837                 let chanmon_cfgs = create_chanmon_cfgs(2);
11838                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11839                 let mut settings = test_default_channel_config();
11840                 settings.manually_accept_inbound_channels = true;
11841                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
11842                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11843
11844                 // Note that create_network connects the nodes together for us
11845
11846                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11847                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11848
11849                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
11850                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11851                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11852                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11853                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11854                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11855                         }, true).unwrap();
11856
11857                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
11858                         let events = nodes[1].node.get_and_clear_pending_events();
11859                         match events[0] {
11860                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11861                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
11862                                 }
11863                                 _ => panic!("Unexpected event"),
11864                         }
11865                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
11866                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11867                 }
11868
11869                 // If we try to accept a channel from another peer non-0conf it will fail.
11870                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11871                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11872                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11873                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11874                 }, true).unwrap();
11875                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11876                 let events = nodes[1].node.get_and_clear_pending_events();
11877                 match events[0] {
11878                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11879                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
11880                                         Err(APIError::APIMisuseError { err }) =>
11881                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
11882                                         _ => panic!(),
11883                                 }
11884                         }
11885                         _ => panic!("Unexpected event"),
11886                 }
11887                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11888                         open_channel_msg.temporary_channel_id);
11889
11890                 // ...however if we accept the same channel 0conf it should work just fine.
11891                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11892                 let events = nodes[1].node.get_and_clear_pending_events();
11893                 match events[0] {
11894                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11895                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
11896                         }
11897                         _ => panic!("Unexpected event"),
11898                 }
11899                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11900         }
11901
11902         #[test]
11903         fn reject_excessively_underpaying_htlcs() {
11904                 let chanmon_cfg = create_chanmon_cfgs(1);
11905                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11906                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11907                 let node = create_network(1, &node_cfg, &node_chanmgr);
11908                 let sender_intended_amt_msat = 100;
11909                 let extra_fee_msat = 10;
11910                 let hop_data = msgs::InboundOnionPayload::Receive {
11911                         amt_msat: 100,
11912                         outgoing_cltv_value: 42,
11913                         payment_metadata: None,
11914                         keysend_preimage: None,
11915                         payment_data: Some(msgs::FinalOnionHopData {
11916                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11917                         }),
11918                         custom_tlvs: Vec::new(),
11919                 };
11920                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
11921                 // intended amount, we fail the payment.
11922                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11923                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
11924                         create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11925                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
11926                                 current_height, node[0].node.default_configuration.accept_mpp_keysend)
11927                 {
11928                         assert_eq!(err_code, 19);
11929                 } else { panic!(); }
11930
11931                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
11932                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
11933                         amt_msat: 100,
11934                         outgoing_cltv_value: 42,
11935                         payment_metadata: None,
11936                         keysend_preimage: None,
11937                         payment_data: Some(msgs::FinalOnionHopData {
11938                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11939                         }),
11940                         custom_tlvs: Vec::new(),
11941                 };
11942                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11943                 assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11944                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
11945                         current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
11946         }
11947
11948         #[test]
11949         fn test_final_incorrect_cltv(){
11950                 let chanmon_cfg = create_chanmon_cfgs(1);
11951                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11952                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11953                 let node = create_network(1, &node_cfg, &node_chanmgr);
11954
11955                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11956                 let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
11957                         amt_msat: 100,
11958                         outgoing_cltv_value: 22,
11959                         payment_metadata: None,
11960                         keysend_preimage: None,
11961                         payment_data: Some(msgs::FinalOnionHopData {
11962                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
11963                         }),
11964                         custom_tlvs: Vec::new(),
11965                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
11966                         node[0].node.default_configuration.accept_mpp_keysend);
11967
11968                 // Should not return an error as this condition:
11969                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
11970                 // is not satisfied.
11971                 assert!(result.is_ok());
11972         }
11973
11974         #[test]
11975         fn test_inbound_anchors_manual_acceptance() {
11976                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11977                 // flag set and (sometimes) accept channels as 0conf.
11978                 let mut anchors_cfg = test_default_channel_config();
11979                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11980
11981                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
11982                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
11983
11984                 let chanmon_cfgs = create_chanmon_cfgs(3);
11985                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11986                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
11987                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
11988                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11989
11990                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11991                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11992
11993                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11994                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11995                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
11996                 match &msg_events[0] {
11997                         MessageSendEvent::HandleError { node_id, action } => {
11998                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
11999                                 match action {
12000                                         ErrorAction::SendErrorMessage { msg } =>
12001                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
12002                                         _ => panic!("Unexpected error action"),
12003                                 }
12004                         }
12005                         _ => panic!("Unexpected event"),
12006                 }
12007
12008                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12009                 let events = nodes[2].node.get_and_clear_pending_events();
12010                 match events[0] {
12011                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
12012                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
12013                         _ => panic!("Unexpected event"),
12014                 }
12015                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12016         }
12017
12018         #[test]
12019         fn test_anchors_zero_fee_htlc_tx_fallback() {
12020                 // Tests that if both nodes support anchors, but the remote node does not want to accept
12021                 // anchor channels at the moment, an error it sent to the local node such that it can retry
12022                 // the channel without the anchors feature.
12023                 let chanmon_cfgs = create_chanmon_cfgs(2);
12024                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12025                 let mut anchors_config = test_default_channel_config();
12026                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12027                 anchors_config.manually_accept_inbound_channels = true;
12028                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
12029                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12030
12031                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
12032                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12033                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
12034
12035                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12036                 let events = nodes[1].node.get_and_clear_pending_events();
12037                 match events[0] {
12038                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12039                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
12040                         }
12041                         _ => panic!("Unexpected event"),
12042                 }
12043
12044                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
12045                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
12046
12047                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12048                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
12049
12050                 // Since nodes[1] should not have accepted the channel, it should
12051                 // not have generated any events.
12052                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12053         }
12054
12055         #[test]
12056         fn test_update_channel_config() {
12057                 let chanmon_cfg = create_chanmon_cfgs(2);
12058                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12059                 let mut user_config = test_default_channel_config();
12060                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12061                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12062                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
12063                 let channel = &nodes[0].node.list_channels()[0];
12064
12065                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12066                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12067                 assert_eq!(events.len(), 0);
12068
12069                 user_config.channel_config.forwarding_fee_base_msat += 10;
12070                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12071                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
12072                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12073                 assert_eq!(events.len(), 1);
12074                 match &events[0] {
12075                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12076                         _ => panic!("expected BroadcastChannelUpdate event"),
12077                 }
12078
12079                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
12080                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12081                 assert_eq!(events.len(), 0);
12082
12083                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
12084                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12085                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
12086                         ..Default::default()
12087                 }).unwrap();
12088                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12089                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12090                 assert_eq!(events.len(), 1);
12091                 match &events[0] {
12092                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12093                         _ => panic!("expected BroadcastChannelUpdate event"),
12094                 }
12095
12096                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
12097                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12098                         forwarding_fee_proportional_millionths: Some(new_fee),
12099                         ..Default::default()
12100                 }).unwrap();
12101                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12102                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
12103                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12104                 assert_eq!(events.len(), 1);
12105                 match &events[0] {
12106                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12107                         _ => panic!("expected BroadcastChannelUpdate event"),
12108                 }
12109
12110                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
12111                 // should be applied to ensure update atomicity as specified in the API docs.
12112                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
12113                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
12114                 let new_fee = current_fee + 100;
12115                 assert!(
12116                         matches!(
12117                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
12118                                         forwarding_fee_proportional_millionths: Some(new_fee),
12119                                         ..Default::default()
12120                                 }),
12121                                 Err(APIError::ChannelUnavailable { err: _ }),
12122                         )
12123                 );
12124                 // Check that the fee hasn't changed for the channel that exists.
12125                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
12126                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12127                 assert_eq!(events.len(), 0);
12128         }
12129
12130         #[test]
12131         fn test_payment_display() {
12132                 let payment_id = PaymentId([42; 32]);
12133                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12134                 let payment_hash = PaymentHash([42; 32]);
12135                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12136                 let payment_preimage = PaymentPreimage([42; 32]);
12137                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12138         }
12139
12140         #[test]
12141         fn test_trigger_lnd_force_close() {
12142                 let chanmon_cfg = create_chanmon_cfgs(2);
12143                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12144                 let user_config = test_default_channel_config();
12145                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12146                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12147
12148                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
12149                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
12150                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
12151                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12152                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
12153                 check_closed_broadcast(&nodes[0], 1, true);
12154                 check_added_monitors(&nodes[0], 1);
12155                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
12156                 {
12157                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
12158                         assert_eq!(txn.len(), 1);
12159                         check_spends!(txn[0], funding_tx);
12160                 }
12161
12162                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
12163                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
12164                 // their side.
12165                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
12166                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
12167                 }, true).unwrap();
12168                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12169                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12170                 }, false).unwrap();
12171                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
12172                 let channel_reestablish = get_event_msg!(
12173                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
12174                 );
12175                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
12176
12177                 // Alice should respond with an error since the channel isn't known, but a bogus
12178                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
12179                 // close even if it was an lnd node.
12180                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
12181                 assert_eq!(msg_events.len(), 2);
12182                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
12183                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
12184                         assert_eq!(msg.next_local_commitment_number, 0);
12185                         assert_eq!(msg.next_remote_commitment_number, 0);
12186                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
12187                 } else { panic!() };
12188                 check_closed_broadcast(&nodes[1], 1, true);
12189                 check_added_monitors(&nodes[1], 1);
12190                 let expected_close_reason = ClosureReason::ProcessingError {
12191                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
12192                 };
12193                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
12194                 {
12195                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
12196                         assert_eq!(txn.len(), 1);
12197                         check_spends!(txn[0], funding_tx);
12198                 }
12199         }
12200
12201         #[test]
12202         fn test_peel_payment_onion() {
12203                 use super::*;
12204                 let secp_ctx = Secp256k1::new();
12205
12206                 let bob = crate::sign::KeysManager::new(&[2; 32], 42, 42);
12207                 let bob_pk = PublicKey::from_secret_key(&secp_ctx, &bob.get_node_secret_key());
12208                 let charlie = crate::sign::KeysManager::new(&[3; 32], 42, 42);
12209                 let charlie_pk = PublicKey::from_secret_key(&secp_ctx, &charlie.get_node_secret_key());
12210
12211                 let (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
12212                         prng_seed, hops, recipient_amount, pay_secret) = payment_onion_args(bob_pk, charlie_pk);
12213
12214                 let path = Path {
12215                         hops: hops,
12216                         blinded_tail: None,
12217                 };
12218
12219                 let (amount_msat, cltv_expiry, onion) = create_payment_onion(
12220                         &secp_ctx, &path, &session_priv, total_amt_msat, recipient_onion, cur_height,
12221                         payment_hash, Some(preimage), prng_seed
12222                 ).unwrap();
12223
12224                 let msg = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, onion);
12225                 let logger = test_utils::TestLogger::with_id("bob".to_string());
12226
12227                 let peeled = peel_payment_onion(&msg, &&bob, &&logger, &secp_ctx, cur_height, true)
12228                         .map_err(|e| e.msg).unwrap();
12229
12230                 let next_onion = match peeled.routing {
12231                         PendingHTLCRouting::Forward { onion_packet, short_channel_id: _ } => {
12232                                 onion_packet
12233                         },
12234                         _ => panic!("expected a forwarded onion"),
12235                 };
12236
12237                 let msg2 = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, next_onion);
12238                 let peeled2 = peel_payment_onion(&msg2, &&charlie, &&logger, &secp_ctx, cur_height, true)
12239                         .map_err(|e| e.msg).unwrap();
12240
12241                 match peeled2.routing {
12242                         PendingHTLCRouting::ReceiveKeysend { payment_preimage, payment_data, incoming_cltv_expiry, .. } => {
12243                                 assert_eq!(payment_preimage, preimage);
12244                                 assert_eq!(peeled2.outgoing_amt_msat, recipient_amount);
12245                                 assert_eq!(incoming_cltv_expiry, peeled2.outgoing_cltv_value);
12246                                 let msgs::FinalOnionHopData{total_msat, payment_secret} = payment_data.unwrap();
12247                                 assert_eq!(total_msat, total_amt_msat);
12248                                 assert_eq!(payment_secret, pay_secret);
12249                         },
12250                         _ => panic!("expected a received keysend"),
12251                 };
12252         }
12253
12254         fn make_update_add_msg(
12255                 amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash,
12256                 onion_routing_packet: msgs::OnionPacket
12257         ) -> msgs::UpdateAddHTLC {
12258                 msgs::UpdateAddHTLC {
12259                         channel_id: ChannelId::from_bytes([0; 32]),
12260                         htlc_id: 0,
12261                         amount_msat,
12262                         cltv_expiry,
12263                         payment_hash,
12264                         onion_routing_packet,
12265                         skimmed_fee_msat: None,
12266                 }
12267         }
12268
12269         fn payment_onion_args(hop_pk: PublicKey, recipient_pk: PublicKey) -> (
12270                 SecretKey, u64, u32, RecipientOnionFields, PaymentPreimage, PaymentHash, [u8; 32],
12271                 Vec<RouteHop>, u64, PaymentSecret,
12272         ) {
12273                 let session_priv_bytes = [42; 32];
12274                 let session_priv = SecretKey::from_slice(&session_priv_bytes).unwrap();
12275                 let total_amt_msat = 1000;
12276                 let cur_height = 1000;
12277                 let pay_secret = PaymentSecret([99; 32]);
12278                 let recipient_onion = RecipientOnionFields::secret_only(pay_secret);
12279                 let preimage_bytes = [43; 32];
12280                 let preimage = PaymentPreimage(preimage_bytes);
12281                 let rhash_bytes = Sha256::hash(&preimage_bytes).into_inner();
12282                 let payment_hash = PaymentHash(rhash_bytes);
12283                 let prng_seed = [44; 32];
12284
12285                 // make a route alice -> bob -> charlie
12286                 let hop_fee = 1;
12287                 let recipient_amount = total_amt_msat - hop_fee;
12288                 let hops = vec![
12289                         RouteHop {
12290                                 pubkey: hop_pk,
12291                                 fee_msat: hop_fee,
12292                                 cltv_expiry_delta: 42,
12293                                 short_channel_id: 1,
12294                                 node_features: NodeFeatures::empty(),
12295                                 channel_features: ChannelFeatures::empty(),
12296                                 maybe_announced_channel: false,
12297                         },
12298                         RouteHop {
12299                                 pubkey: recipient_pk,
12300                                 fee_msat: recipient_amount,
12301                                 cltv_expiry_delta: 42,
12302                                 short_channel_id: 2,
12303                                 node_features: NodeFeatures::empty(),
12304                                 channel_features: ChannelFeatures::empty(),
12305                                 maybe_announced_channel: false,
12306                         }
12307                 ];
12308
12309                 (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
12310                         prng_seed, hops, recipient_amount, pay_secret)
12311         }
12312
12313         pub fn create_payment_onion<T: bitcoin::secp256k1::Signing>(
12314                 secp_ctx: &Secp256k1<T>, path: &Path, session_priv: &SecretKey, total_msat: u64,
12315                 recipient_onion: RecipientOnionFields, best_block_height: u32, payment_hash: PaymentHash,
12316                 keysend_preimage: Option<PaymentPreimage>, prng_seed: [u8; 32]
12317         ) -> Result<(u64, u32, msgs::OnionPacket), ()> {
12318                 let onion_keys = super::onion_utils::construct_onion_keys(&secp_ctx, &path, &session_priv).map_err(|_| ())?;
12319                 let (onion_payloads, htlc_msat, htlc_cltv) = super::onion_utils::build_onion_payloads(
12320                         &path,
12321                         total_msat,
12322                         recipient_onion,
12323                         best_block_height + 1,
12324                         &keysend_preimage,
12325                 ).map_err(|_| ())?;
12326                 let onion_packet = super::onion_utils::construct_onion_packet(
12327                         onion_payloads, onion_keys, prng_seed, &payment_hash
12328                 )?;
12329                 Ok((htlc_msat, htlc_cltv, onion_packet))
12330         }
12331 }
12332
12333 #[cfg(ldk_bench)]
12334 pub mod bench {
12335         use crate::chain::Listen;
12336         use crate::chain::chainmonitor::{ChainMonitor, Persist};
12337         use crate::sign::{KeysManager, InMemorySigner};
12338         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
12339         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
12340         use crate::ln::functional_test_utils::*;
12341         use crate::ln::msgs::{ChannelMessageHandler, Init};
12342         use crate::routing::gossip::NetworkGraph;
12343         use crate::routing::router::{PaymentParameters, RouteParameters};
12344         use crate::util::test_utils;
12345         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
12346
12347         use bitcoin::hashes::Hash;
12348         use bitcoin::hashes::sha256::Hash as Sha256;
12349         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
12350
12351         use crate::sync::{Arc, Mutex, RwLock};
12352
12353         use criterion::Criterion;
12354
12355         type Manager<'a, P> = ChannelManager<
12356                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
12357                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
12358                         &'a test_utils::TestLogger, &'a P>,
12359                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
12360                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
12361                 &'a test_utils::TestLogger>;
12362
12363         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
12364                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
12365         }
12366         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
12367                 type CM = Manager<'chan_mon_cfg, P>;
12368                 #[inline]
12369                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
12370                 #[inline]
12371                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
12372         }
12373
12374         pub fn bench_sends(bench: &mut Criterion) {
12375                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
12376         }
12377
12378         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
12379                 // Do a simple benchmark of sending a payment back and forth between two nodes.
12380                 // Note that this is unrealistic as each payment send will require at least two fsync
12381                 // calls per node.
12382                 let network = bitcoin::Network::Testnet;
12383                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
12384
12385                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
12386                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
12387                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
12388                 let scorer = RwLock::new(test_utils::TestScorer::new());
12389                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
12390
12391                 let mut config: UserConfig = Default::default();
12392                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
12393                 config.channel_handshake_config.minimum_depth = 1;
12394
12395                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
12396                 let seed_a = [1u8; 32];
12397                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
12398                 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 {
12399                         network,
12400                         best_block: BestBlock::from_network(network),
12401                 }, genesis_block.header.time);
12402                 let node_a_holder = ANodeHolder { node: &node_a };
12403
12404                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
12405                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
12406                 let seed_b = [2u8; 32];
12407                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
12408                 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 {
12409                         network,
12410                         best_block: BestBlock::from_network(network),
12411                 }, genesis_block.header.time);
12412                 let node_b_holder = ANodeHolder { node: &node_b };
12413
12414                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
12415                         features: node_b.init_features(), networks: None, remote_network_address: None
12416                 }, true).unwrap();
12417                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
12418                         features: node_a.init_features(), networks: None, remote_network_address: None
12419                 }, false).unwrap();
12420                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
12421                 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()));
12422                 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()));
12423
12424                 let tx;
12425                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
12426                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12427                                 value: 8_000_000, script_pubkey: output_script,
12428                         }]};
12429                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
12430                 } else { panic!(); }
12431
12432                 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()));
12433                 let events_b = node_b.get_and_clear_pending_events();
12434                 assert_eq!(events_b.len(), 1);
12435                 match events_b[0] {
12436                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12437                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12438                         },
12439                         _ => panic!("Unexpected event"),
12440                 }
12441
12442                 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()));
12443                 let events_a = node_a.get_and_clear_pending_events();
12444                 assert_eq!(events_a.len(), 1);
12445                 match events_a[0] {
12446                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12447                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12448                         },
12449                         _ => panic!("Unexpected event"),
12450                 }
12451
12452                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
12453
12454                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
12455                 Listen::block_connected(&node_a, &block, 1);
12456                 Listen::block_connected(&node_b, &block, 1);
12457
12458                 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()));
12459                 let msg_events = node_a.get_and_clear_pending_msg_events();
12460                 assert_eq!(msg_events.len(), 2);
12461                 match msg_events[0] {
12462                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
12463                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
12464                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
12465                         },
12466                         _ => panic!(),
12467                 }
12468                 match msg_events[1] {
12469                         MessageSendEvent::SendChannelUpdate { .. } => {},
12470                         _ => panic!(),
12471                 }
12472
12473                 let events_a = node_a.get_and_clear_pending_events();
12474                 assert_eq!(events_a.len(), 1);
12475                 match events_a[0] {
12476                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12477                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12478                         },
12479                         _ => panic!("Unexpected event"),
12480                 }
12481
12482                 let events_b = node_b.get_and_clear_pending_events();
12483                 assert_eq!(events_b.len(), 1);
12484                 match events_b[0] {
12485                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12486                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12487                         },
12488                         _ => panic!("Unexpected event"),
12489                 }
12490
12491                 let mut payment_count: u64 = 0;
12492                 macro_rules! send_payment {
12493                         ($node_a: expr, $node_b: expr) => {
12494                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
12495                                         .with_bolt11_features($node_b.bolt11_invoice_features()).unwrap();
12496                                 let mut payment_preimage = PaymentPreimage([0; 32]);
12497                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
12498                                 payment_count += 1;
12499                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
12500                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
12501
12502                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
12503                                         PaymentId(payment_hash.0),
12504                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12505                                         Retry::Attempts(0)).unwrap();
12506                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12507                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12508                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12509                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12510                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12511                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12512                                 $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()));
12513
12514                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12515                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12516                                 $node_b.claim_funds(payment_preimage);
12517                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12518
12519                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12520                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12521                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12522                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12523                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12524                                         },
12525                                         _ => panic!("Failed to generate claim event"),
12526                                 }
12527
12528                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12529                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12530                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12531                                 $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()));
12532
12533                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12534                         }
12535                 }
12536
12537                 bench.bench_function(bench_name, |b| b.iter(|| {
12538                         send_payment!(node_a, node_b);
12539                         send_payment!(node_b, node_a);
12540                 }));
12541         }
12542 }