InboundOnionErr fields public
[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         /// BOLT 4 error code.
400         pub err_code: u16,
401         /// Data attached to this error.
402         pub err_data: Vec<u8>,
403         /// Error message text.
404         pub msg: &'static str,
405 }
406
407 /// This enum is used to specify which error data to send to peers when failing back an HTLC
408 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
409 ///
410 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
411 #[derive(Clone, Copy)]
412 pub enum FailureCode {
413         /// We had a temporary error processing the payment. Useful if no other error codes fit
414         /// and you want to indicate that the payer may want to retry.
415         TemporaryNodeFailure,
416         /// We have a required feature which was not in this onion. For example, you may require
417         /// some additional metadata that was not provided with this payment.
418         RequiredNodeFeatureMissing,
419         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
420         /// the HTLC is too close to the current block height for safe handling.
421         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
422         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
423         IncorrectOrUnknownPaymentDetails,
424         /// We failed to process the payload after the onion was decrypted. You may wish to
425         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
426         ///
427         /// If available, the tuple data may include the type number and byte offset in the
428         /// decrypted byte stream where the failure occurred.
429         InvalidOnionPayload(Option<(u64, u16)>),
430 }
431
432 impl Into<u16> for FailureCode {
433     fn into(self) -> u16 {
434                 match self {
435                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
436                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
437                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
438                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
439                 }
440         }
441 }
442
443 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
444 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
445 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
446 /// peer_state lock. We then return the set of things that need to be done outside the lock in
447 /// this struct and call handle_error!() on it.
448
449 struct MsgHandleErrInternal {
450         err: msgs::LightningError,
451         chan_id: Option<(ChannelId, u128)>, // If Some a channel of ours has been closed
452         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
453         channel_capacity: Option<u64>,
454 }
455 impl MsgHandleErrInternal {
456         #[inline]
457         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
458                 Self {
459                         err: LightningError {
460                                 err: err.clone(),
461                                 action: msgs::ErrorAction::SendErrorMessage {
462                                         msg: msgs::ErrorMessage {
463                                                 channel_id,
464                                                 data: err
465                                         },
466                                 },
467                         },
468                         chan_id: None,
469                         shutdown_finish: None,
470                         channel_capacity: None,
471                 }
472         }
473         #[inline]
474         fn from_no_close(err: msgs::LightningError) -> Self {
475                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
476         }
477         #[inline]
478         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 {
479                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
480                 let action = if shutdown_res.monitor_update.is_some() {
481                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
482                         // should disconnect our peer such that we force them to broadcast their latest
483                         // commitment upon reconnecting.
484                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
485                 } else {
486                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
487                 };
488                 Self {
489                         err: LightningError { err, action },
490                         chan_id: Some((channel_id, user_channel_id)),
491                         shutdown_finish: Some((shutdown_res, channel_update)),
492                         channel_capacity: Some(channel_capacity)
493                 }
494         }
495         #[inline]
496         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
497                 Self {
498                         err: match err {
499                                 ChannelError::Warn(msg) =>  LightningError {
500                                         err: msg.clone(),
501                                         action: msgs::ErrorAction::SendWarningMessage {
502                                                 msg: msgs::WarningMessage {
503                                                         channel_id,
504                                                         data: msg
505                                                 },
506                                                 log_level: Level::Warn,
507                                         },
508                                 },
509                                 ChannelError::Ignore(msg) => LightningError {
510                                         err: msg,
511                                         action: msgs::ErrorAction::IgnoreError,
512                                 },
513                                 ChannelError::Close(msg) => LightningError {
514                                         err: msg.clone(),
515                                         action: msgs::ErrorAction::SendErrorMessage {
516                                                 msg: msgs::ErrorMessage {
517                                                         channel_id,
518                                                         data: msg
519                                                 },
520                                         },
521                                 },
522                         },
523                         chan_id: None,
524                         shutdown_finish: None,
525                         channel_capacity: None,
526                 }
527         }
528
529         fn closes_channel(&self) -> bool {
530                 self.chan_id.is_some()
531         }
532 }
533
534 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
535 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
536 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
537 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
538 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
539
540 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
541 /// be sent in the order they appear in the return value, however sometimes the order needs to be
542 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
543 /// they were originally sent). In those cases, this enum is also returned.
544 #[derive(Clone, PartialEq)]
545 pub(super) enum RAACommitmentOrder {
546         /// Send the CommitmentUpdate messages first
547         CommitmentFirst,
548         /// Send the RevokeAndACK message first
549         RevokeAndACKFirst,
550 }
551
552 /// Information about a payment which is currently being claimed.
553 struct ClaimingPayment {
554         amount_msat: u64,
555         payment_purpose: events::PaymentPurpose,
556         receiver_node_id: PublicKey,
557         htlcs: Vec<events::ClaimedHTLC>,
558         sender_intended_value: Option<u64>,
559 }
560 impl_writeable_tlv_based!(ClaimingPayment, {
561         (0, amount_msat, required),
562         (2, payment_purpose, required),
563         (4, receiver_node_id, required),
564         (5, htlcs, optional_vec),
565         (7, sender_intended_value, option),
566 });
567
568 struct ClaimablePayment {
569         purpose: events::PaymentPurpose,
570         onion_fields: Option<RecipientOnionFields>,
571         htlcs: Vec<ClaimableHTLC>,
572 }
573
574 /// Information about claimable or being-claimed payments
575 struct ClaimablePayments {
576         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
577         /// failed/claimed by the user.
578         ///
579         /// Note that, no consistency guarantees are made about the channels given here actually
580         /// existing anymore by the time you go to read them!
581         ///
582         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
583         /// we don't get a duplicate payment.
584         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
585
586         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
587         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
588         /// as an [`events::Event::PaymentClaimed`].
589         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
590 }
591
592 /// Events which we process internally but cannot be processed immediately at the generation site
593 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
594 /// running normally, and specifically must be processed before any other non-background
595 /// [`ChannelMonitorUpdate`]s are applied.
596 #[derive(Debug)]
597 enum BackgroundEvent {
598         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
599         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
600         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
601         /// channel has been force-closed we do not need the counterparty node_id.
602         ///
603         /// Note that any such events are lost on shutdown, so in general they must be updates which
604         /// are regenerated on startup.
605         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
606         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
607         /// channel to continue normal operation.
608         ///
609         /// In general this should be used rather than
610         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
611         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
612         /// error the other variant is acceptable.
613         ///
614         /// Note that any such events are lost on shutdown, so in general they must be updates which
615         /// are regenerated on startup.
616         MonitorUpdateRegeneratedOnStartup {
617                 counterparty_node_id: PublicKey,
618                 funding_txo: OutPoint,
619                 update: ChannelMonitorUpdate
620         },
621         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
622         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
623         /// on a channel.
624         MonitorUpdatesComplete {
625                 counterparty_node_id: PublicKey,
626                 channel_id: ChannelId,
627         },
628 }
629
630 #[derive(Debug)]
631 pub(crate) enum MonitorUpdateCompletionAction {
632         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
633         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
634         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
635         /// event can be generated.
636         PaymentClaimed { payment_hash: PaymentHash },
637         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
638         /// operation of another channel.
639         ///
640         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
641         /// from completing a monitor update which removes the payment preimage until the inbound edge
642         /// completes a monitor update containing the payment preimage. In that case, after the inbound
643         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
644         /// outbound edge.
645         EmitEventAndFreeOtherChannel {
646                 event: events::Event,
647                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
648         },
649         /// Indicates we should immediately resume the operation of another channel, unless there is
650         /// some other reason why the channel is blocked. In practice this simply means immediately
651         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
652         ///
653         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
654         /// from completing a monitor update which removes the payment preimage until the inbound edge
655         /// completes a monitor update containing the payment preimage. However, we use this variant
656         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
657         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
658         ///
659         /// This variant should thus never be written to disk, as it is processed inline rather than
660         /// stored for later processing.
661         FreeOtherChannelImmediately {
662                 downstream_counterparty_node_id: PublicKey,
663                 downstream_funding_outpoint: OutPoint,
664                 blocking_action: RAAMonitorUpdateBlockingAction,
665         },
666 }
667
668 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
669         (0, PaymentClaimed) => { (0, payment_hash, required) },
670         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
671         // *immediately*. However, for simplicity we implement read/write here.
672         (1, FreeOtherChannelImmediately) => {
673                 (0, downstream_counterparty_node_id, required),
674                 (2, downstream_funding_outpoint, required),
675                 (4, blocking_action, required),
676         },
677         (2, EmitEventAndFreeOtherChannel) => {
678                 (0, event, upgradable_required),
679                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
680                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
681                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
682                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
683                 // downgrades to prior versions.
684                 (1, downstream_counterparty_and_funding_outpoint, option),
685         },
686 );
687
688 #[derive(Clone, Debug, PartialEq, Eq)]
689 pub(crate) enum EventCompletionAction {
690         ReleaseRAAChannelMonitorUpdate {
691                 counterparty_node_id: PublicKey,
692                 channel_funding_outpoint: OutPoint,
693         },
694 }
695 impl_writeable_tlv_based_enum!(EventCompletionAction,
696         (0, ReleaseRAAChannelMonitorUpdate) => {
697                 (0, channel_funding_outpoint, required),
698                 (2, counterparty_node_id, required),
699         };
700 );
701
702 #[derive(Clone, PartialEq, Eq, Debug)]
703 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
704 /// the blocked action here. See enum variants for more info.
705 pub(crate) enum RAAMonitorUpdateBlockingAction {
706         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
707         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
708         /// durably to disk.
709         ForwardedPaymentInboundClaim {
710                 /// The upstream channel ID (i.e. the inbound edge).
711                 channel_id: ChannelId,
712                 /// The HTLC ID on the inbound edge.
713                 htlc_id: u64,
714         },
715 }
716
717 impl RAAMonitorUpdateBlockingAction {
718         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
719                 Self::ForwardedPaymentInboundClaim {
720                         channel_id: prev_hop.outpoint.to_channel_id(),
721                         htlc_id: prev_hop.htlc_id,
722                 }
723         }
724 }
725
726 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
727         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
728 ;);
729
730
731 /// State we hold per-peer.
732 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
733         /// `channel_id` -> `ChannelPhase`
734         ///
735         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
736         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
737         /// `temporary_channel_id` -> `InboundChannelRequest`.
738         ///
739         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
740         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
741         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
742         /// the channel is rejected, then the entry is simply removed.
743         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
744         /// The latest `InitFeatures` we heard from the peer.
745         latest_features: InitFeatures,
746         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
747         /// for broadcast messages, where ordering isn't as strict).
748         pub(super) pending_msg_events: Vec<MessageSendEvent>,
749         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
750         /// user but which have not yet completed.
751         ///
752         /// Note that the channel may no longer exist. For example if the channel was closed but we
753         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
754         /// for a missing channel.
755         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
756         /// Map from a specific channel to some action(s) that should be taken when all pending
757         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
758         ///
759         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
760         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
761         /// channels with a peer this will just be one allocation and will amount to a linear list of
762         /// channels to walk, avoiding the whole hashing rigmarole.
763         ///
764         /// Note that the channel may no longer exist. For example, if a channel was closed but we
765         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
766         /// for a missing channel. While a malicious peer could construct a second channel with the
767         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
768         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
769         /// duplicates do not occur, so such channels should fail without a monitor update completing.
770         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
771         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
772         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
773         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
774         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
775         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
776         /// The peer is currently connected (i.e. we've seen a
777         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
778         /// [`ChannelMessageHandler::peer_disconnected`].
779         is_connected: bool,
780 }
781
782 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
783         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
784         /// If true is passed for `require_disconnected`, the function will return false if we haven't
785         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
786         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
787                 if require_disconnected && self.is_connected {
788                         return false
789                 }
790                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
791                         && self.monitor_update_blocked_actions.is_empty()
792                         && self.in_flight_monitor_updates.is_empty()
793         }
794
795         // Returns a count of all channels we have with this peer, including unfunded channels.
796         fn total_channel_count(&self) -> usize {
797                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
798         }
799
800         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
801         fn has_channel(&self, channel_id: &ChannelId) -> bool {
802                 self.channel_by_id.contains_key(channel_id) ||
803                         self.inbound_channel_request_by_id.contains_key(channel_id)
804         }
805 }
806
807 /// A not-yet-accepted inbound (from counterparty) channel. Once
808 /// accepted, the parameters will be used to construct a channel.
809 pub(super) struct InboundChannelRequest {
810         /// The original OpenChannel message.
811         pub open_channel_msg: msgs::OpenChannel,
812         /// The number of ticks remaining before the request expires.
813         pub ticks_remaining: i32,
814 }
815
816 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
817 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
818 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
819
820 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
821 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
822 ///
823 /// For users who don't want to bother doing their own payment preimage storage, we also store that
824 /// here.
825 ///
826 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
827 /// and instead encoding it in the payment secret.
828 struct PendingInboundPayment {
829         /// The payment secret that the sender must use for us to accept this payment
830         payment_secret: PaymentSecret,
831         /// Time at which this HTLC expires - blocks with a header time above this value will result in
832         /// this payment being removed.
833         expiry_time: u64,
834         /// Arbitrary identifier the user specifies (or not)
835         user_payment_id: u64,
836         // Other required attributes of the payment, optionally enforced:
837         payment_preimage: Option<PaymentPreimage>,
838         min_value_msat: Option<u64>,
839 }
840
841 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
842 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
843 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
844 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
845 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
846 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
847 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
848 /// of [`KeysManager`] and [`DefaultRouter`].
849 ///
850 /// This is not exported to bindings users as type aliases aren't supported in most languages.
851 #[cfg(not(c_bindings))]
852 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
853         Arc<M>,
854         Arc<T>,
855         Arc<KeysManager>,
856         Arc<KeysManager>,
857         Arc<KeysManager>,
858         Arc<F>,
859         Arc<DefaultRouter<
860                 Arc<NetworkGraph<Arc<L>>>,
861                 Arc<L>,
862                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
863                 ProbabilisticScoringFeeParameters,
864                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
865         >>,
866         Arc<L>
867 >;
868
869 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
870 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
871 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
872 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
873 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
874 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
875 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
876 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
877 /// of [`KeysManager`] and [`DefaultRouter`].
878 ///
879 /// This is not exported to bindings users as type aliases aren't supported in most languages.
880 #[cfg(not(c_bindings))]
881 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
882         ChannelManager<
883                 &'a M,
884                 &'b T,
885                 &'c KeysManager,
886                 &'c KeysManager,
887                 &'c KeysManager,
888                 &'d F,
889                 &'e DefaultRouter<
890                         &'f NetworkGraph<&'g L>,
891                         &'g L,
892                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
893                         ProbabilisticScoringFeeParameters,
894                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
895                 >,
896                 &'g L
897         >;
898
899 /// A trivial trait which describes any [`ChannelManager`].
900 ///
901 /// This is not exported to bindings users as general cover traits aren't useful in other
902 /// languages.
903 pub trait AChannelManager {
904         /// A type implementing [`chain::Watch`].
905         type Watch: chain::Watch<Self::Signer> + ?Sized;
906         /// A type that may be dereferenced to [`Self::Watch`].
907         type M: Deref<Target = Self::Watch>;
908         /// A type implementing [`BroadcasterInterface`].
909         type Broadcaster: BroadcasterInterface + ?Sized;
910         /// A type that may be dereferenced to [`Self::Broadcaster`].
911         type T: Deref<Target = Self::Broadcaster>;
912         /// A type implementing [`EntropySource`].
913         type EntropySource: EntropySource + ?Sized;
914         /// A type that may be dereferenced to [`Self::EntropySource`].
915         type ES: Deref<Target = Self::EntropySource>;
916         /// A type implementing [`NodeSigner`].
917         type NodeSigner: NodeSigner + ?Sized;
918         /// A type that may be dereferenced to [`Self::NodeSigner`].
919         type NS: Deref<Target = Self::NodeSigner>;
920         /// A type implementing [`WriteableEcdsaChannelSigner`].
921         type Signer: WriteableEcdsaChannelSigner + Sized;
922         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
923         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
924         /// A type that may be dereferenced to [`Self::SignerProvider`].
925         type SP: Deref<Target = Self::SignerProvider>;
926         /// A type implementing [`FeeEstimator`].
927         type FeeEstimator: FeeEstimator + ?Sized;
928         /// A type that may be dereferenced to [`Self::FeeEstimator`].
929         type F: Deref<Target = Self::FeeEstimator>;
930         /// A type implementing [`Router`].
931         type Router: Router + ?Sized;
932         /// A type that may be dereferenced to [`Self::Router`].
933         type R: Deref<Target = Self::Router>;
934         /// A type implementing [`Logger`].
935         type Logger: Logger + ?Sized;
936         /// A type that may be dereferenced to [`Self::Logger`].
937         type L: Deref<Target = Self::Logger>;
938         /// Returns a reference to the actual [`ChannelManager`] object.
939         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
940 }
941
942 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
943 for ChannelManager<M, T, ES, NS, SP, F, R, L>
944 where
945         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
946         T::Target: BroadcasterInterface,
947         ES::Target: EntropySource,
948         NS::Target: NodeSigner,
949         SP::Target: SignerProvider,
950         F::Target: FeeEstimator,
951         R::Target: Router,
952         L::Target: Logger,
953 {
954         type Watch = M::Target;
955         type M = M;
956         type Broadcaster = T::Target;
957         type T = T;
958         type EntropySource = ES::Target;
959         type ES = ES;
960         type NodeSigner = NS::Target;
961         type NS = NS;
962         type Signer = <SP::Target as SignerProvider>::Signer;
963         type SignerProvider = SP::Target;
964         type SP = SP;
965         type FeeEstimator = F::Target;
966         type F = F;
967         type Router = R::Target;
968         type R = R;
969         type Logger = L::Target;
970         type L = L;
971         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
972 }
973
974 /// Manager which keeps track of a number of channels and sends messages to the appropriate
975 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
976 ///
977 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
978 /// to individual Channels.
979 ///
980 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
981 /// all peers during write/read (though does not modify this instance, only the instance being
982 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
983 /// called [`funding_transaction_generated`] for outbound channels) being closed.
984 ///
985 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
986 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
987 /// [`ChannelMonitorUpdate`] before returning from
988 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
989 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
990 /// `ChannelManager` operations from occurring during the serialization process). If the
991 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
992 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
993 /// will be lost (modulo on-chain transaction fees).
994 ///
995 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
996 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
997 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
998 ///
999 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
1000 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
1001 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
1002 /// offline for a full minute. In order to track this, you must call
1003 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1004 ///
1005 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1006 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1007 /// not have a channel with being unable to connect to us or open new channels with us if we have
1008 /// many peers with unfunded channels.
1009 ///
1010 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1011 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1012 /// never limited. Please ensure you limit the count of such channels yourself.
1013 ///
1014 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1015 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1016 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1017 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1018 /// you're using lightning-net-tokio.
1019 ///
1020 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1021 /// [`funding_created`]: msgs::FundingCreated
1022 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1023 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1024 /// [`update_channel`]: chain::Watch::update_channel
1025 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1026 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1027 /// [`read`]: ReadableArgs::read
1028 //
1029 // Lock order:
1030 // The tree structure below illustrates the lock order requirements for the different locks of the
1031 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1032 // and should then be taken in the order of the lowest to the highest level in the tree.
1033 // Note that locks on different branches shall not be taken at the same time, as doing so will
1034 // create a new lock order for those specific locks in the order they were taken.
1035 //
1036 // Lock order tree:
1037 //
1038 // `pending_offers_messages`
1039 //
1040 // `total_consistency_lock`
1041 //  |
1042 //  |__`forward_htlcs`
1043 //  |   |
1044 //  |   |__`pending_intercepted_htlcs`
1045 //  |
1046 //  |__`per_peer_state`
1047 //      |
1048 //      |__`pending_inbound_payments`
1049 //          |
1050 //          |__`claimable_payments`
1051 //          |
1052 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1053 //              |
1054 //              |__`peer_state`
1055 //                  |
1056 //                  |__`id_to_peer`
1057 //                  |
1058 //                  |__`short_to_chan_info`
1059 //                  |
1060 //                  |__`outbound_scid_aliases`
1061 //                  |
1062 //                  |__`best_block`
1063 //                  |
1064 //                  |__`pending_events`
1065 //                      |
1066 //                      |__`pending_background_events`
1067 //
1068 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1069 where
1070         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1071         T::Target: BroadcasterInterface,
1072         ES::Target: EntropySource,
1073         NS::Target: NodeSigner,
1074         SP::Target: SignerProvider,
1075         F::Target: FeeEstimator,
1076         R::Target: Router,
1077         L::Target: Logger,
1078 {
1079         default_configuration: UserConfig,
1080         chain_hash: ChainHash,
1081         fee_estimator: LowerBoundedFeeEstimator<F>,
1082         chain_monitor: M,
1083         tx_broadcaster: T,
1084         #[allow(unused)]
1085         router: R,
1086
1087         /// See `ChannelManager` struct-level documentation for lock order requirements.
1088         #[cfg(test)]
1089         pub(super) best_block: RwLock<BestBlock>,
1090         #[cfg(not(test))]
1091         best_block: RwLock<BestBlock>,
1092         secp_ctx: Secp256k1<secp256k1::All>,
1093
1094         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1095         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1096         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1097         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1098         ///
1099         /// See `ChannelManager` struct-level documentation for lock order requirements.
1100         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1101
1102         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1103         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1104         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1105         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1106         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1107         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1108         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1109         /// after reloading from disk while replaying blocks against ChannelMonitors.
1110         ///
1111         /// See `PendingOutboundPayment` documentation for more info.
1112         ///
1113         /// See `ChannelManager` struct-level documentation for lock order requirements.
1114         pending_outbound_payments: OutboundPayments,
1115
1116         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1117         ///
1118         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1119         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1120         /// and via the classic SCID.
1121         ///
1122         /// Note that no consistency guarantees are made about the existence of a channel with the
1123         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1124         ///
1125         /// See `ChannelManager` struct-level documentation for lock order requirements.
1126         #[cfg(test)]
1127         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1128         #[cfg(not(test))]
1129         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1130         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1131         /// until the user tells us what we should do with them.
1132         ///
1133         /// See `ChannelManager` struct-level documentation for lock order requirements.
1134         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1135
1136         /// The sets of payments which are claimable or currently being claimed. See
1137         /// [`ClaimablePayments`]' individual field docs for more info.
1138         ///
1139         /// See `ChannelManager` struct-level documentation for lock order requirements.
1140         claimable_payments: Mutex<ClaimablePayments>,
1141
1142         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1143         /// and some closed channels which reached a usable state prior to being closed. This is used
1144         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1145         /// active channel list on load.
1146         ///
1147         /// See `ChannelManager` struct-level documentation for lock order requirements.
1148         outbound_scid_aliases: Mutex<HashSet<u64>>,
1149
1150         /// `channel_id` -> `counterparty_node_id`.
1151         ///
1152         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1153         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1154         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1155         ///
1156         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1157         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1158         /// the handling of the events.
1159         ///
1160         /// Note that no consistency guarantees are made about the existence of a peer with the
1161         /// `counterparty_node_id` in our other maps.
1162         ///
1163         /// TODO:
1164         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1165         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1166         /// would break backwards compatability.
1167         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1168         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1169         /// required to access the channel with the `counterparty_node_id`.
1170         ///
1171         /// See `ChannelManager` struct-level documentation for lock order requirements.
1172         id_to_peer: Mutex<HashMap<ChannelId, PublicKey>>,
1173
1174         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1175         ///
1176         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1177         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1178         /// confirmation depth.
1179         ///
1180         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1181         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1182         /// channel with the `channel_id` in our other maps.
1183         ///
1184         /// See `ChannelManager` struct-level documentation for lock order requirements.
1185         #[cfg(test)]
1186         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1187         #[cfg(not(test))]
1188         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1189
1190         our_network_pubkey: PublicKey,
1191
1192         inbound_payment_key: inbound_payment::ExpandedKey,
1193
1194         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1195         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1196         /// we encrypt the namespace identifier using these bytes.
1197         ///
1198         /// [fake scids]: crate::util::scid_utils::fake_scid
1199         fake_scid_rand_bytes: [u8; 32],
1200
1201         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1202         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1203         /// keeping additional state.
1204         probing_cookie_secret: [u8; 32],
1205
1206         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1207         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1208         /// very far in the past, and can only ever be up to two hours in the future.
1209         highest_seen_timestamp: AtomicUsize,
1210
1211         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1212         /// basis, as well as the peer's latest features.
1213         ///
1214         /// If we are connected to a peer we always at least have an entry here, even if no channels
1215         /// are currently open with that peer.
1216         ///
1217         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1218         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1219         /// channels.
1220         ///
1221         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1222         ///
1223         /// See `ChannelManager` struct-level documentation for lock order requirements.
1224         #[cfg(not(any(test, feature = "_test_utils")))]
1225         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1226         #[cfg(any(test, feature = "_test_utils"))]
1227         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1228
1229         /// The set of events which we need to give to the user to handle. In some cases an event may
1230         /// require some further action after the user handles it (currently only blocking a monitor
1231         /// update from being handed to the user to ensure the included changes to the channel state
1232         /// are handled by the user before they're persisted durably to disk). In that case, the second
1233         /// element in the tuple is set to `Some` with further details of the action.
1234         ///
1235         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1236         /// could be in the middle of being processed without the direct mutex held.
1237         ///
1238         /// See `ChannelManager` struct-level documentation for lock order requirements.
1239         #[cfg(not(any(test, feature = "_test_utils")))]
1240         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1241         #[cfg(any(test, feature = "_test_utils"))]
1242         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1243
1244         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1245         pending_events_processor: AtomicBool,
1246
1247         /// If we are running during init (either directly during the deserialization method or in
1248         /// block connection methods which run after deserialization but before normal operation) we
1249         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1250         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1251         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1252         ///
1253         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1254         ///
1255         /// See `ChannelManager` struct-level documentation for lock order requirements.
1256         ///
1257         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1258         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1259         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1260         /// Essentially just when we're serializing ourselves out.
1261         /// Taken first everywhere where we are making changes before any other locks.
1262         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1263         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1264         /// Notifier the lock contains sends out a notification when the lock is released.
1265         total_consistency_lock: RwLock<()>,
1266         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1267         /// received and the monitor has been persisted.
1268         ///
1269         /// This information does not need to be persisted as funding nodes can forget
1270         /// unfunded channels upon disconnection.
1271         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1272
1273         background_events_processed_since_startup: AtomicBool,
1274
1275         event_persist_notifier: Notifier,
1276         needs_persist_flag: AtomicBool,
1277
1278         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1279
1280         entropy_source: ES,
1281         node_signer: NS,
1282         signer_provider: SP,
1283
1284         logger: L,
1285 }
1286
1287 /// Chain-related parameters used to construct a new `ChannelManager`.
1288 ///
1289 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1290 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1291 /// are not needed when deserializing a previously constructed `ChannelManager`.
1292 #[derive(Clone, Copy, PartialEq)]
1293 pub struct ChainParameters {
1294         /// The network for determining the `chain_hash` in Lightning messages.
1295         pub network: Network,
1296
1297         /// The hash and height of the latest block successfully connected.
1298         ///
1299         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1300         pub best_block: BestBlock,
1301 }
1302
1303 #[derive(Copy, Clone, PartialEq)]
1304 #[must_use]
1305 enum NotifyOption {
1306         DoPersist,
1307         SkipPersistHandleEvents,
1308         SkipPersistNoEvents,
1309 }
1310
1311 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1312 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1313 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1314 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1315 /// sending the aforementioned notification (since the lock being released indicates that the
1316 /// updates are ready for persistence).
1317 ///
1318 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1319 /// notify or not based on whether relevant changes have been made, providing a closure to
1320 /// `optionally_notify` which returns a `NotifyOption`.
1321 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1322         event_persist_notifier: &'a Notifier,
1323         needs_persist_flag: &'a AtomicBool,
1324         should_persist: F,
1325         // We hold onto this result so the lock doesn't get released immediately.
1326         _read_guard: RwLockReadGuard<'a, ()>,
1327 }
1328
1329 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1330         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1331         /// events to handle.
1332         ///
1333         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1334         /// other cases where losing the changes on restart may result in a force-close or otherwise
1335         /// isn't ideal.
1336         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1337                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1338         }
1339
1340         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1341         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1342                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1343                 let force_notify = cm.get_cm().process_background_events();
1344
1345                 PersistenceNotifierGuard {
1346                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1347                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1348                         should_persist: move || {
1349                                 // Pick the "most" action between `persist_check` and the background events
1350                                 // processing and return that.
1351                                 let notify = persist_check();
1352                                 match (notify, force_notify) {
1353                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1354                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1355                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1356                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1357                                         _ => NotifyOption::SkipPersistNoEvents,
1358                                 }
1359                         },
1360                         _read_guard: read_guard,
1361                 }
1362         }
1363
1364         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1365         /// [`ChannelManager::process_background_events`] MUST be called first (or
1366         /// [`Self::optionally_notify`] used).
1367         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1368         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1369                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1370
1371                 PersistenceNotifierGuard {
1372                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1373                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1374                         should_persist: persist_check,
1375                         _read_guard: read_guard,
1376                 }
1377         }
1378 }
1379
1380 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1381         fn drop(&mut self) {
1382                 match (self.should_persist)() {
1383                         NotifyOption::DoPersist => {
1384                                 self.needs_persist_flag.store(true, Ordering::Release);
1385                                 self.event_persist_notifier.notify()
1386                         },
1387                         NotifyOption::SkipPersistHandleEvents =>
1388                                 self.event_persist_notifier.notify(),
1389                         NotifyOption::SkipPersistNoEvents => {},
1390                 }
1391         }
1392 }
1393
1394 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1395 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1396 ///
1397 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1398 ///
1399 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1400 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1401 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1402 /// the maximum required amount in lnd as of March 2021.
1403 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1404
1405 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1406 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1407 ///
1408 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1409 ///
1410 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1411 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1412 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1413 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1414 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1415 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1416 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1417 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1418 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1419 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1420 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1421 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1422 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1423
1424 /// Minimum CLTV difference between the current block height and received inbound payments.
1425 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1426 /// this value.
1427 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1428 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1429 // a payment was being routed, so we add an extra block to be safe.
1430 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1431
1432 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1433 // ie that if the next-hop peer fails the HTLC within
1434 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1435 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1436 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1437 // LATENCY_GRACE_PERIOD_BLOCKS.
1438 #[deny(const_err)]
1439 #[allow(dead_code)]
1440 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;
1441
1442 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1443 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1444 #[deny(const_err)]
1445 #[allow(dead_code)]
1446 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1447
1448 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1449 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1450
1451 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1452 /// until we mark the channel disabled and gossip the update.
1453 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1454
1455 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1456 /// we mark the channel enabled and gossip the update.
1457 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1458
1459 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1460 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1461 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1462 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1463
1464 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1465 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1466 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1467
1468 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1469 /// many peers we reject new (inbound) connections.
1470 const MAX_NO_CHANNEL_PEERS: usize = 250;
1471
1472 /// Information needed for constructing an invoice route hint for this channel.
1473 #[derive(Clone, Debug, PartialEq)]
1474 pub struct CounterpartyForwardingInfo {
1475         /// Base routing fee in millisatoshis.
1476         pub fee_base_msat: u32,
1477         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1478         pub fee_proportional_millionths: u32,
1479         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1480         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1481         /// `cltv_expiry_delta` for more details.
1482         pub cltv_expiry_delta: u16,
1483 }
1484
1485 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1486 /// to better separate parameters.
1487 #[derive(Clone, Debug, PartialEq)]
1488 pub struct ChannelCounterparty {
1489         /// The node_id of our counterparty
1490         pub node_id: PublicKey,
1491         /// The Features the channel counterparty provided upon last connection.
1492         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1493         /// many routing-relevant features are present in the init context.
1494         pub features: InitFeatures,
1495         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1496         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1497         /// claiming at least this value on chain.
1498         ///
1499         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1500         ///
1501         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1502         pub unspendable_punishment_reserve: u64,
1503         /// Information on the fees and requirements that the counterparty requires when forwarding
1504         /// payments to us through this channel.
1505         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1506         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1507         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1508         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1509         pub outbound_htlc_minimum_msat: Option<u64>,
1510         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1511         pub outbound_htlc_maximum_msat: Option<u64>,
1512 }
1513
1514 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1515 #[derive(Clone, Debug, PartialEq)]
1516 pub struct ChannelDetails {
1517         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1518         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1519         /// Note that this means this value is *not* persistent - it can change once during the
1520         /// lifetime of the channel.
1521         pub channel_id: ChannelId,
1522         /// Parameters which apply to our counterparty. See individual fields for more information.
1523         pub counterparty: ChannelCounterparty,
1524         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1525         /// our counterparty already.
1526         ///
1527         /// Note that, if this has been set, `channel_id` will be equivalent to
1528         /// `funding_txo.unwrap().to_channel_id()`.
1529         pub funding_txo: Option<OutPoint>,
1530         /// The features which this channel operates with. See individual features for more info.
1531         ///
1532         /// `None` until negotiation completes and the channel type is finalized.
1533         pub channel_type: Option<ChannelTypeFeatures>,
1534         /// The position of the funding transaction in the chain. None if the funding transaction has
1535         /// not yet been confirmed and the channel fully opened.
1536         ///
1537         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1538         /// payments instead of this. See [`get_inbound_payment_scid`].
1539         ///
1540         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1541         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1542         ///
1543         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1544         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1545         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1546         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1547         /// [`confirmations_required`]: Self::confirmations_required
1548         pub short_channel_id: Option<u64>,
1549         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1550         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1551         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1552         /// `Some(0)`).
1553         ///
1554         /// This will be `None` as long as the channel is not available for routing outbound payments.
1555         ///
1556         /// [`short_channel_id`]: Self::short_channel_id
1557         /// [`confirmations_required`]: Self::confirmations_required
1558         pub outbound_scid_alias: Option<u64>,
1559         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1560         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1561         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1562         /// when they see a payment to be routed to us.
1563         ///
1564         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1565         /// previous values for inbound payment forwarding.
1566         ///
1567         /// [`short_channel_id`]: Self::short_channel_id
1568         pub inbound_scid_alias: Option<u64>,
1569         /// The value, in satoshis, of this channel as appears in the funding output
1570         pub channel_value_satoshis: u64,
1571         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1572         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1573         /// this value on chain.
1574         ///
1575         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1576         ///
1577         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1578         ///
1579         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1580         pub unspendable_punishment_reserve: Option<u64>,
1581         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1582         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1583         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1584         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1585         /// serialized with LDK versions prior to 0.0.113.
1586         ///
1587         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1588         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1589         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1590         pub user_channel_id: u128,
1591         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1592         /// which is applied to commitment and HTLC transactions.
1593         ///
1594         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1595         pub feerate_sat_per_1000_weight: Option<u32>,
1596         /// Our total balance.  This is the amount we would get if we close the channel.
1597         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1598         /// amount is not likely to be recoverable on close.
1599         ///
1600         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1601         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1602         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1603         /// This does not consider any on-chain fees.
1604         ///
1605         /// See also [`ChannelDetails::outbound_capacity_msat`]
1606         pub balance_msat: u64,
1607         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1608         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1609         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1610         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1611         ///
1612         /// See also [`ChannelDetails::balance_msat`]
1613         ///
1614         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1615         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1616         /// should be able to spend nearly this amount.
1617         pub outbound_capacity_msat: u64,
1618         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1619         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1620         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1621         /// to use a limit as close as possible to the HTLC limit we can currently send.
1622         ///
1623         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1624         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1625         pub next_outbound_htlc_limit_msat: u64,
1626         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1627         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1628         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1629         /// route which is valid.
1630         pub next_outbound_htlc_minimum_msat: u64,
1631         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1632         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1633         /// available for inclusion in new inbound HTLCs).
1634         /// Note that there are some corner cases not fully handled here, so the actual available
1635         /// inbound capacity may be slightly higher than this.
1636         ///
1637         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1638         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1639         /// However, our counterparty should be able to spend nearly this amount.
1640         pub inbound_capacity_msat: u64,
1641         /// The number of required confirmations on the funding transaction before the funding will be
1642         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1643         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1644         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1645         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1646         ///
1647         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1648         ///
1649         /// [`is_outbound`]: ChannelDetails::is_outbound
1650         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1651         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1652         pub confirmations_required: Option<u32>,
1653         /// The current number of confirmations on the funding transaction.
1654         ///
1655         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1656         pub confirmations: Option<u32>,
1657         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1658         /// until we can claim our funds after we force-close the channel. During this time our
1659         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1660         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1661         /// time to claim our non-HTLC-encumbered funds.
1662         ///
1663         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1664         pub force_close_spend_delay: Option<u16>,
1665         /// True if the channel was initiated (and thus funded) by us.
1666         pub is_outbound: bool,
1667         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1668         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1669         /// required confirmation count has been reached (and we were connected to the peer at some
1670         /// point after the funding transaction received enough confirmations). The required
1671         /// confirmation count is provided in [`confirmations_required`].
1672         ///
1673         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1674         pub is_channel_ready: bool,
1675         /// The stage of the channel's shutdown.
1676         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1677         pub channel_shutdown_state: Option<ChannelShutdownState>,
1678         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1679         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1680         ///
1681         /// This is a strict superset of `is_channel_ready`.
1682         pub is_usable: bool,
1683         /// True if this channel is (or will be) publicly-announced.
1684         pub is_public: bool,
1685         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1686         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1687         pub inbound_htlc_minimum_msat: Option<u64>,
1688         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1689         pub inbound_htlc_maximum_msat: Option<u64>,
1690         /// Set of configurable parameters that affect channel operation.
1691         ///
1692         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1693         pub config: Option<ChannelConfig>,
1694 }
1695
1696 impl ChannelDetails {
1697         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1698         /// This should be used for providing invoice hints or in any other context where our
1699         /// counterparty will forward a payment to us.
1700         ///
1701         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1702         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1703         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1704                 self.inbound_scid_alias.or(self.short_channel_id)
1705         }
1706
1707         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1708         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1709         /// we're sending or forwarding a payment outbound over this channel.
1710         ///
1711         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1712         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1713         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1714                 self.short_channel_id.or(self.outbound_scid_alias)
1715         }
1716
1717         fn from_channel_context<SP: Deref, F: Deref>(
1718                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1719                 fee_estimator: &LowerBoundedFeeEstimator<F>
1720         ) -> Self
1721         where
1722                 SP::Target: SignerProvider,
1723                 F::Target: FeeEstimator
1724         {
1725                 let balance = context.get_available_balances(fee_estimator);
1726                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1727                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1728                 ChannelDetails {
1729                         channel_id: context.channel_id(),
1730                         counterparty: ChannelCounterparty {
1731                                 node_id: context.get_counterparty_node_id(),
1732                                 features: latest_features,
1733                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1734                                 forwarding_info: context.counterparty_forwarding_info(),
1735                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1736                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1737                                 // message (as they are always the first message from the counterparty).
1738                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1739                                 // default `0` value set by `Channel::new_outbound`.
1740                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1741                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1742                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1743                         },
1744                         funding_txo: context.get_funding_txo(),
1745                         // Note that accept_channel (or open_channel) is always the first message, so
1746                         // `have_received_message` indicates that type negotiation has completed.
1747                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1748                         short_channel_id: context.get_short_channel_id(),
1749                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1750                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1751                         channel_value_satoshis: context.get_value_satoshis(),
1752                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1753                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1754                         balance_msat: balance.balance_msat,
1755                         inbound_capacity_msat: balance.inbound_capacity_msat,
1756                         outbound_capacity_msat: balance.outbound_capacity_msat,
1757                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1758                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1759                         user_channel_id: context.get_user_id(),
1760                         confirmations_required: context.minimum_depth(),
1761                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1762                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1763                         is_outbound: context.is_outbound(),
1764                         is_channel_ready: context.is_usable(),
1765                         is_usable: context.is_live(),
1766                         is_public: context.should_announce(),
1767                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1768                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1769                         config: Some(context.config()),
1770                         channel_shutdown_state: Some(context.shutdown_state()),
1771                 }
1772         }
1773 }
1774
1775 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1776 /// Further information on the details of the channel shutdown.
1777 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1778 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1779 /// the channel will be removed shortly.
1780 /// Also note, that in normal operation, peers could disconnect at any of these states
1781 /// and require peer re-connection before making progress onto other states
1782 pub enum ChannelShutdownState {
1783         /// Channel has not sent or received a shutdown message.
1784         NotShuttingDown,
1785         /// Local node has sent a shutdown message for this channel.
1786         ShutdownInitiated,
1787         /// Shutdown message exchanges have concluded and the channels are in the midst of
1788         /// resolving all existing open HTLCs before closing can continue.
1789         ResolvingHTLCs,
1790         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1791         NegotiatingClosingFee,
1792         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1793         /// to drop the channel.
1794         ShutdownComplete,
1795 }
1796
1797 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1798 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1799 #[derive(Debug, PartialEq)]
1800 pub enum RecentPaymentDetails {
1801         /// When an invoice was requested and thus a payment has not yet been sent.
1802         AwaitingInvoice {
1803                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1804                 /// a payment and ensure idempotency in LDK.
1805                 payment_id: PaymentId,
1806         },
1807         /// When a payment is still being sent and awaiting successful delivery.
1808         Pending {
1809                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1810                 /// a payment and ensure idempotency in LDK.
1811                 payment_id: PaymentId,
1812                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1813                 /// abandoned.
1814                 payment_hash: PaymentHash,
1815                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1816                 /// not just the amount currently inflight.
1817                 total_msat: u64,
1818         },
1819         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1820         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1821         /// payment is removed from tracking.
1822         Fulfilled {
1823                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1824                 /// a payment and ensure idempotency in LDK.
1825                 payment_id: PaymentId,
1826                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1827                 /// made before LDK version 0.0.104.
1828                 payment_hash: Option<PaymentHash>,
1829         },
1830         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1831         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1832         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1833         Abandoned {
1834                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1835                 /// a payment and ensure idempotency in LDK.
1836                 payment_id: PaymentId,
1837                 /// Hash of the payment that we have given up trying to send.
1838                 payment_hash: PaymentHash,
1839         },
1840 }
1841
1842 /// Route hints used in constructing invoices for [phantom node payents].
1843 ///
1844 /// [phantom node payments]: crate::sign::PhantomKeysManager
1845 #[derive(Clone)]
1846 pub struct PhantomRouteHints {
1847         /// The list of channels to be included in the invoice route hints.
1848         pub channels: Vec<ChannelDetails>,
1849         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1850         /// route hints.
1851         pub phantom_scid: u64,
1852         /// The pubkey of the real backing node that would ultimately receive the payment.
1853         pub real_node_pubkey: PublicKey,
1854 }
1855
1856 macro_rules! handle_error {
1857         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1858                 // In testing, ensure there are no deadlocks where the lock is already held upon
1859                 // entering the macro.
1860                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1861                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1862
1863                 match $internal {
1864                         Ok(msg) => Ok(msg),
1865                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1866                                 let mut msg_events = Vec::with_capacity(2);
1867
1868                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1869                                         $self.finish_close_channel(shutdown_res);
1870                                         if let Some(update) = update_option {
1871                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1872                                                         msg: update
1873                                                 });
1874                                         }
1875                                         if let Some((channel_id, user_channel_id)) = chan_id {
1876                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1877                                                         channel_id, user_channel_id,
1878                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1879                                                         counterparty_node_id: Some($counterparty_node_id),
1880                                                         channel_capacity_sats: channel_capacity,
1881                                                 }, None));
1882                                         }
1883                                 }
1884
1885                                 log_error!($self.logger, "{}", err.err);
1886                                 if let msgs::ErrorAction::IgnoreError = err.action {
1887                                 } else {
1888                                         msg_events.push(events::MessageSendEvent::HandleError {
1889                                                 node_id: $counterparty_node_id,
1890                                                 action: err.action.clone()
1891                                         });
1892                                 }
1893
1894                                 if !msg_events.is_empty() {
1895                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1896                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1897                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1898                                                 peer_state.pending_msg_events.append(&mut msg_events);
1899                                         }
1900                                 }
1901
1902                                 // Return error in case higher-API need one
1903                                 Err(err)
1904                         },
1905                 }
1906         } };
1907         ($self: ident, $internal: expr) => {
1908                 match $internal {
1909                         Ok(res) => Ok(res),
1910                         Err((chan, msg_handle_err)) => {
1911                                 let counterparty_node_id = chan.get_counterparty_node_id();
1912                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1913                         },
1914                 }
1915         };
1916 }
1917
1918 macro_rules! update_maps_on_chan_removal {
1919         ($self: expr, $channel_context: expr) => {{
1920                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1921                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1922                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1923                         short_to_chan_info.remove(&short_id);
1924                 } else {
1925                         // If the channel was never confirmed on-chain prior to its closure, remove the
1926                         // outbound SCID alias we used for it from the collision-prevention set. While we
1927                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1928                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1929                         // opening a million channels with us which are closed before we ever reach the funding
1930                         // stage.
1931                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1932                         debug_assert!(alias_removed);
1933                 }
1934                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1935         }}
1936 }
1937
1938 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1939 macro_rules! convert_chan_phase_err {
1940         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
1941                 match $err {
1942                         ChannelError::Warn(msg) => {
1943                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
1944                         },
1945                         ChannelError::Ignore(msg) => {
1946                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
1947                         },
1948                         ChannelError::Close(msg) => {
1949                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
1950                                 update_maps_on_chan_removal!($self, $channel.context);
1951                                 let shutdown_res = $channel.context.force_shutdown(true);
1952                                 let user_id = $channel.context.get_user_id();
1953                                 let channel_capacity_satoshis = $channel.context.get_value_satoshis();
1954
1955                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, user_id,
1956                                         shutdown_res, $channel_update, channel_capacity_satoshis))
1957                         },
1958                 }
1959         };
1960         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
1961                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
1962         };
1963         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
1964                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
1965         };
1966         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
1967                 match $channel_phase {
1968                         ChannelPhase::Funded(channel) => {
1969                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
1970                         },
1971                         ChannelPhase::UnfundedOutboundV1(channel) => {
1972                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1973                         },
1974                         ChannelPhase::UnfundedInboundV1(channel) => {
1975                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1976                         },
1977                 }
1978         };
1979 }
1980
1981 macro_rules! break_chan_phase_entry {
1982         ($self: ident, $res: expr, $entry: expr) => {
1983                 match $res {
1984                         Ok(res) => res,
1985                         Err(e) => {
1986                                 let key = *$entry.key();
1987                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1988                                 if drop {
1989                                         $entry.remove_entry();
1990                                 }
1991                                 break Err(res);
1992                         }
1993                 }
1994         }
1995 }
1996
1997 macro_rules! try_chan_phase_entry {
1998         ($self: ident, $res: expr, $entry: expr) => {
1999                 match $res {
2000                         Ok(res) => res,
2001                         Err(e) => {
2002                                 let key = *$entry.key();
2003                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2004                                 if drop {
2005                                         $entry.remove_entry();
2006                                 }
2007                                 return Err(res);
2008                         }
2009                 }
2010         }
2011 }
2012
2013 macro_rules! remove_channel_phase {
2014         ($self: expr, $entry: expr) => {
2015                 {
2016                         let channel = $entry.remove_entry().1;
2017                         update_maps_on_chan_removal!($self, &channel.context());
2018                         channel
2019                 }
2020         }
2021 }
2022
2023 macro_rules! send_channel_ready {
2024         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2025                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2026                         node_id: $channel.context.get_counterparty_node_id(),
2027                         msg: $channel_ready_msg,
2028                 });
2029                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2030                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2031                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2032                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2033                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2034                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2035                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2036                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2037                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2038                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2039                 }
2040         }}
2041 }
2042
2043 macro_rules! emit_channel_pending_event {
2044         ($locked_events: expr, $channel: expr) => {
2045                 if $channel.context.should_emit_channel_pending_event() {
2046                         $locked_events.push_back((events::Event::ChannelPending {
2047                                 channel_id: $channel.context.channel_id(),
2048                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2049                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2050                                 user_channel_id: $channel.context.get_user_id(),
2051                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2052                         }, None));
2053                         $channel.context.set_channel_pending_event_emitted();
2054                 }
2055         }
2056 }
2057
2058 macro_rules! emit_channel_ready_event {
2059         ($locked_events: expr, $channel: expr) => {
2060                 if $channel.context.should_emit_channel_ready_event() {
2061                         debug_assert!($channel.context.channel_pending_event_emitted());
2062                         $locked_events.push_back((events::Event::ChannelReady {
2063                                 channel_id: $channel.context.channel_id(),
2064                                 user_channel_id: $channel.context.get_user_id(),
2065                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2066                                 channel_type: $channel.context.get_channel_type().clone(),
2067                         }, None));
2068                         $channel.context.set_channel_ready_event_emitted();
2069                 }
2070         }
2071 }
2072
2073 macro_rules! handle_monitor_update_completion {
2074         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2075                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
2076                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2077                         $self.best_block.read().unwrap().height());
2078                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2079                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2080                         // We only send a channel_update in the case where we are just now sending a
2081                         // channel_ready and the channel is in a usable state. We may re-send a
2082                         // channel_update later through the announcement_signatures process for public
2083                         // channels, but there's no reason not to just inform our counterparty of our fees
2084                         // now.
2085                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2086                                 Some(events::MessageSendEvent::SendChannelUpdate {
2087                                         node_id: counterparty_node_id,
2088                                         msg,
2089                                 })
2090                         } else { None }
2091                 } else { None };
2092
2093                 let update_actions = $peer_state.monitor_update_blocked_actions
2094                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2095
2096                 let htlc_forwards = $self.handle_channel_resumption(
2097                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2098                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2099                         updates.funding_broadcastable, updates.channel_ready,
2100                         updates.announcement_sigs);
2101                 if let Some(upd) = channel_update {
2102                         $peer_state.pending_msg_events.push(upd);
2103                 }
2104
2105                 let channel_id = $chan.context.channel_id();
2106                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2107                 core::mem::drop($peer_state_lock);
2108                 core::mem::drop($per_peer_state_lock);
2109
2110                 // If the channel belongs to a batch funding transaction, the progress of the batch
2111                 // should be updated as we have received funding_signed and persisted the monitor.
2112                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2113                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2114                         let mut batch_completed = false;
2115                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2116                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2117                                         *chan_id == channel_id &&
2118                                         *pubkey == counterparty_node_id
2119                                 ));
2120                                 if let Some(channel_state) = channel_state {
2121                                         channel_state.2 = true;
2122                                 } else {
2123                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2124                                 }
2125                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2126                         } else {
2127                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2128                         }
2129
2130                         // When all channels in a batched funding transaction have become ready, it is not necessary
2131                         // to track the progress of the batch anymore and the state of the channels can be updated.
2132                         if batch_completed {
2133                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2134                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2135                                 let mut batch_funding_tx = None;
2136                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2137                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2138                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2139                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2140                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2141                                                         chan.set_batch_ready();
2142                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2143                                                         emit_channel_pending_event!(pending_events, chan);
2144                                                 }
2145                                         }
2146                                 }
2147                                 if let Some(tx) = batch_funding_tx {
2148                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2149                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2150                                 }
2151                         }
2152                 }
2153
2154                 $self.handle_monitor_update_completion_actions(update_actions);
2155
2156                 if let Some(forwards) = htlc_forwards {
2157                         $self.forward_htlcs(&mut [forwards][..]);
2158                 }
2159                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2160                 for failure in updates.failed_htlcs.drain(..) {
2161                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2162                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2163                 }
2164         } }
2165 }
2166
2167 macro_rules! handle_new_monitor_update {
2168         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2169                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2170                 match $update_res {
2171                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2172                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2173                                 log_error!($self.logger, "{}", err_str);
2174                                 panic!("{}", err_str);
2175                         },
2176                         ChannelMonitorUpdateStatus::InProgress => {
2177                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2178                                         &$chan.context.channel_id());
2179                                 false
2180                         },
2181                         ChannelMonitorUpdateStatus::Completed => {
2182                                 $completed;
2183                                 true
2184                         },
2185                 }
2186         } };
2187         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2188                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2189                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2190         };
2191         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2192                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2193                         .or_insert_with(Vec::new);
2194                 // During startup, we push monitor updates as background events through to here in
2195                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2196                 // filter for uniqueness here.
2197                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2198                         .unwrap_or_else(|| {
2199                                 in_flight_updates.push($update);
2200                                 in_flight_updates.len() - 1
2201                         });
2202                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2203                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2204                         {
2205                                 let _ = in_flight_updates.remove(idx);
2206                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2207                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2208                                 }
2209                         })
2210         } };
2211 }
2212
2213 macro_rules! process_events_body {
2214         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2215                 let mut processed_all_events = false;
2216                 while !processed_all_events {
2217                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2218                                 return;
2219                         }
2220
2221                         let mut result;
2222
2223                         {
2224                                 // We'll acquire our total consistency lock so that we can be sure no other
2225                                 // persists happen while processing monitor events.
2226                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2227
2228                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2229                                 // ensure any startup-generated background events are handled first.
2230                                 result = $self.process_background_events();
2231
2232                                 // TODO: This behavior should be documented. It's unintuitive that we query
2233                                 // ChannelMonitors when clearing other events.
2234                                 if $self.process_pending_monitor_events() {
2235                                         result = NotifyOption::DoPersist;
2236                                 }
2237                         }
2238
2239                         let pending_events = $self.pending_events.lock().unwrap().clone();
2240                         let num_events = pending_events.len();
2241                         if !pending_events.is_empty() {
2242                                 result = NotifyOption::DoPersist;
2243                         }
2244
2245                         let mut post_event_actions = Vec::new();
2246
2247                         for (event, action_opt) in pending_events {
2248                                 $event_to_handle = event;
2249                                 $handle_event;
2250                                 if let Some(action) = action_opt {
2251                                         post_event_actions.push(action);
2252                                 }
2253                         }
2254
2255                         {
2256                                 let mut pending_events = $self.pending_events.lock().unwrap();
2257                                 pending_events.drain(..num_events);
2258                                 processed_all_events = pending_events.is_empty();
2259                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2260                                 // updated here with the `pending_events` lock acquired.
2261                                 $self.pending_events_processor.store(false, Ordering::Release);
2262                         }
2263
2264                         if !post_event_actions.is_empty() {
2265                                 $self.handle_post_event_actions(post_event_actions);
2266                                 // If we had some actions, go around again as we may have more events now
2267                                 processed_all_events = false;
2268                         }
2269
2270                         match result {
2271                                 NotifyOption::DoPersist => {
2272                                         $self.needs_persist_flag.store(true, Ordering::Release);
2273                                         $self.event_persist_notifier.notify();
2274                                 },
2275                                 NotifyOption::SkipPersistHandleEvents =>
2276                                         $self.event_persist_notifier.notify(),
2277                                 NotifyOption::SkipPersistNoEvents => {},
2278                         }
2279                 }
2280         }
2281 }
2282
2283 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>
2284 where
2285         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2286         T::Target: BroadcasterInterface,
2287         ES::Target: EntropySource,
2288         NS::Target: NodeSigner,
2289         SP::Target: SignerProvider,
2290         F::Target: FeeEstimator,
2291         R::Target: Router,
2292         L::Target: Logger,
2293 {
2294         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2295         ///
2296         /// The current time or latest block header time can be provided as the `current_timestamp`.
2297         ///
2298         /// This is the main "logic hub" for all channel-related actions, and implements
2299         /// [`ChannelMessageHandler`].
2300         ///
2301         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2302         ///
2303         /// Users need to notify the new `ChannelManager` when a new block is connected or
2304         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2305         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2306         /// more details.
2307         ///
2308         /// [`block_connected`]: chain::Listen::block_connected
2309         /// [`block_disconnected`]: chain::Listen::block_disconnected
2310         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2311         pub fn new(
2312                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2313                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2314                 current_timestamp: u32,
2315         ) -> Self {
2316                 let mut secp_ctx = Secp256k1::new();
2317                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2318                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2319                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2320                 ChannelManager {
2321                         default_configuration: config.clone(),
2322                         chain_hash: ChainHash::using_genesis_block(params.network),
2323                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2324                         chain_monitor,
2325                         tx_broadcaster,
2326                         router,
2327
2328                         best_block: RwLock::new(params.best_block),
2329
2330                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2331                         pending_inbound_payments: Mutex::new(HashMap::new()),
2332                         pending_outbound_payments: OutboundPayments::new(),
2333                         forward_htlcs: Mutex::new(HashMap::new()),
2334                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2335                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2336                         id_to_peer: Mutex::new(HashMap::new()),
2337                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2338
2339                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2340                         secp_ctx,
2341
2342                         inbound_payment_key: expanded_inbound_key,
2343                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2344
2345                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2346
2347                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2348
2349                         per_peer_state: FairRwLock::new(HashMap::new()),
2350
2351                         pending_events: Mutex::new(VecDeque::new()),
2352                         pending_events_processor: AtomicBool::new(false),
2353                         pending_background_events: Mutex::new(Vec::new()),
2354                         total_consistency_lock: RwLock::new(()),
2355                         background_events_processed_since_startup: AtomicBool::new(false),
2356                         event_persist_notifier: Notifier::new(),
2357                         needs_persist_flag: AtomicBool::new(false),
2358                         funding_batch_states: Mutex::new(BTreeMap::new()),
2359
2360                         pending_offers_messages: Mutex::new(Vec::new()),
2361
2362                         entropy_source,
2363                         node_signer,
2364                         signer_provider,
2365
2366                         logger,
2367                 }
2368         }
2369
2370         /// Gets the current configuration applied to all new channels.
2371         pub fn get_current_default_configuration(&self) -> &UserConfig {
2372                 &self.default_configuration
2373         }
2374
2375         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2376                 let height = self.best_block.read().unwrap().height();
2377                 let mut outbound_scid_alias = 0;
2378                 let mut i = 0;
2379                 loop {
2380                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2381                                 outbound_scid_alias += 1;
2382                         } else {
2383                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2384                         }
2385                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2386                                 break;
2387                         }
2388                         i += 1;
2389                         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"); }
2390                 }
2391                 outbound_scid_alias
2392         }
2393
2394         /// Creates a new outbound channel to the given remote node and with the given value.
2395         ///
2396         /// `user_channel_id` will be provided back as in
2397         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2398         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2399         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2400         /// is simply copied to events and otherwise ignored.
2401         ///
2402         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2403         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2404         ///
2405         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2406         /// generate a shutdown scriptpubkey or destination script set by
2407         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2408         ///
2409         /// Note that we do not check if you are currently connected to the given peer. If no
2410         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2411         /// the channel eventually being silently forgotten (dropped on reload).
2412         ///
2413         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2414         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2415         /// [`ChannelDetails::channel_id`] until after
2416         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2417         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2418         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2419         ///
2420         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2421         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2422         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2423         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> {
2424                 if channel_value_satoshis < 1000 {
2425                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2426                 }
2427
2428                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2429                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2430                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2431
2432                 let per_peer_state = self.per_peer_state.read().unwrap();
2433
2434                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2435                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2436
2437                 let mut peer_state = peer_state_mutex.lock().unwrap();
2438                 let channel = {
2439                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2440                         let their_features = &peer_state.latest_features;
2441                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2442                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2443                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2444                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2445                         {
2446                                 Ok(res) => res,
2447                                 Err(e) => {
2448                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2449                                         return Err(e);
2450                                 },
2451                         }
2452                 };
2453                 let res = channel.get_open_channel(self.chain_hash);
2454
2455                 let temporary_channel_id = channel.context.channel_id();
2456                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2457                         hash_map::Entry::Occupied(_) => {
2458                                 if cfg!(fuzzing) {
2459                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2460                                 } else {
2461                                         panic!("RNG is bad???");
2462                                 }
2463                         },
2464                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2465                 }
2466
2467                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2468                         node_id: their_network_key,
2469                         msg: res,
2470                 });
2471                 Ok(temporary_channel_id)
2472         }
2473
2474         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2475                 // Allocate our best estimate of the number of channels we have in the `res`
2476                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2477                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2478                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2479                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2480                 // the same channel.
2481                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2482                 {
2483                         let best_block_height = self.best_block.read().unwrap().height();
2484                         let per_peer_state = self.per_peer_state.read().unwrap();
2485                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2486                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2487                                 let peer_state = &mut *peer_state_lock;
2488                                 res.extend(peer_state.channel_by_id.iter()
2489                                         .filter_map(|(chan_id, phase)| match phase {
2490                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2491                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2492                                                 _ => None,
2493                                         })
2494                                         .filter(f)
2495                                         .map(|(_channel_id, channel)| {
2496                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2497                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2498                                         })
2499                                 );
2500                         }
2501                 }
2502                 res
2503         }
2504
2505         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2506         /// more information.
2507         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2508                 // Allocate our best estimate of the number of channels we have in the `res`
2509                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2510                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2511                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2512                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2513                 // the same channel.
2514                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2515                 {
2516                         let best_block_height = self.best_block.read().unwrap().height();
2517                         let per_peer_state = self.per_peer_state.read().unwrap();
2518                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2519                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2520                                 let peer_state = &mut *peer_state_lock;
2521                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2522                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2523                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2524                                         res.push(details);
2525                                 }
2526                         }
2527                 }
2528                 res
2529         }
2530
2531         /// Gets the list of usable channels, in random order. Useful as an argument to
2532         /// [`Router::find_route`] to ensure non-announced channels are used.
2533         ///
2534         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2535         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2536         /// are.
2537         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2538                 // Note we use is_live here instead of usable which leads to somewhat confused
2539                 // internal/external nomenclature, but that's ok cause that's probably what the user
2540                 // really wanted anyway.
2541                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2542         }
2543
2544         /// Gets the list of channels we have with a given counterparty, in random order.
2545         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2546                 let best_block_height = self.best_block.read().unwrap().height();
2547                 let per_peer_state = self.per_peer_state.read().unwrap();
2548
2549                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2550                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2551                         let peer_state = &mut *peer_state_lock;
2552                         let features = &peer_state.latest_features;
2553                         let context_to_details = |context| {
2554                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2555                         };
2556                         return peer_state.channel_by_id
2557                                 .iter()
2558                                 .map(|(_, phase)| phase.context())
2559                                 .map(context_to_details)
2560                                 .collect();
2561                 }
2562                 vec![]
2563         }
2564
2565         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2566         /// successful path, or have unresolved HTLCs.
2567         ///
2568         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2569         /// result of a crash. If such a payment exists, is not listed here, and an
2570         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2571         ///
2572         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2573         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2574                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2575                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2576                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2577                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2578                                 },
2579                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2580                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2581                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2582                                 },
2583                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2584                                         Some(RecentPaymentDetails::Pending {
2585                                                 payment_id: *payment_id,
2586                                                 payment_hash: *payment_hash,
2587                                                 total_msat: *total_msat,
2588                                         })
2589                                 },
2590                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2591                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2592                                 },
2593                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2594                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2595                                 },
2596                                 PendingOutboundPayment::Legacy { .. } => None
2597                         })
2598                         .collect()
2599         }
2600
2601         /// Helper function that issues the channel close events
2602         fn issue_channel_close_events(&self, context: &ChannelContext<SP>, closure_reason: ClosureReason) {
2603                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2604                 match context.unbroadcasted_funding() {
2605                         Some(transaction) => {
2606                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2607                                         channel_id: context.channel_id(), transaction
2608                                 }, None));
2609                         },
2610                         None => {},
2611                 }
2612                 pending_events_lock.push_back((events::Event::ChannelClosed {
2613                         channel_id: context.channel_id(),
2614                         user_channel_id: context.get_user_id(),
2615                         reason: closure_reason,
2616                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2617                         channel_capacity_sats: Some(context.get_value_satoshis()),
2618                 }, None));
2619         }
2620
2621         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> {
2622                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2623
2624                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2625                 let shutdown_result;
2626                 loop {
2627                         let per_peer_state = self.per_peer_state.read().unwrap();
2628
2629                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2630                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2631
2632                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2633                         let peer_state = &mut *peer_state_lock;
2634
2635                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2636                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2637                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2638                                                 let funding_txo_opt = chan.context.get_funding_txo();
2639                                                 let their_features = &peer_state.latest_features;
2640                                                 let (shutdown_msg, mut monitor_update_opt, htlcs, local_shutdown_result) =
2641                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2642                                                 failed_htlcs = htlcs;
2643                                                 shutdown_result = local_shutdown_result;
2644                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
2645
2646                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2647                                                 // here as we don't need the monitor update to complete until we send a
2648                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2649                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2650                                                         node_id: *counterparty_node_id,
2651                                                         msg: shutdown_msg,
2652                                                 });
2653
2654                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2655                                                         "We can't both complete shutdown and generate a monitor update");
2656
2657                                                 // Update the monitor with the shutdown script if necessary.
2658                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2659                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2660                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2661                                                         break;
2662                                                 }
2663
2664                                                 if chan.is_shutdown() {
2665                                                         if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2666                                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2667                                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2668                                                                                 msg: channel_update
2669                                                                         });
2670                                                                 }
2671                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2672                                                         }
2673                                                 }
2674                                                 break;
2675                                         }
2676                                 },
2677                                 hash_map::Entry::Vacant(_) => {
2678                                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2679                                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2680                                         //
2681                                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2682                                         mem::drop(peer_state_lock);
2683                                         mem::drop(per_peer_state);
2684                                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2685                                 },
2686                         }
2687                 }
2688
2689                 for htlc_source in failed_htlcs.drain(..) {
2690                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2691                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2692                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2693                 }
2694
2695                 if let Some(shutdown_result) = shutdown_result {
2696                         self.finish_close_channel(shutdown_result);
2697                 }
2698
2699                 Ok(())
2700         }
2701
2702         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2703         /// will be accepted on the given channel, and after additional timeout/the closing of all
2704         /// pending HTLCs, the channel will be closed on chain.
2705         ///
2706         ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2707         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2708         ///    fee estimate.
2709         ///  * If our counterparty is the channel initiator, we will require a channel closing
2710         ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2711         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2712         ///    counterparty to pay as much fee as they'd like, however.
2713         ///
2714         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2715         ///
2716         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2717         /// generate a shutdown scriptpubkey or destination script set by
2718         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2719         /// channel.
2720         ///
2721         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2722         /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2723         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2724         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2725         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2726                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2727         }
2728
2729         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2730         /// will be accepted on the given channel, and after additional timeout/the closing of all
2731         /// pending HTLCs, the channel will be closed on chain.
2732         ///
2733         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2734         /// the channel being closed or not:
2735         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2736         ///    transaction. The upper-bound is set by
2737         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2738         ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2739         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2740         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2741         ///    will appear on a force-closure transaction, whichever is lower).
2742         ///
2743         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2744         /// Will fail if a shutdown script has already been set for this channel by
2745         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2746         /// also be compatible with our and the counterparty's features.
2747         ///
2748         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2749         ///
2750         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2751         /// generate a shutdown scriptpubkey or destination script set by
2752         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2753         /// channel.
2754         ///
2755         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2756         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2757         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2758         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> {
2759                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2760         }
2761
2762         fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) {
2763                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2764                 #[cfg(debug_assertions)]
2765                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2766                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2767                 }
2768
2769                 log_debug!(self.logger, "Finishing closure of channel with {} HTLCs to fail", shutdown_res.dropped_outbound_htlcs.len());
2770                 for htlc_source in shutdown_res.dropped_outbound_htlcs.drain(..) {
2771                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2772                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2773                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2774                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2775                 }
2776                 if let Some((_, funding_txo, monitor_update)) = shutdown_res.monitor_update {
2777                         // There isn't anything we can do if we get an update failure - we're already
2778                         // force-closing. The monitor update on the required in-memory copy should broadcast
2779                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2780                         // ignore the result here.
2781                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2782                 }
2783                 let mut shutdown_results = Vec::new();
2784                 if let Some(txid) = shutdown_res.unbroadcasted_batch_funding_txid {
2785                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2786                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2787                         let per_peer_state = self.per_peer_state.read().unwrap();
2788                         let mut has_uncompleted_channel = None;
2789                         for (channel_id, counterparty_node_id, state) in affected_channels {
2790                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2791                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2792                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2793                                                 update_maps_on_chan_removal!(self, &chan.context());
2794                                                 self.issue_channel_close_events(&chan.context(), ClosureReason::FundingBatchClosure);
2795                                                 shutdown_results.push(chan.context_mut().force_shutdown(false));
2796                                         }
2797                                 }
2798                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2799                         }
2800                         debug_assert!(
2801                                 has_uncompleted_channel.unwrap_or(true),
2802                                 "Closing a batch where all channels have completed initial monitor update",
2803                         );
2804                 }
2805                 for shutdown_result in shutdown_results.drain(..) {
2806                         self.finish_close_channel(shutdown_result);
2807                 }
2808         }
2809
2810         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2811         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2812         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2813         -> Result<PublicKey, APIError> {
2814                 let per_peer_state = self.per_peer_state.read().unwrap();
2815                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2816                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2817                 let (update_opt, counterparty_node_id) = {
2818                         let mut peer_state = peer_state_mutex.lock().unwrap();
2819                         let closure_reason = if let Some(peer_msg) = peer_msg {
2820                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2821                         } else {
2822                                 ClosureReason::HolderForceClosed
2823                         };
2824                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2825                                 log_error!(self.logger, "Force-closing channel {}", channel_id);
2826                                 self.issue_channel_close_events(&chan_phase_entry.get().context(), closure_reason);
2827                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2828                                 mem::drop(peer_state);
2829                                 mem::drop(per_peer_state);
2830                                 match chan_phase {
2831                                         ChannelPhase::Funded(mut chan) => {
2832                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast));
2833                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2834                                         },
2835                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2836                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false));
2837                                                 // Unfunded channel has no update
2838                                                 (None, chan_phase.context().get_counterparty_node_id())
2839                                         },
2840                                 }
2841                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2842                                 log_error!(self.logger, "Force-closing channel {}", &channel_id);
2843                                 // N.B. that we don't send any channel close event here: we
2844                                 // don't have a user_channel_id, and we never sent any opening
2845                                 // events anyway.
2846                                 (None, *peer_node_id)
2847                         } else {
2848                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2849                         }
2850                 };
2851                 if let Some(update) = update_opt {
2852                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2853                         // not try to broadcast it via whatever peer we have.
2854                         let per_peer_state = self.per_peer_state.read().unwrap();
2855                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2856                                 .ok_or(per_peer_state.values().next());
2857                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2858                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2859                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2860                                         msg: update
2861                                 });
2862                         }
2863                 }
2864
2865                 Ok(counterparty_node_id)
2866         }
2867
2868         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2869                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2870                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2871                         Ok(counterparty_node_id) => {
2872                                 let per_peer_state = self.per_peer_state.read().unwrap();
2873                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2874                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2875                                         peer_state.pending_msg_events.push(
2876                                                 events::MessageSendEvent::HandleError {
2877                                                         node_id: counterparty_node_id,
2878                                                         action: msgs::ErrorAction::DisconnectPeer {
2879                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2880                                                         },
2881                                                 }
2882                                         );
2883                                 }
2884                                 Ok(())
2885                         },
2886                         Err(e) => Err(e)
2887                 }
2888         }
2889
2890         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2891         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2892         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2893         /// channel.
2894         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2895         -> Result<(), APIError> {
2896                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2897         }
2898
2899         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2900         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2901         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2902         ///
2903         /// You can always get the latest local transaction(s) to broadcast from
2904         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2905         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2906         -> Result<(), APIError> {
2907                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2908         }
2909
2910         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2911         /// for each to the chain and rejecting new HTLCs on each.
2912         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2913                 for chan in self.list_channels() {
2914                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2915                 }
2916         }
2917
2918         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2919         /// local transaction(s).
2920         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2921                 for chan in self.list_channels() {
2922                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2923                 }
2924         }
2925
2926         fn decode_update_add_htlc_onion(
2927                 &self, msg: &msgs::UpdateAddHTLC
2928         ) -> Result<
2929                 (onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg
2930         > {
2931                 let (next_hop, shared_secret, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(
2932                         msg, &self.node_signer, &self.logger, &self.secp_ctx
2933                 )?;
2934
2935                 macro_rules! return_err {
2936                         ($msg: expr, $err_code: expr, $data: expr) => {
2937                                 {
2938                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2939                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2940                                                 channel_id: msg.channel_id,
2941                                                 htlc_id: msg.htlc_id,
2942                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2943                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2944                                         }));
2945                                 }
2946                         }
2947                 }
2948
2949                 let NextPacketDetails {
2950                         next_packet_pubkey, outgoing_amt_msat, outgoing_scid, outgoing_cltv_value
2951                 } = match next_packet_details_opt {
2952                         Some(next_packet_details) => next_packet_details,
2953                         // it is a receive, so no need for outbound checks
2954                         None => return Ok((next_hop, shared_secret, None)),
2955                 };
2956
2957                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
2958                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
2959                 if let Some((err, mut code, chan_update)) = loop {
2960                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
2961                         let forwarding_chan_info_opt = match id_option {
2962                                 None => { // unknown_next_peer
2963                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2964                                         // phantom or an intercept.
2965                                         if (self.default_configuration.accept_intercept_htlcs &&
2966                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
2967                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
2968                                         {
2969                                                 None
2970                                         } else {
2971                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2972                                         }
2973                                 },
2974                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
2975                         };
2976                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
2977                                 let per_peer_state = self.per_peer_state.read().unwrap();
2978                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2979                                 if peer_state_mutex_opt.is_none() {
2980                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2981                                 }
2982                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2983                                 let peer_state = &mut *peer_state_lock;
2984                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
2985                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
2986                                 ).flatten() {
2987                                         None => {
2988                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
2989                                                 // have no consistency guarantees.
2990                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2991                                         },
2992                                         Some(chan) => chan
2993                                 };
2994                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2995                                         // Note that the behavior here should be identical to the above block - we
2996                                         // should NOT reveal the existence or non-existence of a private channel if
2997                                         // we don't allow forwards outbound over them.
2998                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2999                                 }
3000                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3001                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3002                                         // "refuse to forward unless the SCID alias was used", so we pretend
3003                                         // we don't have the channel here.
3004                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3005                                 }
3006                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3007
3008                                 // Note that we could technically not return an error yet here and just hope
3009                                 // that the connection is reestablished or monitor updated by the time we get
3010                                 // around to doing the actual forward, but better to fail early if we can and
3011                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3012                                 // on a small/per-node/per-channel scale.
3013                                 if !chan.context.is_live() { // channel_disabled
3014                                         // If the channel_update we're going to return is disabled (i.e. the
3015                                         // peer has been disabled for some time), return `channel_disabled`,
3016                                         // otherwise return `temporary_channel_failure`.
3017                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3018                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3019                                         } else {
3020                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3021                                         }
3022                                 }
3023                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3024                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3025                                 }
3026                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3027                                         break Some((err, code, chan_update_opt));
3028                                 }
3029                                 chan_update_opt
3030                         } else {
3031                                 None
3032                         };
3033
3034                         let cur_height = self.best_block.read().unwrap().height() + 1;
3035
3036                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
3037                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
3038                         ) {
3039                                 if code & 0x1000 != 0 && chan_update_opt.is_none() {
3040                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3041                                         // forwarding over a real channel we can't generate a channel_update
3042                                         // for it. Instead we just return a generic temporary_node_failure.
3043                                         break Some((err_msg, 0x2000 | 2, None))
3044                                 }
3045                                 let chan_update_opt = if code & 0x1000 != 0 { chan_update_opt } else { None };
3046                                 break Some((err_msg, code, chan_update_opt));
3047                         }
3048
3049                         break None;
3050                 }
3051                 {
3052                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3053                         if let Some(chan_update) = chan_update {
3054                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3055                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3056                                 }
3057                                 else if code == 0x1000 | 13 {
3058                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3059                                 }
3060                                 else if code == 0x1000 | 20 {
3061                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3062                                         0u16.write(&mut res).expect("Writes cannot fail");
3063                                 }
3064                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3065                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3066                                 chan_update.write(&mut res).expect("Writes cannot fail");
3067                         } else if code & 0x1000 == 0x1000 {
3068                                 // If we're trying to return an error that requires a `channel_update` but
3069                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3070                                 // generate an update), just use the generic "temporary_node_failure"
3071                                 // instead.
3072                                 code = 0x2000 | 2;
3073                         }
3074                         return_err!(err, code, &res.0[..]);
3075                 }
3076                 Ok((next_hop, shared_secret, Some(next_packet_pubkey)))
3077         }
3078
3079         fn construct_pending_htlc_status<'a>(
3080                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3081                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3082         ) -> PendingHTLCStatus {
3083                 macro_rules! return_err {
3084                         ($msg: expr, $err_code: expr, $data: expr) => {
3085                                 {
3086                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3087                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3088                                                 channel_id: msg.channel_id,
3089                                                 htlc_id: msg.htlc_id,
3090                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3091                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3092                                         }));
3093                                 }
3094                         }
3095                 }
3096                 match decoded_hop {
3097                         onion_utils::Hop::Receive(next_hop_data) => {
3098                                 // OUR PAYMENT!
3099                                 let current_height: u32 = self.best_block.read().unwrap().height();
3100                                 match create_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3101                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat,
3102                                         current_height, self.default_configuration.accept_mpp_keysend)
3103                                 {
3104                                         Ok(info) => {
3105                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3106                                                 // message, however that would leak that we are the recipient of this payment, so
3107                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3108                                                 // delay) once they've send us a commitment_signed!
3109                                                 PendingHTLCStatus::Forward(info)
3110                                         },
3111                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3112                                 }
3113                         },
3114                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3115                                 match create_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3116                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3117                                         Ok(info) => PendingHTLCStatus::Forward(info),
3118                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3119                                 }
3120                         }
3121                 }
3122         }
3123
3124         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3125         /// public, and thus should be called whenever the result is going to be passed out in a
3126         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3127         ///
3128         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3129         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3130         /// storage and the `peer_state` lock has been dropped.
3131         ///
3132         /// [`channel_update`]: msgs::ChannelUpdate
3133         /// [`internal_closing_signed`]: Self::internal_closing_signed
3134         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3135                 if !chan.context.should_announce() {
3136                         return Err(LightningError {
3137                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3138                                 action: msgs::ErrorAction::IgnoreError
3139                         });
3140                 }
3141                 if chan.context.get_short_channel_id().is_none() {
3142                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3143                 }
3144                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3145                 self.get_channel_update_for_unicast(chan)
3146         }
3147
3148         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3149         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3150         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3151         /// provided evidence that they know about the existence of the channel.
3152         ///
3153         /// Note that through [`internal_closing_signed`], this function is called without the
3154         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3155         /// removed from the storage and the `peer_state` lock has been dropped.
3156         ///
3157         /// [`channel_update`]: msgs::ChannelUpdate
3158         /// [`internal_closing_signed`]: Self::internal_closing_signed
3159         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3160                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", &chan.context.channel_id());
3161                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3162                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3163                         Some(id) => id,
3164                 };
3165
3166                 self.get_channel_update_for_onion(short_channel_id, chan)
3167         }
3168
3169         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3170                 log_trace!(self.logger, "Generating channel update for channel {}", &chan.context.channel_id());
3171                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3172
3173                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3174                         ChannelUpdateStatus::Enabled => true,
3175                         ChannelUpdateStatus::DisabledStaged(_) => true,
3176                         ChannelUpdateStatus::Disabled => false,
3177                         ChannelUpdateStatus::EnabledStaged(_) => false,
3178                 };
3179
3180                 let unsigned = msgs::UnsignedChannelUpdate {
3181                         chain_hash: self.chain_hash,
3182                         short_channel_id,
3183                         timestamp: chan.context.get_update_time_counter(),
3184                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3185                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3186                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3187                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3188                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3189                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3190                         excess_data: Vec::new(),
3191                 };
3192                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3193                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3194                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3195                 // channel.
3196                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3197
3198                 Ok(msgs::ChannelUpdate {
3199                         signature: sig,
3200                         contents: unsigned
3201                 })
3202         }
3203
3204         #[cfg(test)]
3205         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> {
3206                 let _lck = self.total_consistency_lock.read().unwrap();
3207                 self.send_payment_along_path(SendAlongPathArgs {
3208                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3209                         session_priv_bytes
3210                 })
3211         }
3212
3213         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3214                 let SendAlongPathArgs {
3215                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3216                         session_priv_bytes
3217                 } = args;
3218                 // The top-level caller should hold the total_consistency_lock read lock.
3219                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3220
3221                 log_trace!(self.logger,
3222                         "Attempting to send payment with payment hash {} along path with next hop {}",
3223                         payment_hash, path.hops.first().unwrap().short_channel_id);
3224                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3225                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3226
3227                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3228                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3229                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3230
3231                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3232                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3233
3234                 let err: Result<(), _> = loop {
3235                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3236                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3237                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3238                         };
3239
3240                         let per_peer_state = self.per_peer_state.read().unwrap();
3241                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3242                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3243                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3244                         let peer_state = &mut *peer_state_lock;
3245                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3246                                 match chan_phase_entry.get_mut() {
3247                                         ChannelPhase::Funded(chan) => {
3248                                                 if !chan.context.is_live() {
3249                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3250                                                 }
3251                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3252                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3253                                                         htlc_cltv, HTLCSource::OutboundRoute {
3254                                                                 path: path.clone(),
3255                                                                 session_priv: session_priv.clone(),
3256                                                                 first_hop_htlc_msat: htlc_msat,
3257                                                                 payment_id,
3258                                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3259                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3260                                                         Some(monitor_update) => {
3261                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3262                                                                         false => {
3263                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3264                                                                                 // docs) that we will resend the commitment update once monitor
3265                                                                                 // updating completes. Therefore, we must return an error
3266                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3267                                                                                 // which we do in the send_payment check for
3268                                                                                 // MonitorUpdateInProgress, below.
3269                                                                                 return Err(APIError::MonitorUpdateInProgress);
3270                                                                         },
3271                                                                         true => {},
3272                                                                 }
3273                                                         },
3274                                                         None => {},
3275                                                 }
3276                                         },
3277                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3278                                 };
3279                         } else {
3280                                 // The channel was likely removed after we fetched the id from the
3281                                 // `short_to_chan_info` map, but before we successfully locked the
3282                                 // `channel_by_id` map.
3283                                 // This can occur as no consistency guarantees exists between the two maps.
3284                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3285                         }
3286                         return Ok(());
3287                 };
3288
3289                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3290                         Ok(_) => unreachable!(),
3291                         Err(e) => {
3292                                 Err(APIError::ChannelUnavailable { err: e.err })
3293                         },
3294                 }
3295         }
3296
3297         /// Sends a payment along a given route.
3298         ///
3299         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3300         /// fields for more info.
3301         ///
3302         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3303         /// [`PeerManager::process_events`]).
3304         ///
3305         /// # Avoiding Duplicate Payments
3306         ///
3307         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3308         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3309         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3310         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3311         /// second payment with the same [`PaymentId`].
3312         ///
3313         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3314         /// tracking of payments, including state to indicate once a payment has completed. Because you
3315         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3316         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3317         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3318         ///
3319         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3320         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3321         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3322         /// [`ChannelManager::list_recent_payments`] for more information.
3323         ///
3324         /// # Possible Error States on [`PaymentSendFailure`]
3325         ///
3326         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3327         /// each entry matching the corresponding-index entry in the route paths, see
3328         /// [`PaymentSendFailure`] for more info.
3329         ///
3330         /// In general, a path may raise:
3331         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3332         ///    node public key) is specified.
3333         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3334         ///    closed, doesn't exist, or the peer is currently disconnected.
3335         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3336         ///    relevant updates.
3337         ///
3338         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3339         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3340         /// different route unless you intend to pay twice!
3341         ///
3342         /// [`RouteHop`]: crate::routing::router::RouteHop
3343         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3344         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3345         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3346         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3347         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3348         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3349                 let best_block_height = self.best_block.read().unwrap().height();
3350                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3351                 self.pending_outbound_payments
3352                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3353                                 &self.entropy_source, &self.node_signer, best_block_height,
3354                                 |args| self.send_payment_along_path(args))
3355         }
3356
3357         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3358         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3359         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3360                 let best_block_height = self.best_block.read().unwrap().height();
3361                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3362                 self.pending_outbound_payments
3363                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3364                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3365                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3366                                 &self.pending_events, |args| self.send_payment_along_path(args))
3367         }
3368
3369         #[cfg(test)]
3370         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> {
3371                 let best_block_height = self.best_block.read().unwrap().height();
3372                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3373                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3374                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3375                         best_block_height, |args| self.send_payment_along_path(args))
3376         }
3377
3378         #[cfg(test)]
3379         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> {
3380                 let best_block_height = self.best_block.read().unwrap().height();
3381                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3382         }
3383
3384         #[cfg(test)]
3385         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3386                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3387         }
3388
3389         pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3390                 let best_block_height = self.best_block.read().unwrap().height();
3391                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3392                 self.pending_outbound_payments
3393                         .send_payment_for_bolt12_invoice(
3394                                 invoice, payment_id, &self.router, self.list_usable_channels(),
3395                                 || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3396                                 best_block_height, &self.logger, &self.pending_events,
3397                                 |args| self.send_payment_along_path(args)
3398                         )
3399         }
3400
3401         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3402         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3403         /// retries are exhausted.
3404         ///
3405         /// # Event Generation
3406         ///
3407         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3408         /// as there are no remaining pending HTLCs for this payment.
3409         ///
3410         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3411         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3412         /// determine the ultimate status of a payment.
3413         ///
3414         /// # Requested Invoices
3415         ///
3416         /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
3417         /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
3418         /// and prevent any attempts at paying it once received. The other events may only be generated
3419         /// once the invoice has been received.
3420         ///
3421         /// # Restart Behavior
3422         ///
3423         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3424         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
3425         /// [`Event::InvoiceRequestFailed`].
3426         ///
3427         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3428         pub fn abandon_payment(&self, payment_id: PaymentId) {
3429                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3430                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3431         }
3432
3433         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3434         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3435         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3436         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3437         /// never reach the recipient.
3438         ///
3439         /// See [`send_payment`] documentation for more details on the return value of this function
3440         /// and idempotency guarantees provided by the [`PaymentId`] key.
3441         ///
3442         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3443         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3444         ///
3445         /// [`send_payment`]: Self::send_payment
3446         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3447                 let best_block_height = self.best_block.read().unwrap().height();
3448                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3449                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3450                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3451                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3452         }
3453
3454         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3455         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3456         ///
3457         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3458         /// payments.
3459         ///
3460         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3461         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> {
3462                 let best_block_height = self.best_block.read().unwrap().height();
3463                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3464                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3465                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3466                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3467                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3468         }
3469
3470         /// Send a payment that is probing the given route for liquidity. We calculate the
3471         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3472         /// us to easily discern them from real payments.
3473         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3474                 let best_block_height = self.best_block.read().unwrap().height();
3475                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3476                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3477                         &self.entropy_source, &self.node_signer, best_block_height,
3478                         |args| self.send_payment_along_path(args))
3479         }
3480
3481         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3482         /// payment probe.
3483         #[cfg(test)]
3484         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3485                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3486         }
3487
3488         /// Sends payment probes over all paths of a route that would be used to pay the given
3489         /// amount to the given `node_id`.
3490         ///
3491         /// See [`ChannelManager::send_preflight_probes`] for more information.
3492         pub fn send_spontaneous_preflight_probes(
3493                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3494                 liquidity_limit_multiplier: Option<u64>,
3495         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3496                 let payment_params =
3497                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3498
3499                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3500
3501                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3502         }
3503
3504         /// Sends payment probes over all paths of a route that would be used to pay a route found
3505         /// according to the given [`RouteParameters`].
3506         ///
3507         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3508         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3509         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3510         /// confirmation in a wallet UI.
3511         ///
3512         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3513         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3514         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3515         /// payment. To mitigate this issue, channels with available liquidity less than the required
3516         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3517         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3518         pub fn send_preflight_probes(
3519                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3520         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3521                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3522
3523                 let payer = self.get_our_node_id();
3524                 let usable_channels = self.list_usable_channels();
3525                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3526                 let inflight_htlcs = self.compute_inflight_htlcs();
3527
3528                 let route = self
3529                         .router
3530                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3531                         .map_err(|e| {
3532                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3533                                 ProbeSendFailure::RouteNotFound
3534                         })?;
3535
3536                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3537
3538                 let mut res = Vec::new();
3539
3540                 for mut path in route.paths {
3541                         // If the last hop is probably an unannounced channel we refrain from probing all the
3542                         // way through to the end and instead probe up to the second-to-last channel.
3543                         while let Some(last_path_hop) = path.hops.last() {
3544                                 if last_path_hop.maybe_announced_channel {
3545                                         // We found a potentially announced last hop.
3546                                         break;
3547                                 } else {
3548                                         // Drop the last hop, as it's likely unannounced.
3549                                         log_debug!(
3550                                                 self.logger,
3551                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3552                                                 last_path_hop.short_channel_id
3553                                         );
3554                                         let final_value_msat = path.final_value_msat();
3555                                         path.hops.pop();
3556                                         if let Some(new_last) = path.hops.last_mut() {
3557                                                 new_last.fee_msat += final_value_msat;
3558                                         }
3559                                 }
3560                         }
3561
3562                         if path.hops.len() < 2 {
3563                                 log_debug!(
3564                                         self.logger,
3565                                         "Skipped sending payment probe over path with less than two hops."
3566                                 );
3567                                 continue;
3568                         }
3569
3570                         if let Some(first_path_hop) = path.hops.first() {
3571                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3572                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3573                                 }) {
3574                                         let path_value = path.final_value_msat() + path.fee_msat();
3575                                         let used_liquidity =
3576                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3577
3578                                         if first_hop.next_outbound_htlc_limit_msat
3579                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3580                                         {
3581                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3582                                                 continue;
3583                                         } else {
3584                                                 *used_liquidity += path_value;
3585                                         }
3586                                 }
3587                         }
3588
3589                         res.push(self.send_probe(path).map_err(|e| {
3590                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3591                                 ProbeSendFailure::SendingFailed(e)
3592                         })?);
3593                 }
3594
3595                 Ok(res)
3596         }
3597
3598         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3599         /// which checks the correctness of the funding transaction given the associated channel.
3600         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3601                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3602                 mut find_funding_output: FundingOutput,
3603         ) -> Result<(), APIError> {
3604                 let per_peer_state = self.per_peer_state.read().unwrap();
3605                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3606                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3607
3608                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3609                 let peer_state = &mut *peer_state_lock;
3610                 let (chan, msg) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3611                         Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
3612                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3613
3614                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &self.logger)
3615                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3616                                                 let channel_id = chan.context.channel_id();
3617                                                 let user_id = chan.context.get_user_id();
3618                                                 let shutdown_res = chan.context.force_shutdown(false);
3619                                                 let channel_capacity = chan.context.get_value_satoshis();
3620                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3621                                         } else { unreachable!(); });
3622                                 match funding_res {
3623                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3624                                         Err((chan, err)) => {
3625                                                 mem::drop(peer_state_lock);
3626                                                 mem::drop(per_peer_state);
3627
3628                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3629                                                 return Err(APIError::ChannelUnavailable {
3630                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3631                                                 });
3632                                         },
3633                                 }
3634                         },
3635                         Some(phase) => {
3636                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3637                                 return Err(APIError::APIMisuseError {
3638                                         err: format!(
3639                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3640                                                 temporary_channel_id, counterparty_node_id),
3641                                 })
3642                         },
3643                         None => return Err(APIError::ChannelUnavailable {err: format!(
3644                                 "Channel with id {} not found for the passed counterparty node_id {}",
3645                                 temporary_channel_id, counterparty_node_id),
3646                                 }),
3647                 };
3648
3649                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3650                         node_id: chan.context.get_counterparty_node_id(),
3651                         msg,
3652                 });
3653                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3654                         hash_map::Entry::Occupied(_) => {
3655                                 panic!("Generated duplicate funding txid?");
3656                         },
3657                         hash_map::Entry::Vacant(e) => {
3658                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3659                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3660                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3661                                 }
3662                                 e.insert(ChannelPhase::Funded(chan));
3663                         }
3664                 }
3665                 Ok(())
3666         }
3667
3668         #[cfg(test)]
3669         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3670                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3671                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3672                 })
3673         }
3674
3675         /// Call this upon creation of a funding transaction for the given channel.
3676         ///
3677         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3678         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3679         ///
3680         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3681         /// across the p2p network.
3682         ///
3683         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3684         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3685         ///
3686         /// May panic if the output found in the funding transaction is duplicative with some other
3687         /// channel (note that this should be trivially prevented by using unique funding transaction
3688         /// keys per-channel).
3689         ///
3690         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3691         /// counterparty's signature the funding transaction will automatically be broadcast via the
3692         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3693         ///
3694         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3695         /// not currently support replacing a funding transaction on an existing channel. Instead,
3696         /// create a new channel with a conflicting funding transaction.
3697         ///
3698         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3699         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3700         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3701         /// for more details.
3702         ///
3703         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3704         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3705         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3706                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3707         }
3708
3709         /// Call this upon creation of a batch funding transaction for the given channels.
3710         ///
3711         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3712         /// each individual channel and transaction output.
3713         ///
3714         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3715         /// will only be broadcast when we have safely received and persisted the counterparty's
3716         /// signature for each channel.
3717         ///
3718         /// If there is an error, all channels in the batch are to be considered closed.
3719         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3720                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3721                 let mut result = Ok(());
3722
3723                 if !funding_transaction.is_coin_base() {
3724                         for inp in funding_transaction.input.iter() {
3725                                 if inp.witness.is_empty() {
3726                                         result = result.and(Err(APIError::APIMisuseError {
3727                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3728                                         }));
3729                                 }
3730                         }
3731                 }
3732                 if funding_transaction.output.len() > u16::max_value() as usize {
3733                         result = result.and(Err(APIError::APIMisuseError {
3734                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3735                         }));
3736                 }
3737                 {
3738                         let height = self.best_block.read().unwrap().height();
3739                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3740                         // lower than the next block height. However, the modules constituting our Lightning
3741                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3742                         // module is ahead of LDK, only allow one more block of headroom.
3743                         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 {
3744                                 result = result.and(Err(APIError::APIMisuseError {
3745                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3746                                 }));
3747                         }
3748                 }
3749
3750                 let txid = funding_transaction.txid();
3751                 let is_batch_funding = temporary_channels.len() > 1;
3752                 let mut funding_batch_states = if is_batch_funding {
3753                         Some(self.funding_batch_states.lock().unwrap())
3754                 } else {
3755                         None
3756                 };
3757                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3758                         match states.entry(txid) {
3759                                 btree_map::Entry::Occupied(_) => {
3760                                         result = result.clone().and(Err(APIError::APIMisuseError {
3761                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3762                                         }));
3763                                         None
3764                                 },
3765                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3766                         }
3767                 });
3768                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3769                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3770                                 temporary_channel_id,
3771                                 counterparty_node_id,
3772                                 funding_transaction.clone(),
3773                                 is_batch_funding,
3774                                 |chan, tx| {
3775                                         let mut output_index = None;
3776                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3777                                         for (idx, outp) in tx.output.iter().enumerate() {
3778                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3779                                                         if output_index.is_some() {
3780                                                                 return Err(APIError::APIMisuseError {
3781                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3782                                                                 });
3783                                                         }
3784                                                         output_index = Some(idx as u16);
3785                                                 }
3786                                         }
3787                                         if output_index.is_none() {
3788                                                 return Err(APIError::APIMisuseError {
3789                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3790                                                 });
3791                                         }
3792                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3793                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3794                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3795                                         }
3796                                         Ok(outpoint)
3797                                 })
3798                         );
3799                 }
3800                 if let Err(ref e) = result {
3801                         // Remaining channels need to be removed on any error.
3802                         let e = format!("Error in transaction funding: {:?}", e);
3803                         let mut channels_to_remove = Vec::new();
3804                         channels_to_remove.extend(funding_batch_states.as_mut()
3805                                 .and_then(|states| states.remove(&txid))
3806                                 .into_iter().flatten()
3807                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3808                         );
3809                         channels_to_remove.extend(temporary_channels.iter()
3810                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3811                         );
3812                         let mut shutdown_results = Vec::new();
3813                         {
3814                                 let per_peer_state = self.per_peer_state.read().unwrap();
3815                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3816                                         per_peer_state.get(&counterparty_node_id)
3817                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3818                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3819                                                 .map(|mut chan| {
3820                                                         update_maps_on_chan_removal!(self, &chan.context());
3821                                                         self.issue_channel_close_events(&chan.context(), ClosureReason::ProcessingError { err: e.clone() });
3822                                                         shutdown_results.push(chan.context_mut().force_shutdown(false));
3823                                                 });
3824                                 }
3825                         }
3826                         for shutdown_result in shutdown_results.drain(..) {
3827                                 self.finish_close_channel(shutdown_result);
3828                         }
3829                 }
3830                 result
3831         }
3832
3833         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3834         ///
3835         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3836         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3837         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3838         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3839         ///
3840         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3841         /// `counterparty_node_id` is provided.
3842         ///
3843         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3844         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3845         ///
3846         /// If an error is returned, none of the updates should be considered applied.
3847         ///
3848         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3849         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3850         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3851         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3852         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3853         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3854         /// [`APIMisuseError`]: APIError::APIMisuseError
3855         pub fn update_partial_channel_config(
3856                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
3857         ) -> Result<(), APIError> {
3858                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
3859                         return Err(APIError::APIMisuseError {
3860                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
3861                         });
3862                 }
3863
3864                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3865                 let per_peer_state = self.per_peer_state.read().unwrap();
3866                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3867                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3868                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3869                 let peer_state = &mut *peer_state_lock;
3870                 for channel_id in channel_ids {
3871                         if !peer_state.has_channel(channel_id) {
3872                                 return Err(APIError::ChannelUnavailable {
3873                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
3874                                 });
3875                         };
3876                 }
3877                 for channel_id in channel_ids {
3878                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
3879                                 let mut config = channel_phase.context().config();
3880                                 config.apply(config_update);
3881                                 if !channel_phase.context_mut().update_config(&config) {
3882                                         continue;
3883                                 }
3884                                 if let ChannelPhase::Funded(channel) = channel_phase {
3885                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
3886                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
3887                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
3888                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
3889                                                         node_id: channel.context.get_counterparty_node_id(),
3890                                                         msg,
3891                                                 });
3892                                         }
3893                                 }
3894                                 continue;
3895                         } else {
3896                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
3897                                 debug_assert!(false);
3898                                 return Err(APIError::ChannelUnavailable {
3899                                         err: format!(
3900                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
3901                                                 channel_id, counterparty_node_id),
3902                                 });
3903                         };
3904                 }
3905                 Ok(())
3906         }
3907
3908         /// Atomically updates the [`ChannelConfig`] for the given channels.
3909         ///
3910         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3911         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3912         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3913         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3914         ///
3915         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3916         /// `counterparty_node_id` is provided.
3917         ///
3918         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3919         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3920         ///
3921         /// If an error is returned, none of the updates should be considered applied.
3922         ///
3923         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3924         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3925         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3926         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3927         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3928         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3929         /// [`APIMisuseError`]: APIError::APIMisuseError
3930         pub fn update_channel_config(
3931                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
3932         ) -> Result<(), APIError> {
3933                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
3934         }
3935
3936         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
3937         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
3938         ///
3939         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
3940         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
3941         ///
3942         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
3943         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
3944         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
3945         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
3946         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
3947         ///
3948         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
3949         /// you from forwarding more than you received. See
3950         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
3951         /// than expected.
3952         ///
3953         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3954         /// backwards.
3955         ///
3956         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
3957         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3958         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
3959         // TODO: when we move to deciding the best outbound channel at forward time, only take
3960         // `next_node_id` and not `next_hop_channel_id`
3961         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> {
3962                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3963
3964                 let next_hop_scid = {
3965                         let peer_state_lock = self.per_peer_state.read().unwrap();
3966                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
3967                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
3968                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3969                         let peer_state = &mut *peer_state_lock;
3970                         match peer_state.channel_by_id.get(next_hop_channel_id) {
3971                                 Some(ChannelPhase::Funded(chan)) => {
3972                                         if !chan.context.is_usable() {
3973                                                 return Err(APIError::ChannelUnavailable {
3974                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
3975                                                 })
3976                                         }
3977                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
3978                                 },
3979                                 Some(_) => return Err(APIError::ChannelUnavailable {
3980                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
3981                                                 next_hop_channel_id, next_node_id)
3982                                 }),
3983                                 None => return Err(APIError::ChannelUnavailable {
3984                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}",
3985                                                 next_hop_channel_id, next_node_id)
3986                                 })
3987                         }
3988                 };
3989
3990                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3991                         .ok_or_else(|| APIError::APIMisuseError {
3992                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3993                         })?;
3994
3995                 let routing = match payment.forward_info.routing {
3996                         PendingHTLCRouting::Forward { onion_packet, .. } => {
3997                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
3998                         },
3999                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4000                 };
4001                 let skimmed_fee_msat =
4002                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4003                 let pending_htlc_info = PendingHTLCInfo {
4004                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4005                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4006                 };
4007
4008                 let mut per_source_pending_forward = [(
4009                         payment.prev_short_channel_id,
4010                         payment.prev_funding_outpoint,
4011                         payment.prev_user_channel_id,
4012                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4013                 )];
4014                 self.forward_htlcs(&mut per_source_pending_forward);
4015                 Ok(())
4016         }
4017
4018         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4019         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4020         ///
4021         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4022         /// backwards.
4023         ///
4024         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4025         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4026                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4027
4028                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4029                         .ok_or_else(|| APIError::APIMisuseError {
4030                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4031                         })?;
4032
4033                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4034                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4035                                 short_channel_id: payment.prev_short_channel_id,
4036                                 user_channel_id: Some(payment.prev_user_channel_id),
4037                                 outpoint: payment.prev_funding_outpoint,
4038                                 htlc_id: payment.prev_htlc_id,
4039                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4040                                 phantom_shared_secret: None,
4041                         });
4042
4043                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4044                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4045                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4046                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4047
4048                 Ok(())
4049         }
4050
4051         /// Processes HTLCs which are pending waiting on random forward delay.
4052         ///
4053         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4054         /// Will likely generate further events.
4055         pub fn process_pending_htlc_forwards(&self) {
4056                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4057
4058                 let mut new_events = VecDeque::new();
4059                 let mut failed_forwards = Vec::new();
4060                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4061                 {
4062                         let mut forward_htlcs = HashMap::new();
4063                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4064
4065                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4066                                 if short_chan_id != 0 {
4067                                         macro_rules! forwarding_channel_not_found {
4068                                                 () => {
4069                                                         for forward_info in pending_forwards.drain(..) {
4070                                                                 match forward_info {
4071                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4072                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4073                                                                                 forward_info: PendingHTLCInfo {
4074                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4075                                                                                         outgoing_cltv_value, ..
4076                                                                                 }
4077                                                                         }) => {
4078                                                                                 macro_rules! failure_handler {
4079                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4080                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4081
4082                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4083                                                                                                         short_channel_id: prev_short_channel_id,
4084                                                                                                         user_channel_id: Some(prev_user_channel_id),
4085                                                                                                         outpoint: prev_funding_outpoint,
4086                                                                                                         htlc_id: prev_htlc_id,
4087                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4088                                                                                                         phantom_shared_secret: $phantom_ss,
4089                                                                                                 });
4090
4091                                                                                                 let reason = if $next_hop_unknown {
4092                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4093                                                                                                 } else {
4094                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4095                                                                                                 };
4096
4097                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4098                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4099                                                                                                         reason
4100                                                                                                 ));
4101                                                                                                 continue;
4102                                                                                         }
4103                                                                                 }
4104                                                                                 macro_rules! fail_forward {
4105                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4106                                                                                                 {
4107                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4108                                                                                                 }
4109                                                                                         }
4110                                                                                 }
4111                                                                                 macro_rules! failed_payment {
4112                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4113                                                                                                 {
4114                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4115                                                                                                 }
4116                                                                                         }
4117                                                                                 }
4118                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
4119                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4120                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4121                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4122                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4123                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4124                                                                                                         payment_hash, &self.node_signer
4125                                                                                                 ) {
4126                                                                                                         Ok(res) => res,
4127                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4128                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
4129                                                                                                                 // In this scenario, the phantom would have sent us an
4130                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4131                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4132                                                                                                                 // of the onion.
4133                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4134                                                                                                         },
4135                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4136                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4137                                                                                                         },
4138                                                                                                 };
4139                                                                                                 match next_hop {
4140                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4141                                                                                                                 let current_height: u32 = self.best_block.read().unwrap().height();
4142                                                                                                                 match create_recv_pending_htlc_info(hop_data,
4143                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4144                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None,
4145                                                                                                                         current_height, self.default_configuration.accept_mpp_keysend)
4146                                                                                                                 {
4147                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4148                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4149                                                                                                                 }
4150                                                                                                         },
4151                                                                                                         _ => panic!(),
4152                                                                                                 }
4153                                                                                         } else {
4154                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4155                                                                                         }
4156                                                                                 } else {
4157                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4158                                                                                 }
4159                                                                         },
4160                                                                         HTLCForwardInfo::FailHTLC { .. } => {
4161                                                                                 // Channel went away before we could fail it. This implies
4162                                                                                 // the channel is now on chain and our counterparty is
4163                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4164                                                                                 // problem, not ours.
4165                                                                         }
4166                                                                 }
4167                                                         }
4168                                                 }
4169                                         }
4170                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4171                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4172                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4173                                                 None => {
4174                                                         forwarding_channel_not_found!();
4175                                                         continue;
4176                                                 }
4177                                         };
4178                                         let per_peer_state = self.per_peer_state.read().unwrap();
4179                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4180                                         if peer_state_mutex_opt.is_none() {
4181                                                 forwarding_channel_not_found!();
4182                                                 continue;
4183                                         }
4184                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4185                                         let peer_state = &mut *peer_state_lock;
4186                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4187                                                 for forward_info in pending_forwards.drain(..) {
4188                                                         match forward_info {
4189                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4190                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4191                                                                         forward_info: PendingHTLCInfo {
4192                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4193                                                                                 routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
4194                                                                         },
4195                                                                 }) => {
4196                                                                         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);
4197                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4198                                                                                 short_channel_id: prev_short_channel_id,
4199                                                                                 user_channel_id: Some(prev_user_channel_id),
4200                                                                                 outpoint: prev_funding_outpoint,
4201                                                                                 htlc_id: prev_htlc_id,
4202                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4203                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4204                                                                                 phantom_shared_secret: None,
4205                                                                         });
4206                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4207                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4208                                                                                 onion_packet, skimmed_fee_msat, &self.fee_estimator,
4209                                                                                 &self.logger)
4210                                                                         {
4211                                                                                 if let ChannelError::Ignore(msg) = e {
4212                                                                                         log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4213                                                                                 } else {
4214                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4215                                                                                 }
4216                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4217                                                                                 failed_forwards.push((htlc_source, payment_hash,
4218                                                                                         HTLCFailReason::reason(failure_code, data),
4219                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4220                                                                                 ));
4221                                                                                 continue;
4222                                                                         }
4223                                                                 },
4224                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4225                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4226                                                                 },
4227                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4228                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4229                                                                         if let Err(e) = chan.queue_fail_htlc(
4230                                                                                 htlc_id, err_packet, &self.logger
4231                                                                         ) {
4232                                                                                 if let ChannelError::Ignore(msg) = e {
4233                                                                                         log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4234                                                                                 } else {
4235                                                                                         panic!("Stated return value requirements in queue_fail_htlc() were not met");
4236                                                                                 }
4237                                                                                 // fail-backs are best-effort, we probably already have one
4238                                                                                 // pending, and if not that's OK, if not, the channel is on
4239                                                                                 // the chain and sending the HTLC-Timeout is their problem.
4240                                                                                 continue;
4241                                                                         }
4242                                                                 },
4243                                                         }
4244                                                 }
4245                                         } else {
4246                                                 forwarding_channel_not_found!();
4247                                                 continue;
4248                                         }
4249                                 } else {
4250                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4251                                                 match forward_info {
4252                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4253                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4254                                                                 forward_info: PendingHTLCInfo {
4255                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4256                                                                         skimmed_fee_msat, ..
4257                                                                 }
4258                                                         }) => {
4259                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4260                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4261                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4262                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4263                                                                                                 payment_metadata, custom_tlvs };
4264                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4265                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4266                                                                         },
4267                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4268                                                                                 let onion_fields = RecipientOnionFields {
4269                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4270                                                                                         payment_metadata,
4271                                                                                         custom_tlvs,
4272                                                                                 };
4273                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4274                                                                                         payment_data, None, onion_fields)
4275                                                                         },
4276                                                                         _ => {
4277                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4278                                                                         }
4279                                                                 };
4280                                                                 let claimable_htlc = ClaimableHTLC {
4281                                                                         prev_hop: HTLCPreviousHopData {
4282                                                                                 short_channel_id: prev_short_channel_id,
4283                                                                                 user_channel_id: Some(prev_user_channel_id),
4284                                                                                 outpoint: prev_funding_outpoint,
4285                                                                                 htlc_id: prev_htlc_id,
4286                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4287                                                                                 phantom_shared_secret,
4288                                                                         },
4289                                                                         // We differentiate the received value from the sender intended value
4290                                                                         // if possible so that we don't prematurely mark MPP payments complete
4291                                                                         // if routing nodes overpay
4292                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4293                                                                         sender_intended_value: outgoing_amt_msat,
4294                                                                         timer_ticks: 0,
4295                                                                         total_value_received: None,
4296                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4297                                                                         cltv_expiry,
4298                                                                         onion_payload,
4299                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4300                                                                 };
4301
4302                                                                 let mut committed_to_claimable = false;
4303
4304                                                                 macro_rules! fail_htlc {
4305                                                                         ($htlc: expr, $payment_hash: expr) => {
4306                                                                                 debug_assert!(!committed_to_claimable);
4307                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4308                                                                                 htlc_msat_height_data.extend_from_slice(
4309                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4310                                                                                 );
4311                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4312                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4313                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4314                                                                                                 outpoint: prev_funding_outpoint,
4315                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4316                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4317                                                                                                 phantom_shared_secret,
4318                                                                                         }), payment_hash,
4319                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4320                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4321                                                                                 ));
4322                                                                                 continue 'next_forwardable_htlc;
4323                                                                         }
4324                                                                 }
4325                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4326                                                                 let mut receiver_node_id = self.our_network_pubkey;
4327                                                                 if phantom_shared_secret.is_some() {
4328                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4329                                                                                 .expect("Failed to get node_id for phantom node recipient");
4330                                                                 }
4331
4332                                                                 macro_rules! check_total_value {
4333                                                                         ($purpose: expr) => {{
4334                                                                                 let mut payment_claimable_generated = false;
4335                                                                                 let is_keysend = match $purpose {
4336                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4337                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4338                                                                                 };
4339                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4340                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4341                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4342                                                                                 }
4343                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4344                                                                                         .entry(payment_hash)
4345                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4346                                                                                         .or_insert_with(|| {
4347                                                                                                 committed_to_claimable = true;
4348                                                                                                 ClaimablePayment {
4349                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4350                                                                                                 }
4351                                                                                         });
4352                                                                                 if $purpose != claimable_payment.purpose {
4353                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4354                                                                                         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));
4355                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4356                                                                                 }
4357                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4358                                                                                         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);
4359                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4360                                                                                 }
4361                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4362                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4363                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4364                                                                                         }
4365                                                                                 } else {
4366                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4367                                                                                 }
4368                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4369                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4370                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4371                                                                                 for htlc in htlcs.iter() {
4372                                                                                         total_value += htlc.sender_intended_value;
4373                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4374                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4375                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4376                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4377                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4378                                                                                         }
4379                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4380                                                                                 }
4381                                                                                 // The condition determining whether an MPP is complete must
4382                                                                                 // match exactly the condition used in `timer_tick_occurred`
4383                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4384                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4385                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4386                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4387                                                                                                 &payment_hash);
4388                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4389                                                                                 } else if total_value >= claimable_htlc.total_msat {
4390                                                                                         #[allow(unused_assignments)] {
4391                                                                                                 committed_to_claimable = true;
4392                                                                                         }
4393                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4394                                                                                         htlcs.push(claimable_htlc);
4395                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4396                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4397                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4398                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4399                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4400                                                                                                 counterparty_skimmed_fee_msat);
4401                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4402                                                                                                 receiver_node_id: Some(receiver_node_id),
4403                                                                                                 payment_hash,
4404                                                                                                 purpose: $purpose,
4405                                                                                                 amount_msat,
4406                                                                                                 counterparty_skimmed_fee_msat,
4407                                                                                                 via_channel_id: Some(prev_channel_id),
4408                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4409                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4410                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4411                                                                                         }, None));
4412                                                                                         payment_claimable_generated = true;
4413                                                                                 } else {
4414                                                                                         // Nothing to do - we haven't reached the total
4415                                                                                         // payment value yet, wait until we receive more
4416                                                                                         // MPP parts.
4417                                                                                         htlcs.push(claimable_htlc);
4418                                                                                         #[allow(unused_assignments)] {
4419                                                                                                 committed_to_claimable = true;
4420                                                                                         }
4421                                                                                 }
4422                                                                                 payment_claimable_generated
4423                                                                         }}
4424                                                                 }
4425
4426                                                                 // Check that the payment hash and secret are known. Note that we
4427                                                                 // MUST take care to handle the "unknown payment hash" and
4428                                                                 // "incorrect payment secret" cases here identically or we'd expose
4429                                                                 // that we are the ultimate recipient of the given payment hash.
4430                                                                 // Further, we must not expose whether we have any other HTLCs
4431                                                                 // associated with the same payment_hash pending or not.
4432                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4433                                                                 match payment_secrets.entry(payment_hash) {
4434                                                                         hash_map::Entry::Vacant(_) => {
4435                                                                                 match claimable_htlc.onion_payload {
4436                                                                                         OnionPayload::Invoice { .. } => {
4437                                                                                                 let payment_data = payment_data.unwrap();
4438                                                                                                 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) {
4439                                                                                                         Ok(result) => result,
4440                                                                                                         Err(()) => {
4441                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4442                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4443                                                                                                         }
4444                                                                                                 };
4445                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4446                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4447                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4448                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4449                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4450                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4451                                                                                                         }
4452                                                                                                 }
4453                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4454                                                                                                         payment_preimage: payment_preimage.clone(),
4455                                                                                                         payment_secret: payment_data.payment_secret,
4456                                                                                                 };
4457                                                                                                 check_total_value!(purpose);
4458                                                                                         },
4459                                                                                         OnionPayload::Spontaneous(preimage) => {
4460                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4461                                                                                                 check_total_value!(purpose);
4462                                                                                         }
4463                                                                                 }
4464                                                                         },
4465                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4466                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4467                                                                                         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);
4468                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4469                                                                                 }
4470                                                                                 let payment_data = payment_data.unwrap();
4471                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4472                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4473                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4474                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4475                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4476                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4477                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4478                                                                                 } else {
4479                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4480                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4481                                                                                                 payment_secret: payment_data.payment_secret,
4482                                                                                         };
4483                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4484                                                                                         if payment_claimable_generated {
4485                                                                                                 inbound_payment.remove_entry();
4486                                                                                         }
4487                                                                                 }
4488                                                                         },
4489                                                                 };
4490                                                         },
4491                                                         HTLCForwardInfo::FailHTLC { .. } => {
4492                                                                 panic!("Got pending fail of our own HTLC");
4493                                                         }
4494                                                 }
4495                                         }
4496                                 }
4497                         }
4498                 }
4499
4500                 let best_block_height = self.best_block.read().unwrap().height();
4501                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4502                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4503                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4504
4505                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4506                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4507                 }
4508                 self.forward_htlcs(&mut phantom_receives);
4509
4510                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4511                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4512                 // nice to do the work now if we can rather than while we're trying to get messages in the
4513                 // network stack.
4514                 self.check_free_holding_cells();
4515
4516                 if new_events.is_empty() { return }
4517                 let mut events = self.pending_events.lock().unwrap();
4518                 events.append(&mut new_events);
4519         }
4520
4521         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4522         ///
4523         /// Expects the caller to have a total_consistency_lock read lock.
4524         fn process_background_events(&self) -> NotifyOption {
4525                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4526
4527                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4528
4529                 let mut background_events = Vec::new();
4530                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4531                 if background_events.is_empty() {
4532                         return NotifyOption::SkipPersistNoEvents;
4533                 }
4534
4535                 for event in background_events.drain(..) {
4536                         match event {
4537                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4538                                         // The channel has already been closed, so no use bothering to care about the
4539                                         // monitor updating completing.
4540                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4541                                 },
4542                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4543                                         let mut updated_chan = false;
4544                                         {
4545                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4546                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4547                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4548                                                         let peer_state = &mut *peer_state_lock;
4549                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4550                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4551                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4552                                                                                 updated_chan = true;
4553                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4554                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4555                                                                         } else {
4556                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4557                                                                         }
4558                                                                 },
4559                                                                 hash_map::Entry::Vacant(_) => {},
4560                                                         }
4561                                                 }
4562                                         }
4563                                         if !updated_chan {
4564                                                 // TODO: Track this as in-flight even though the channel is closed.
4565                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4566                                         }
4567                                 },
4568                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4569                                         let per_peer_state = self.per_peer_state.read().unwrap();
4570                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4571                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4572                                                 let peer_state = &mut *peer_state_lock;
4573                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4574                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4575                                                 } else {
4576                                                         let update_actions = peer_state.monitor_update_blocked_actions
4577                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4578                                                         mem::drop(peer_state_lock);
4579                                                         mem::drop(per_peer_state);
4580                                                         self.handle_monitor_update_completion_actions(update_actions);
4581                                                 }
4582                                         }
4583                                 },
4584                         }
4585                 }
4586                 NotifyOption::DoPersist
4587         }
4588
4589         #[cfg(any(test, feature = "_test_utils"))]
4590         /// Process background events, for functional testing
4591         pub fn test_process_background_events(&self) {
4592                 let _lck = self.total_consistency_lock.read().unwrap();
4593                 let _ = self.process_background_events();
4594         }
4595
4596         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4597                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4598                 // If the feerate has decreased by less than half, don't bother
4599                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4600                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4601                                 log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4602                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4603                         }
4604                         return NotifyOption::SkipPersistNoEvents;
4605                 }
4606                 if !chan.context.is_live() {
4607                         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).",
4608                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4609                         return NotifyOption::SkipPersistNoEvents;
4610                 }
4611                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4612                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4613
4614                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4615                 NotifyOption::DoPersist
4616         }
4617
4618         #[cfg(fuzzing)]
4619         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4620         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4621         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4622         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4623         pub fn maybe_update_chan_fees(&self) {
4624                 PersistenceNotifierGuard::optionally_notify(self, || {
4625                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4626
4627                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4628                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4629
4630                         let per_peer_state = self.per_peer_state.read().unwrap();
4631                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4632                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4633                                 let peer_state = &mut *peer_state_lock;
4634                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4635                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4636                                 ) {
4637                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4638                                                 anchor_feerate
4639                                         } else {
4640                                                 non_anchor_feerate
4641                                         };
4642                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4643                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4644                                 }
4645                         }
4646
4647                         should_persist
4648                 });
4649         }
4650
4651         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4652         ///
4653         /// This currently includes:
4654         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4655         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4656         ///    than a minute, informing the network that they should no longer attempt to route over
4657         ///    the channel.
4658         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4659         ///    with the current [`ChannelConfig`].
4660         ///  * Removing peers which have disconnected but and no longer have any channels.
4661         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4662         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4663         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4664         ///    The latter is determined using the system clock in `std` and the highest seen block time
4665         ///    minus two hours in `no-std`.
4666         ///
4667         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4668         /// estimate fetches.
4669         ///
4670         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4671         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4672         pub fn timer_tick_occurred(&self) {
4673                 PersistenceNotifierGuard::optionally_notify(self, || {
4674                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4675
4676                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4677                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4678
4679                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4680                         let mut timed_out_mpp_htlcs = Vec::new();
4681                         let mut pending_peers_awaiting_removal = Vec::new();
4682                         let mut shutdown_channels = Vec::new();
4683
4684                         let mut process_unfunded_channel_tick = |
4685                                 chan_id: &ChannelId,
4686                                 context: &mut ChannelContext<SP>,
4687                                 unfunded_context: &mut UnfundedChannelContext,
4688                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4689                                 counterparty_node_id: PublicKey,
4690                         | {
4691                                 context.maybe_expire_prev_config();
4692                                 if unfunded_context.should_expire_unfunded_channel() {
4693                                         log_error!(self.logger,
4694                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4695                                         update_maps_on_chan_removal!(self, &context);
4696                                         self.issue_channel_close_events(&context, ClosureReason::HolderForceClosed);
4697                                         shutdown_channels.push(context.force_shutdown(false));
4698                                         pending_msg_events.push(MessageSendEvent::HandleError {
4699                                                 node_id: counterparty_node_id,
4700                                                 action: msgs::ErrorAction::SendErrorMessage {
4701                                                         msg: msgs::ErrorMessage {
4702                                                                 channel_id: *chan_id,
4703                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4704                                                         },
4705                                                 },
4706                                         });
4707                                         false
4708                                 } else {
4709                                         true
4710                                 }
4711                         };
4712
4713                         {
4714                                 let per_peer_state = self.per_peer_state.read().unwrap();
4715                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4716                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4717                                         let peer_state = &mut *peer_state_lock;
4718                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4719                                         let counterparty_node_id = *counterparty_node_id;
4720                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4721                                                 match phase {
4722                                                         ChannelPhase::Funded(chan) => {
4723                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4724                                                                         anchor_feerate
4725                                                                 } else {
4726                                                                         non_anchor_feerate
4727                                                                 };
4728                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4729                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4730
4731                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4732                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4733                                                                         handle_errors.push((Err(err), counterparty_node_id));
4734                                                                         if needs_close { return false; }
4735                                                                 }
4736
4737                                                                 match chan.channel_update_status() {
4738                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4739                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4740                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4741                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4742                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4743                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4744                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4745                                                                                 n += 1;
4746                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4747                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4748                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4749                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4750                                                                                                         msg: update
4751                                                                                                 });
4752                                                                                         }
4753                                                                                         should_persist = NotifyOption::DoPersist;
4754                                                                                 } else {
4755                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4756                                                                                 }
4757                                                                         },
4758                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4759                                                                                 n += 1;
4760                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4761                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4762                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4763                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4764                                                                                                         msg: update
4765                                                                                                 });
4766                                                                                         }
4767                                                                                         should_persist = NotifyOption::DoPersist;
4768                                                                                 } else {
4769                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4770                                                                                 }
4771                                                                         },
4772                                                                         _ => {},
4773                                                                 }
4774
4775                                                                 chan.context.maybe_expire_prev_config();
4776
4777                                                                 if chan.should_disconnect_peer_awaiting_response() {
4778                                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4779                                                                                         counterparty_node_id, chan_id);
4780                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4781                                                                                 node_id: counterparty_node_id,
4782                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4783                                                                                         msg: msgs::WarningMessage {
4784                                                                                                 channel_id: *chan_id,
4785                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4786                                                                                         },
4787                                                                                 },
4788                                                                         });
4789                                                                 }
4790
4791                                                                 true
4792                                                         },
4793                                                         ChannelPhase::UnfundedInboundV1(chan) => {
4794                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4795                                                                         pending_msg_events, counterparty_node_id)
4796                                                         },
4797                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
4798                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4799                                                                         pending_msg_events, counterparty_node_id)
4800                                                         },
4801                                                 }
4802                                         });
4803
4804                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4805                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4806                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
4807                                                         peer_state.pending_msg_events.push(
4808                                                                 events::MessageSendEvent::HandleError {
4809                                                                         node_id: counterparty_node_id,
4810                                                                         action: msgs::ErrorAction::SendErrorMessage {
4811                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4812                                                                         },
4813                                                                 }
4814                                                         );
4815                                                 }
4816                                         }
4817                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4818
4819                                         if peer_state.ok_to_remove(true) {
4820                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4821                                         }
4822                                 }
4823                         }
4824
4825                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4826                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4827                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4828                         // we therefore need to remove the peer from `peer_state` separately.
4829                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4830                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4831                         // negative effects on parallelism as much as possible.
4832                         if pending_peers_awaiting_removal.len() > 0 {
4833                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4834                                 for counterparty_node_id in pending_peers_awaiting_removal {
4835                                         match per_peer_state.entry(counterparty_node_id) {
4836                                                 hash_map::Entry::Occupied(entry) => {
4837                                                         // Remove the entry if the peer is still disconnected and we still
4838                                                         // have no channels to the peer.
4839                                                         let remove_entry = {
4840                                                                 let peer_state = entry.get().lock().unwrap();
4841                                                                 peer_state.ok_to_remove(true)
4842                                                         };
4843                                                         if remove_entry {
4844                                                                 entry.remove_entry();
4845                                                         }
4846                                                 },
4847                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
4848                                         }
4849                                 }
4850                         }
4851
4852                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
4853                                 if payment.htlcs.is_empty() {
4854                                         // This should be unreachable
4855                                         debug_assert!(false);
4856                                         return false;
4857                                 }
4858                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
4859                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
4860                                         // In this case we're not going to handle any timeouts of the parts here.
4861                                         // This condition determining whether the MPP is complete here must match
4862                                         // exactly the condition used in `process_pending_htlc_forwards`.
4863                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
4864                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
4865                                         {
4866                                                 return true;
4867                                         } else if payment.htlcs.iter_mut().any(|htlc| {
4868                                                 htlc.timer_ticks += 1;
4869                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
4870                                         }) {
4871                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
4872                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
4873                                                 return false;
4874                                         }
4875                                 }
4876                                 true
4877                         });
4878
4879                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
4880                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
4881                                 let reason = HTLCFailReason::from_failure_code(23);
4882                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
4883                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
4884                         }
4885
4886                         for (err, counterparty_node_id) in handle_errors.drain(..) {
4887                                 let _ = handle_error!(self, err, counterparty_node_id);
4888                         }
4889
4890                         for shutdown_res in shutdown_channels {
4891                                 self.finish_close_channel(shutdown_res);
4892                         }
4893
4894                         #[cfg(feature = "std")]
4895                         let duration_since_epoch = std::time::SystemTime::now()
4896                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
4897                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
4898                         #[cfg(not(feature = "std"))]
4899                         let duration_since_epoch = Duration::from_secs(
4900                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
4901                         );
4902
4903                         self.pending_outbound_payments.remove_stale_payments(
4904                                 duration_since_epoch, &self.pending_events
4905                         );
4906
4907                         // Technically we don't need to do this here, but if we have holding cell entries in a
4908                         // channel that need freeing, it's better to do that here and block a background task
4909                         // than block the message queueing pipeline.
4910                         if self.check_free_holding_cells() {
4911                                 should_persist = NotifyOption::DoPersist;
4912                         }
4913
4914                         should_persist
4915                 });
4916         }
4917
4918         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
4919         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
4920         /// along the path (including in our own channel on which we received it).
4921         ///
4922         /// Note that in some cases around unclean shutdown, it is possible the payment may have
4923         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
4924         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
4925         /// may have already been failed automatically by LDK if it was nearing its expiration time.
4926         ///
4927         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
4928         /// [`ChannelManager::claim_funds`]), you should still monitor for
4929         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
4930         /// startup during which time claims that were in-progress at shutdown may be replayed.
4931         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
4932                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
4933         }
4934
4935         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
4936         /// reason for the failure.
4937         ///
4938         /// See [`FailureCode`] for valid failure codes.
4939         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
4940                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4941
4942                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
4943                 if let Some(payment) = removed_source {
4944                         for htlc in payment.htlcs {
4945                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
4946                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4947                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
4948                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4949                         }
4950                 }
4951         }
4952
4953         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
4954         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
4955                 match failure_code {
4956                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
4957                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
4958                         FailureCode::IncorrectOrUnknownPaymentDetails => {
4959                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4960                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4961                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
4962                         },
4963                         FailureCode::InvalidOnionPayload(data) => {
4964                                 let fail_data = match data {
4965                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
4966                                         None => Vec::new(),
4967                                 };
4968                                 HTLCFailReason::reason(failure_code.into(), fail_data)
4969                         }
4970                 }
4971         }
4972
4973         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4974         /// that we want to return and a channel.
4975         ///
4976         /// This is for failures on the channel on which the HTLC was *received*, not failures
4977         /// forwarding
4978         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
4979                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
4980                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
4981                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
4982                 // an inbound SCID alias before the real SCID.
4983                 let scid_pref = if chan.context.should_announce() {
4984                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
4985                 } else {
4986                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
4987                 };
4988                 if let Some(scid) = scid_pref {
4989                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
4990                 } else {
4991                         (0x4000|10, Vec::new())
4992                 }
4993         }
4994
4995
4996         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4997         /// that we want to return and a channel.
4998         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
4999                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5000                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5001                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5002                         if desired_err_code == 0x1000 | 20 {
5003                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5004                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5005                                 0u16.write(&mut enc).expect("Writes cannot fail");
5006                         }
5007                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5008                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5009                         upd.write(&mut enc).expect("Writes cannot fail");
5010                         (desired_err_code, enc.0)
5011                 } else {
5012                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5013                         // which means we really shouldn't have gotten a payment to be forwarded over this
5014                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5015                         // PERM|no_such_channel should be fine.
5016                         (0x4000|10, Vec::new())
5017                 }
5018         }
5019
5020         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5021         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5022         // be surfaced to the user.
5023         fn fail_holding_cell_htlcs(
5024                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5025                 counterparty_node_id: &PublicKey
5026         ) {
5027                 let (failure_code, onion_failure_data) = {
5028                         let per_peer_state = self.per_peer_state.read().unwrap();
5029                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5030                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5031                                 let peer_state = &mut *peer_state_lock;
5032                                 match peer_state.channel_by_id.entry(channel_id) {
5033                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5034                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5035                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5036                                                 } else {
5037                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5038                                                         debug_assert!(false);
5039                                                         (0x4000|10, Vec::new())
5040                                                 }
5041                                         },
5042                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5043                                 }
5044                         } else { (0x4000|10, Vec::new()) }
5045                 };
5046
5047                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5048                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5049                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5050                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5051                 }
5052         }
5053
5054         /// Fails an HTLC backwards to the sender of it to us.
5055         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5056         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5057                 // Ensure that no peer state channel storage lock is held when calling this function.
5058                 // This ensures that future code doesn't introduce a lock-order requirement for
5059                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5060                 // this function with any `per_peer_state` peer lock acquired would.
5061                 #[cfg(debug_assertions)]
5062                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5063                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5064                 }
5065
5066                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5067                 //identify whether we sent it or not based on the (I presume) very different runtime
5068                 //between the branches here. We should make this async and move it into the forward HTLCs
5069                 //timer handling.
5070
5071                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5072                 // from block_connected which may run during initialization prior to the chain_monitor
5073                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5074                 match source {
5075                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5076                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5077                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5078                                         &self.pending_events, &self.logger)
5079                                 { self.push_pending_forwards_ev(); }
5080                         },
5081                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint, .. }) => {
5082                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", &payment_hash, onion_error);
5083                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
5084
5085                                 let mut push_forward_ev = false;
5086                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5087                                 if forward_htlcs.is_empty() {
5088                                         push_forward_ev = true;
5089                                 }
5090                                 match forward_htlcs.entry(*short_channel_id) {
5091                                         hash_map::Entry::Occupied(mut entry) => {
5092                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
5093                                         },
5094                                         hash_map::Entry::Vacant(entry) => {
5095                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
5096                                         }
5097                                 }
5098                                 mem::drop(forward_htlcs);
5099                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5100                                 let mut pending_events = self.pending_events.lock().unwrap();
5101                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5102                                         prev_channel_id: outpoint.to_channel_id(),
5103                                         failed_next_destination: destination,
5104                                 }, None));
5105                         },
5106                 }
5107         }
5108
5109         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5110         /// [`MessageSendEvent`]s needed to claim the payment.
5111         ///
5112         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5113         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5114         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5115         /// successful. It will generally be available in the next [`process_pending_events`] call.
5116         ///
5117         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5118         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5119         /// event matches your expectation. If you fail to do so and call this method, you may provide
5120         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5121         ///
5122         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5123         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5124         /// [`claim_funds_with_known_custom_tlvs`].
5125         ///
5126         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5127         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5128         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5129         /// [`process_pending_events`]: EventsProvider::process_pending_events
5130         /// [`create_inbound_payment`]: Self::create_inbound_payment
5131         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5132         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5133         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5134                 self.claim_payment_internal(payment_preimage, false);
5135         }
5136
5137         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5138         /// even type numbers.
5139         ///
5140         /// # Note
5141         ///
5142         /// You MUST check you've understood all even TLVs before using this to
5143         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5144         ///
5145         /// [`claim_funds`]: Self::claim_funds
5146         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5147                 self.claim_payment_internal(payment_preimage, true);
5148         }
5149
5150         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5151                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5152
5153                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5154
5155                 let mut sources = {
5156                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5157                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5158                                 let mut receiver_node_id = self.our_network_pubkey;
5159                                 for htlc in payment.htlcs.iter() {
5160                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5161                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5162                                                         .expect("Failed to get node_id for phantom node recipient");
5163                                                 receiver_node_id = phantom_pubkey;
5164                                                 break;
5165                                         }
5166                                 }
5167
5168                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5169                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5170                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5171                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5172                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5173                                 });
5174                                 if dup_purpose.is_some() {
5175                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5176                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5177                                                 &payment_hash);
5178                                 }
5179
5180                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5181                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5182                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5183                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5184                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5185                                                 mem::drop(claimable_payments);
5186                                                 for htlc in payment.htlcs {
5187                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5188                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5189                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5190                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5191                                                 }
5192                                                 return;
5193                                         }
5194                                 }
5195
5196                                 payment.htlcs
5197                         } else { return; }
5198                 };
5199                 debug_assert!(!sources.is_empty());
5200
5201                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5202                 // and when we got here we need to check that the amount we're about to claim matches the
5203                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5204                 // the MPP parts all have the same `total_msat`.
5205                 let mut claimable_amt_msat = 0;
5206                 let mut prev_total_msat = None;
5207                 let mut expected_amt_msat = None;
5208                 let mut valid_mpp = true;
5209                 let mut errs = Vec::new();
5210                 let per_peer_state = self.per_peer_state.read().unwrap();
5211                 for htlc in sources.iter() {
5212                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5213                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5214                                 debug_assert!(false);
5215                                 valid_mpp = false;
5216                                 break;
5217                         }
5218                         prev_total_msat = Some(htlc.total_msat);
5219
5220                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5221                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5222                                 debug_assert!(false);
5223                                 valid_mpp = false;
5224                                 break;
5225                         }
5226                         expected_amt_msat = htlc.total_value_received;
5227                         claimable_amt_msat += htlc.value;
5228                 }
5229                 mem::drop(per_peer_state);
5230                 if sources.is_empty() || expected_amt_msat.is_none() {
5231                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5232                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5233                         return;
5234                 }
5235                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5236                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5237                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5238                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5239                         return;
5240                 }
5241                 if valid_mpp {
5242                         for htlc in sources.drain(..) {
5243                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5244                                         htlc.prev_hop, payment_preimage,
5245                                         |_, definitely_duplicate| {
5246                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5247                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5248                                         }
5249                                 ) {
5250                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5251                                                 // We got a temporary failure updating monitor, but will claim the
5252                                                 // HTLC when the monitor updating is restored (or on chain).
5253                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5254                                         } else { errs.push((pk, err)); }
5255                                 }
5256                         }
5257                 }
5258                 if !valid_mpp {
5259                         for htlc in sources.drain(..) {
5260                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5261                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5262                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5263                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5264                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5265                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5266                         }
5267                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5268                 }
5269
5270                 // Now we can handle any errors which were generated.
5271                 for (counterparty_node_id, err) in errs.drain(..) {
5272                         let res: Result<(), _> = Err(err);
5273                         let _ = handle_error!(self, res, counterparty_node_id);
5274                 }
5275         }
5276
5277         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5278                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5279         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5280                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5281
5282                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5283                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5284                 // `BackgroundEvent`s.
5285                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5286
5287                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5288                 // the required mutexes are not held before we start.
5289                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5290                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5291
5292                 {
5293                         let per_peer_state = self.per_peer_state.read().unwrap();
5294                         let chan_id = prev_hop.outpoint.to_channel_id();
5295                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5296                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5297                                 None => None
5298                         };
5299
5300                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5301                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5302                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5303                         ).unwrap_or(None);
5304
5305                         if peer_state_opt.is_some() {
5306                                 let mut peer_state_lock = peer_state_opt.unwrap();
5307                                 let peer_state = &mut *peer_state_lock;
5308                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5309                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5310                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5311                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5312
5313                                                 match fulfill_res {
5314                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5315                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5316                                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5317                                                                                 chan_id, action);
5318                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5319                                                                 }
5320                                                                 if !during_init {
5321                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5322                                                                                 peer_state, per_peer_state, chan);
5323                                                                 } else {
5324                                                                         // If we're running during init we cannot update a monitor directly -
5325                                                                         // they probably haven't actually been loaded yet. Instead, push the
5326                                                                         // monitor update as a background event.
5327                                                                         self.pending_background_events.lock().unwrap().push(
5328                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5329                                                                                         counterparty_node_id,
5330                                                                                         funding_txo: prev_hop.outpoint,
5331                                                                                         update: monitor_update.clone(),
5332                                                                                 });
5333                                                                 }
5334                                                         }
5335                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5336                                                                 let action = if let Some(action) = completion_action(None, true) {
5337                                                                         action
5338                                                                 } else {
5339                                                                         return Ok(());
5340                                                                 };
5341                                                                 mem::drop(peer_state_lock);
5342
5343                                                                 log_trace!(self.logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5344                                                                         chan_id, action);
5345                                                                 let (node_id, funding_outpoint, blocker) =
5346                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5347                                                                         downstream_counterparty_node_id: node_id,
5348                                                                         downstream_funding_outpoint: funding_outpoint,
5349                                                                         blocking_action: blocker,
5350                                                                 } = action {
5351                                                                         (node_id, funding_outpoint, blocker)
5352                                                                 } else {
5353                                                                         debug_assert!(false,
5354                                                                                 "Duplicate claims should always free another channel immediately");
5355                                                                         return Ok(());
5356                                                                 };
5357                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5358                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5359                                                                         if let Some(blockers) = peer_state
5360                                                                                 .actions_blocking_raa_monitor_updates
5361                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5362                                                                         {
5363                                                                                 let mut found_blocker = false;
5364                                                                                 blockers.retain(|iter| {
5365                                                                                         // Note that we could actually be blocked, in
5366                                                                                         // which case we need to only remove the one
5367                                                                                         // blocker which was added duplicatively.
5368                                                                                         let first_blocker = !found_blocker;
5369                                                                                         if *iter == blocker { found_blocker = true; }
5370                                                                                         *iter != blocker || !first_blocker
5371                                                                                 });
5372                                                                                 debug_assert!(found_blocker);
5373                                                                         }
5374                                                                 } else {
5375                                                                         debug_assert!(false);
5376                                                                 }
5377                                                         }
5378                                                 }
5379                                         }
5380                                         return Ok(());
5381                                 }
5382                         }
5383                 }
5384                 let preimage_update = ChannelMonitorUpdate {
5385                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5386                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5387                                 payment_preimage,
5388                         }],
5389                 };
5390
5391                 if !during_init {
5392                         // We update the ChannelMonitor on the backward link, after
5393                         // receiving an `update_fulfill_htlc` from the forward link.
5394                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5395                         if update_res != ChannelMonitorUpdateStatus::Completed {
5396                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5397                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5398                                 // channel, or we must have an ability to receive the same event and try
5399                                 // again on restart.
5400                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5401                                         payment_preimage, update_res);
5402                         }
5403                 } else {
5404                         // If we're running during init we cannot update a monitor directly - they probably
5405                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5406                         // event.
5407                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5408                         // channel is already closed) we need to ultimately handle the monitor update
5409                         // completion action only after we've completed the monitor update. This is the only
5410                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5411                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5412                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5413                         // complete the monitor update completion action from `completion_action`.
5414                         self.pending_background_events.lock().unwrap().push(
5415                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5416                                         prev_hop.outpoint, preimage_update,
5417                                 )));
5418                 }
5419                 // Note that we do process the completion action here. This totally could be a
5420                 // duplicate claim, but we have no way of knowing without interrogating the
5421                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5422                 // generally always allowed to be duplicative (and it's specifically noted in
5423                 // `PaymentForwarded`).
5424                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5425                 Ok(())
5426         }
5427
5428         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5429                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5430         }
5431
5432         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5433                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5434                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5435         ) {
5436                 match source {
5437                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5438                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5439                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5440                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5441                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5442                                 }
5443                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5444                                         channel_funding_outpoint: next_channel_outpoint,
5445                                         counterparty_node_id: path.hops[0].pubkey,
5446                                 };
5447                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5448                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5449                                         &self.logger);
5450                         },
5451                         HTLCSource::PreviousHopData(hop_data) => {
5452                                 let prev_outpoint = hop_data.outpoint;
5453                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5454                                 #[cfg(debug_assertions)]
5455                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5456                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5457                                         |htlc_claim_value_msat, definitely_duplicate| {
5458                                                 let chan_to_release =
5459                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5460                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5461                                                         } else {
5462                                                                 // We can only get `None` here if we are processing a
5463                                                                 // `ChannelMonitor`-originated event, in which case we
5464                                                                 // don't care about ensuring we wake the downstream
5465                                                                 // channel's monitor updating - the channel is already
5466                                                                 // closed.
5467                                                                 None
5468                                                         };
5469
5470                                                 if definitely_duplicate && startup_replay {
5471                                                         // On startup we may get redundant claims which are related to
5472                                                         // monitor updates still in flight. In that case, we shouldn't
5473                                                         // immediately free, but instead let that monitor update complete
5474                                                         // in the background.
5475                                                         #[cfg(debug_assertions)] {
5476                                                                 let background_events = self.pending_background_events.lock().unwrap();
5477                                                                 // There should be a `BackgroundEvent` pending...
5478                                                                 assert!(background_events.iter().any(|ev| {
5479                                                                         match ev {
5480                                                                                 // to apply a monitor update that blocked the claiming channel,
5481                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5482                                                                                         funding_txo, update, ..
5483                                                                                 } => {
5484                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5485                                                                                                 assert!(update.updates.iter().any(|upd|
5486                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5487                                                                                                                 payment_preimage: update_preimage
5488                                                                                                         } = upd {
5489                                                                                                                 payment_preimage == *update_preimage
5490                                                                                                         } else { false }
5491                                                                                                 ), "{:?}", update);
5492                                                                                                 true
5493                                                                                         } else { false }
5494                                                                                 },
5495                                                                                 // or the channel we'd unblock is already closed,
5496                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5497                                                                                         (funding_txo, monitor_update)
5498                                                                                 ) => {
5499                                                                                         if *funding_txo == next_channel_outpoint {
5500                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5501                                                                                                 assert!(matches!(
5502                                                                                                         monitor_update.updates[0],
5503                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5504                                                                                                 ));
5505                                                                                                 true
5506                                                                                         } else { false }
5507                                                                                 },
5508                                                                                 // or the monitor update has completed and will unblock
5509                                                                                 // immediately once we get going.
5510                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5511                                                                                         channel_id, ..
5512                                                                                 } =>
5513                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5514                                                                         }
5515                                                                 }), "{:?}", *background_events);
5516                                                         }
5517                                                         None
5518                                                 } else if definitely_duplicate {
5519                                                         if let Some(other_chan) = chan_to_release {
5520                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5521                                                                         downstream_counterparty_node_id: other_chan.0,
5522                                                                         downstream_funding_outpoint: other_chan.1,
5523                                                                         blocking_action: other_chan.2,
5524                                                                 })
5525                                                         } else { None }
5526                                                 } else {
5527                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5528                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5529                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5530                                                                 } else { None }
5531                                                         } else { None };
5532                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5533                                                                 event: events::Event::PaymentForwarded {
5534                                                                         fee_earned_msat,
5535                                                                         claim_from_onchain_tx: from_onchain,
5536                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5537                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5538                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5539                                                                 },
5540                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5541                                                         })
5542                                                 }
5543                                         });
5544                                 if let Err((pk, err)) = res {
5545                                         let result: Result<(), _> = Err(err);
5546                                         let _ = handle_error!(self, result, pk);
5547                                 }
5548                         },
5549                 }
5550         }
5551
5552         /// Gets the node_id held by this ChannelManager
5553         pub fn get_our_node_id(&self) -> PublicKey {
5554                 self.our_network_pubkey.clone()
5555         }
5556
5557         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5558                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5559                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5560                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5561
5562                 for action in actions.into_iter() {
5563                         match action {
5564                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5565                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5566                                         if let Some(ClaimingPayment {
5567                                                 amount_msat,
5568                                                 payment_purpose: purpose,
5569                                                 receiver_node_id,
5570                                                 htlcs,
5571                                                 sender_intended_value: sender_intended_total_msat,
5572                                         }) = payment {
5573                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5574                                                         payment_hash,
5575                                                         purpose,
5576                                                         amount_msat,
5577                                                         receiver_node_id: Some(receiver_node_id),
5578                                                         htlcs,
5579                                                         sender_intended_total_msat,
5580                                                 }, None));
5581                                         }
5582                                 },
5583                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5584                                         event, downstream_counterparty_and_funding_outpoint
5585                                 } => {
5586                                         self.pending_events.lock().unwrap().push_back((event, None));
5587                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5588                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5589                                         }
5590                                 },
5591                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5592                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5593                                 } => {
5594                                         self.handle_monitor_update_release(
5595                                                 downstream_counterparty_node_id,
5596                                                 downstream_funding_outpoint,
5597                                                 Some(blocking_action),
5598                                         );
5599                                 },
5600                         }
5601                 }
5602         }
5603
5604         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5605         /// update completion.
5606         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5607                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5608                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5609                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5610                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5611         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5612                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5613                         &channel.context.channel_id(),
5614                         if raa.is_some() { "an" } else { "no" },
5615                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5616                         if funding_broadcastable.is_some() { "" } else { "not " },
5617                         if channel_ready.is_some() { "sending" } else { "without" },
5618                         if announcement_sigs.is_some() { "sending" } else { "without" });
5619
5620                 let mut htlc_forwards = None;
5621
5622                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5623                 if !pending_forwards.is_empty() {
5624                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5625                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5626                 }
5627
5628                 if let Some(msg) = channel_ready {
5629                         send_channel_ready!(self, pending_msg_events, channel, msg);
5630                 }
5631                 if let Some(msg) = announcement_sigs {
5632                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5633                                 node_id: counterparty_node_id,
5634                                 msg,
5635                         });
5636                 }
5637
5638                 macro_rules! handle_cs { () => {
5639                         if let Some(update) = commitment_update {
5640                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5641                                         node_id: counterparty_node_id,
5642                                         updates: update,
5643                                 });
5644                         }
5645                 } }
5646                 macro_rules! handle_raa { () => {
5647                         if let Some(revoke_and_ack) = raa {
5648                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5649                                         node_id: counterparty_node_id,
5650                                         msg: revoke_and_ack,
5651                                 });
5652                         }
5653                 } }
5654                 match order {
5655                         RAACommitmentOrder::CommitmentFirst => {
5656                                 handle_cs!();
5657                                 handle_raa!();
5658                         },
5659                         RAACommitmentOrder::RevokeAndACKFirst => {
5660                                 handle_raa!();
5661                                 handle_cs!();
5662                         },
5663                 }
5664
5665                 if let Some(tx) = funding_broadcastable {
5666                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5667                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5668                 }
5669
5670                 {
5671                         let mut pending_events = self.pending_events.lock().unwrap();
5672                         emit_channel_pending_event!(pending_events, channel);
5673                         emit_channel_ready_event!(pending_events, channel);
5674                 }
5675
5676                 htlc_forwards
5677         }
5678
5679         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5680                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5681
5682                 let counterparty_node_id = match counterparty_node_id {
5683                         Some(cp_id) => cp_id.clone(),
5684                         None => {
5685                                 // TODO: Once we can rely on the counterparty_node_id from the
5686                                 // monitor event, this and the id_to_peer map should be removed.
5687                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5688                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5689                                         Some(cp_id) => cp_id.clone(),
5690                                         None => return,
5691                                 }
5692                         }
5693                 };
5694                 let per_peer_state = self.per_peer_state.read().unwrap();
5695                 let mut peer_state_lock;
5696                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5697                 if peer_state_mutex_opt.is_none() { return }
5698                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5699                 let peer_state = &mut *peer_state_lock;
5700                 let channel =
5701                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5702                                 chan
5703                         } else {
5704                                 let update_actions = peer_state.monitor_update_blocked_actions
5705                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5706                                 mem::drop(peer_state_lock);
5707                                 mem::drop(per_peer_state);
5708                                 self.handle_monitor_update_completion_actions(update_actions);
5709                                 return;
5710                         };
5711                 let remaining_in_flight =
5712                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5713                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5714                                 pending.len()
5715                         } else { 0 };
5716                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5717                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5718                         remaining_in_flight);
5719                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5720                         return;
5721                 }
5722                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5723         }
5724
5725         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5726         ///
5727         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5728         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5729         /// the channel.
5730         ///
5731         /// The `user_channel_id` parameter will be provided back in
5732         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5733         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5734         ///
5735         /// Note that this method will return an error and reject the channel, if it requires support
5736         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5737         /// used to accept such channels.
5738         ///
5739         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5740         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5741         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5742                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5743         }
5744
5745         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5746         /// it as confirmed immediately.
5747         ///
5748         /// The `user_channel_id` parameter will be provided back in
5749         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5750         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5751         ///
5752         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5753         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5754         ///
5755         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5756         /// transaction and blindly assumes that it will eventually confirm.
5757         ///
5758         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5759         /// does not pay to the correct script the correct amount, *you will lose funds*.
5760         ///
5761         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5762         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5763         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5764                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5765         }
5766
5767         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5768                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5769
5770                 let peers_without_funded_channels =
5771                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5772                 let per_peer_state = self.per_peer_state.read().unwrap();
5773                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5774                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5775                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5776                 let peer_state = &mut *peer_state_lock;
5777                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5778
5779                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5780                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5781                 // that we can delay allocating the SCID until after we're sure that the checks below will
5782                 // succeed.
5783                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5784                         Some(unaccepted_channel) => {
5785                                 let best_block_height = self.best_block.read().unwrap().height();
5786                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5787                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5788                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5789                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5790                         }
5791                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5792                 }?;
5793
5794                 if accept_0conf {
5795                         // This should have been correctly configured by the call to InboundV1Channel::new.
5796                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5797                 } else if channel.context.get_channel_type().requires_zero_conf() {
5798                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5799                                 node_id: channel.context.get_counterparty_node_id(),
5800                                 action: msgs::ErrorAction::SendErrorMessage{
5801                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5802                                 }
5803                         };
5804                         peer_state.pending_msg_events.push(send_msg_err_event);
5805                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5806                 } else {
5807                         // If this peer already has some channels, a new channel won't increase our number of peers
5808                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5809                         // channels per-peer we can accept channels from a peer with existing ones.
5810                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5811                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5812                                         node_id: channel.context.get_counterparty_node_id(),
5813                                         action: msgs::ErrorAction::SendErrorMessage{
5814                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5815                                         }
5816                                 };
5817                                 peer_state.pending_msg_events.push(send_msg_err_event);
5818                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5819                         }
5820                 }
5821
5822                 // Now that we know we have a channel, assign an outbound SCID alias.
5823                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5824                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5825
5826                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5827                         node_id: channel.context.get_counterparty_node_id(),
5828                         msg: channel.accept_inbound_channel(),
5829                 });
5830
5831                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
5832
5833                 Ok(())
5834         }
5835
5836         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5837         /// or 0-conf channels.
5838         ///
5839         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
5840         /// non-0-conf channels we have with the peer.
5841         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
5842         where Filter: Fn(&PeerState<SP>) -> bool {
5843                 let mut peers_without_funded_channels = 0;
5844                 let best_block_height = self.best_block.read().unwrap().height();
5845                 {
5846                         let peer_state_lock = self.per_peer_state.read().unwrap();
5847                         for (_, peer_mtx) in peer_state_lock.iter() {
5848                                 let peer = peer_mtx.lock().unwrap();
5849                                 if !maybe_count_peer(&*peer) { continue; }
5850                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
5851                                 if num_unfunded_channels == peer.total_channel_count() {
5852                                         peers_without_funded_channels += 1;
5853                                 }
5854                         }
5855                 }
5856                 return peers_without_funded_channels;
5857         }
5858
5859         fn unfunded_channel_count(
5860                 peer: &PeerState<SP>, best_block_height: u32
5861         ) -> usize {
5862                 let mut num_unfunded_channels = 0;
5863                 for (_, phase) in peer.channel_by_id.iter() {
5864                         match phase {
5865                                 ChannelPhase::Funded(chan) => {
5866                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
5867                                         // which have not yet had any confirmations on-chain.
5868                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
5869                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
5870                                         {
5871                                                 num_unfunded_channels += 1;
5872                                         }
5873                                 },
5874                                 ChannelPhase::UnfundedInboundV1(chan) => {
5875                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
5876                                                 num_unfunded_channels += 1;
5877                                         }
5878                                 },
5879                                 ChannelPhase::UnfundedOutboundV1(_) => {
5880                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
5881                                         continue;
5882                                 }
5883                         }
5884                 }
5885                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
5886         }
5887
5888         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
5889                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
5890                 // likely to be lost on restart!
5891                 if msg.chain_hash != self.chain_hash {
5892                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
5893                 }
5894
5895                 if !self.default_configuration.accept_inbound_channels {
5896                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5897                 }
5898
5899                 // Get the number of peers with channels, but without funded ones. We don't care too much
5900                 // about peers that never open a channel, so we filter by peers that have at least one
5901                 // channel, and then limit the number of those with unfunded channels.
5902                 let channeled_peers_without_funding =
5903                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
5904
5905                 let per_peer_state = self.per_peer_state.read().unwrap();
5906                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5907                     .ok_or_else(|| {
5908                                 debug_assert!(false);
5909                                 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())
5910                         })?;
5911                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5912                 let peer_state = &mut *peer_state_lock;
5913
5914                 // If this peer already has some channels, a new channel won't increase our number of peers
5915                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5916                 // channels per-peer we can accept channels from a peer with existing ones.
5917                 if peer_state.total_channel_count() == 0 &&
5918                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
5919                         !self.default_configuration.manually_accept_inbound_channels
5920                 {
5921                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5922                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
5923                                 msg.temporary_channel_id.clone()));
5924                 }
5925
5926                 let best_block_height = self.best_block.read().unwrap().height();
5927                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
5928                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5929                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
5930                                 msg.temporary_channel_id.clone()));
5931                 }
5932
5933                 let channel_id = msg.temporary_channel_id;
5934                 let channel_exists = peer_state.has_channel(&channel_id);
5935                 if channel_exists {
5936                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
5937                 }
5938
5939                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
5940                 if self.default_configuration.manually_accept_inbound_channels {
5941                         let mut pending_events = self.pending_events.lock().unwrap();
5942                         pending_events.push_back((events::Event::OpenChannelRequest {
5943                                 temporary_channel_id: msg.temporary_channel_id.clone(),
5944                                 counterparty_node_id: counterparty_node_id.clone(),
5945                                 funding_satoshis: msg.funding_satoshis,
5946                                 push_msat: msg.push_msat,
5947                                 channel_type: msg.channel_type.clone().unwrap(),
5948                         }, None));
5949                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
5950                                 open_channel_msg: msg.clone(),
5951                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
5952                         });
5953                         return Ok(());
5954                 }
5955
5956                 // Otherwise create the channel right now.
5957                 let mut random_bytes = [0u8; 16];
5958                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
5959                 let user_channel_id = u128::from_be_bytes(random_bytes);
5960                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5961                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
5962                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
5963                 {
5964                         Err(e) => {
5965                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
5966                         },
5967                         Ok(res) => res
5968                 };
5969
5970                 let channel_type = channel.context.get_channel_type();
5971                 if channel_type.requires_zero_conf() {
5972                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5973                 }
5974                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
5975                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
5976                 }
5977
5978                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5979                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5980
5981                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5982                         node_id: counterparty_node_id.clone(),
5983                         msg: channel.accept_inbound_channel(),
5984                 });
5985                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
5986                 Ok(())
5987         }
5988
5989         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
5990                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
5991                 // likely to be lost on restart!
5992                 let (value, output_script, user_id) = {
5993                         let per_peer_state = self.per_peer_state.read().unwrap();
5994                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5995                                 .ok_or_else(|| {
5996                                         debug_assert!(false);
5997                                         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)
5998                                 })?;
5999                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6000                         let peer_state = &mut *peer_state_lock;
6001                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6002                                 hash_map::Entry::Occupied(mut phase) => {
6003                                         match phase.get_mut() {
6004                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6005                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6006                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6007                                                 },
6008                                                 _ => {
6009                                                         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));
6010                                                 }
6011                                         }
6012                                 },
6013                                 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))
6014                         }
6015                 };
6016                 let mut pending_events = self.pending_events.lock().unwrap();
6017                 pending_events.push_back((events::Event::FundingGenerationReady {
6018                         temporary_channel_id: msg.temporary_channel_id,
6019                         counterparty_node_id: *counterparty_node_id,
6020                         channel_value_satoshis: value,
6021                         output_script,
6022                         user_channel_id: user_id,
6023                 }, None));
6024                 Ok(())
6025         }
6026
6027         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6028                 let best_block = *self.best_block.read().unwrap();
6029
6030                 let per_peer_state = self.per_peer_state.read().unwrap();
6031                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6032                         .ok_or_else(|| {
6033                                 debug_assert!(false);
6034                                 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)
6035                         })?;
6036
6037                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6038                 let peer_state = &mut *peer_state_lock;
6039                 let (chan, funding_msg, monitor) =
6040                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6041                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6042                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
6043                                                 Ok(res) => res,
6044                                                 Err((mut inbound_chan, err)) => {
6045                                                         // We've already removed this inbound channel from the map in `PeerState`
6046                                                         // above so at this point we just need to clean up any lingering entries
6047                                                         // concerning this channel as it is safe to do so.
6048                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
6049                                                         let user_id = inbound_chan.context.get_user_id();
6050                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
6051                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
6052                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
6053                                                 },
6054                                         }
6055                                 },
6056                                 Some(ChannelPhase::Funded(_)) | Some(ChannelPhase::UnfundedOutboundV1(_)) => {
6057                                         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));
6058                                 },
6059                                 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))
6060                         };
6061
6062                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
6063                         hash_map::Entry::Occupied(_) => {
6064                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
6065                         },
6066                         hash_map::Entry::Vacant(e) => {
6067                                 let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
6068                                 match id_to_peer_lock.entry(chan.context.channel_id()) {
6069                                         hash_map::Entry::Occupied(_) => {
6070                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
6071                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6072                                                         funding_msg.channel_id))
6073                                         },
6074                                         hash_map::Entry::Vacant(i_e) => {
6075                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6076                                                 if let Ok(persist_state) = monitor_res {
6077                                                         i_e.insert(chan.context.get_counterparty_node_id());
6078                                                         mem::drop(id_to_peer_lock);
6079
6080                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6081                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6082                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6083                                                         // until we have persisted our monitor.
6084                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6085                                                                 node_id: counterparty_node_id.clone(),
6086                                                                 msg: funding_msg,
6087                                                         });
6088
6089                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6090                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6091                                                                         per_peer_state, chan, INITIAL_MONITOR);
6092                                                         } else {
6093                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6094                                                         }
6095                                                         Ok(())
6096                                                 } else {
6097                                                         log_error!(self.logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6098                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6099                                                                 "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6100                                                                 funding_msg.channel_id));
6101                                                 }
6102                                         }
6103                                 }
6104                         }
6105                 }
6106         }
6107
6108         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6109                 let best_block = *self.best_block.read().unwrap();
6110                 let per_peer_state = self.per_peer_state.read().unwrap();
6111                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6112                         .ok_or_else(|| {
6113                                 debug_assert!(false);
6114                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6115                         })?;
6116
6117                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6118                 let peer_state = &mut *peer_state_lock;
6119                 match peer_state.channel_by_id.entry(msg.channel_id) {
6120                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6121                                 match chan_phase_entry.get_mut() {
6122                                         ChannelPhase::Funded(ref mut chan) => {
6123                                                 let monitor = try_chan_phase_entry!(self,
6124                                                         chan.funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan_phase_entry);
6125                                                 if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6126                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6127                                                         Ok(())
6128                                                 } else {
6129                                                         try_chan_phase_entry!(self, Err(ChannelError::Close("Channel funding outpoint was a duplicate".to_owned())), chan_phase_entry)
6130                                                 }
6131                                         },
6132                                         _ => {
6133                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6134                                         },
6135                                 }
6136                         },
6137                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6138                 }
6139         }
6140
6141         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6142                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6143                 // closing a channel), so any changes are likely to be lost on restart!
6144                 let per_peer_state = self.per_peer_state.read().unwrap();
6145                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6146                         .ok_or_else(|| {
6147                                 debug_assert!(false);
6148                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6149                         })?;
6150                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6151                 let peer_state = &mut *peer_state_lock;
6152                 match peer_state.channel_by_id.entry(msg.channel_id) {
6153                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6154                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6155                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6156                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
6157                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6158                                                 log_trace!(self.logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6159                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6160                                                         node_id: counterparty_node_id.clone(),
6161                                                         msg: announcement_sigs,
6162                                                 });
6163                                         } else if chan.context.is_usable() {
6164                                                 // If we're sending an announcement_signatures, we'll send the (public)
6165                                                 // channel_update after sending a channel_announcement when we receive our
6166                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6167                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6168                                                 // announcement_signatures.
6169                                                 log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6170                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6171                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6172                                                                 node_id: counterparty_node_id.clone(),
6173                                                                 msg,
6174                                                         });
6175                                                 }
6176                                         }
6177
6178                                         {
6179                                                 let mut pending_events = self.pending_events.lock().unwrap();
6180                                                 emit_channel_ready_event!(pending_events, chan);
6181                                         }
6182
6183                                         Ok(())
6184                                 } else {
6185                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6186                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6187                                 }
6188                         },
6189                         hash_map::Entry::Vacant(_) => {
6190                                 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))
6191                         }
6192                 }
6193         }
6194
6195         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6196                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6197                 let mut finish_shutdown = None;
6198                 {
6199                         let per_peer_state = self.per_peer_state.read().unwrap();
6200                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6201                                 .ok_or_else(|| {
6202                                         debug_assert!(false);
6203                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6204                                 })?;
6205                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6206                         let peer_state = &mut *peer_state_lock;
6207                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6208                                 let phase = chan_phase_entry.get_mut();
6209                                 match phase {
6210                                         ChannelPhase::Funded(chan) => {
6211                                                 if !chan.received_shutdown() {
6212                                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
6213                                                                 msg.channel_id,
6214                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6215                                                 }
6216
6217                                                 let funding_txo_opt = chan.context.get_funding_txo();
6218                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6219                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6220                                                 dropped_htlcs = htlcs;
6221
6222                                                 if let Some(msg) = shutdown {
6223                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6224                                                         // here as we don't need the monitor update to complete until we send a
6225                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6226                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6227                                                                 node_id: *counterparty_node_id,
6228                                                                 msg,
6229                                                         });
6230                                                 }
6231                                                 // Update the monitor with the shutdown script if necessary.
6232                                                 if let Some(monitor_update) = monitor_update_opt {
6233                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6234                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6235                                                 }
6236                                         },
6237                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6238                                                 let context = phase.context_mut();
6239                                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6240                                                 self.issue_channel_close_events(&context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
6241                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6242                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false));
6243                                         },
6244                                 }
6245                         } else {
6246                                 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))
6247                         }
6248                 }
6249                 for htlc_source in dropped_htlcs.drain(..) {
6250                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6251                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6252                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6253                 }
6254                 if let Some(shutdown_res) = finish_shutdown {
6255                         self.finish_close_channel(shutdown_res);
6256                 }
6257
6258                 Ok(())
6259         }
6260
6261         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6262                 let per_peer_state = self.per_peer_state.read().unwrap();
6263                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6264                         .ok_or_else(|| {
6265                                 debug_assert!(false);
6266                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6267                         })?;
6268                 let (tx, chan_option, shutdown_result) = {
6269                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6270                         let peer_state = &mut *peer_state_lock;
6271                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6272                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6273                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6274                                                 let (closing_signed, tx, shutdown_result) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6275                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
6276                                                 if let Some(msg) = closing_signed {
6277                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6278                                                                 node_id: counterparty_node_id.clone(),
6279                                                                 msg,
6280                                                         });
6281                                                 }
6282                                                 if tx.is_some() {
6283                                                         // We're done with this channel, we've got a signed closing transaction and
6284                                                         // will send the closing_signed back to the remote peer upon return. This
6285                                                         // also implies there are no pending HTLCs left on the channel, so we can
6286                                                         // fully delete it from tracking (the channel monitor is still around to
6287                                                         // watch for old state broadcasts)!
6288                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)), shutdown_result)
6289                                                 } else { (tx, None, shutdown_result) }
6290                                         } else {
6291                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6292                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6293                                         }
6294                                 },
6295                                 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))
6296                         }
6297                 };
6298                 if let Some(broadcast_tx) = tx {
6299                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
6300                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6301                 }
6302                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6303                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6304                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6305                                 let peer_state = &mut *peer_state_lock;
6306                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6307                                         msg: update
6308                                 });
6309                         }
6310                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6311                 }
6312                 mem::drop(per_peer_state);
6313                 if let Some(shutdown_result) = shutdown_result {
6314                         self.finish_close_channel(shutdown_result);
6315                 }
6316                 Ok(())
6317         }
6318
6319         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6320                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6321                 //determine the state of the payment based on our response/if we forward anything/the time
6322                 //we take to respond. We should take care to avoid allowing such an attack.
6323                 //
6324                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6325                 //us repeatedly garbled in different ways, and compare our error messages, which are
6326                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6327                 //but we should prevent it anyway.
6328
6329                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6330                 // closing a channel), so any changes are likely to be lost on restart!
6331
6332                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
6333                 let per_peer_state = self.per_peer_state.read().unwrap();
6334                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6335                         .ok_or_else(|| {
6336                                 debug_assert!(false);
6337                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6338                         })?;
6339                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6340                 let peer_state = &mut *peer_state_lock;
6341                 match peer_state.channel_by_id.entry(msg.channel_id) {
6342                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6343                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6344                                         let pending_forward_info = match decoded_hop_res {
6345                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6346                                                         self.construct_pending_htlc_status(msg, shared_secret, next_hop,
6347                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt),
6348                                                 Err(e) => PendingHTLCStatus::Fail(e)
6349                                         };
6350                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6351                                                 // If the update_add is completely bogus, the call will Err and we will close,
6352                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6353                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6354                                                 match pending_forward_info {
6355                                                         PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
6356                                                                 let reason = if (error_code & 0x1000) != 0 {
6357                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6358                                                                         HTLCFailReason::reason(real_code, error_data)
6359                                                                 } else {
6360                                                                         HTLCFailReason::from_failure_code(error_code)
6361                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6362                                                                 let msg = msgs::UpdateFailHTLC {
6363                                                                         channel_id: msg.channel_id,
6364                                                                         htlc_id: msg.htlc_id,
6365                                                                         reason
6366                                                                 };
6367                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6368                                                         },
6369                                                         _ => pending_forward_info
6370                                                 }
6371                                         };
6372                                         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);
6373                                 } else {
6374                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6375                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6376                                 }
6377                         },
6378                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6379                 }
6380                 Ok(())
6381         }
6382
6383         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6384                 let funding_txo;
6385                 let (htlc_source, forwarded_htlc_value) = {
6386                         let per_peer_state = self.per_peer_state.read().unwrap();
6387                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6388                                 .ok_or_else(|| {
6389                                         debug_assert!(false);
6390                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6391                                 })?;
6392                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6393                         let peer_state = &mut *peer_state_lock;
6394                         match peer_state.channel_by_id.entry(msg.channel_id) {
6395                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6396                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6397                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6398                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6399                                                         log_trace!(self.logger,
6400                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6401                                                                 msg.channel_id);
6402                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6403                                                                 .or_insert_with(Vec::new)
6404                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6405                                                 }
6406                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6407                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6408                                                 // We do this instead in the `claim_funds_internal` by attaching a
6409                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6410                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6411                                                 // process the RAA as messages are processed from single peers serially.
6412                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6413                                                 res
6414                                         } else {
6415                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6416                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6417                                         }
6418                                 },
6419                                 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))
6420                         }
6421                 };
6422                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6423                 Ok(())
6424         }
6425
6426         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6427                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6428                 // closing a channel), so any changes are likely to be lost on restart!
6429                 let per_peer_state = self.per_peer_state.read().unwrap();
6430                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6431                         .ok_or_else(|| {
6432                                 debug_assert!(false);
6433                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6434                         })?;
6435                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6436                 let peer_state = &mut *peer_state_lock;
6437                 match peer_state.channel_by_id.entry(msg.channel_id) {
6438                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6439                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6440                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6441                                 } else {
6442                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6443                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6444                                 }
6445                         },
6446                         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))
6447                 }
6448                 Ok(())
6449         }
6450
6451         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6452                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6453                 // closing a channel), so any changes are likely to be lost on restart!
6454                 let per_peer_state = self.per_peer_state.read().unwrap();
6455                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6456                         .ok_or_else(|| {
6457                                 debug_assert!(false);
6458                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6459                         })?;
6460                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6461                 let peer_state = &mut *peer_state_lock;
6462                 match peer_state.channel_by_id.entry(msg.channel_id) {
6463                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6464                                 if (msg.failure_code & 0x8000) == 0 {
6465                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6466                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6467                                 }
6468                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6469                                         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);
6470                                 } else {
6471                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6472                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6473                                 }
6474                                 Ok(())
6475                         },
6476                         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))
6477                 }
6478         }
6479
6480         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6481                 let per_peer_state = self.per_peer_state.read().unwrap();
6482                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6483                         .ok_or_else(|| {
6484                                 debug_assert!(false);
6485                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6486                         })?;
6487                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6488                 let peer_state = &mut *peer_state_lock;
6489                 match peer_state.channel_by_id.entry(msg.channel_id) {
6490                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6491                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6492                                         let funding_txo = chan.context.get_funding_txo();
6493                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &self.logger), chan_phase_entry);
6494                                         if let Some(monitor_update) = monitor_update_opt {
6495                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6496                                                         peer_state, per_peer_state, chan);
6497                                         }
6498                                         Ok(())
6499                                 } else {
6500                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6501                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6502                                 }
6503                         },
6504                         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))
6505                 }
6506         }
6507
6508         #[inline]
6509         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6510                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6511                         let mut push_forward_event = false;
6512                         let mut new_intercept_events = VecDeque::new();
6513                         let mut failed_intercept_forwards = Vec::new();
6514                         if !pending_forwards.is_empty() {
6515                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6516                                         let scid = match forward_info.routing {
6517                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6518                                                 PendingHTLCRouting::Receive { .. } => 0,
6519                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6520                                         };
6521                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6522                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6523
6524                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6525                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6526                                         match forward_htlcs.entry(scid) {
6527                                                 hash_map::Entry::Occupied(mut entry) => {
6528                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6529                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6530                                                 },
6531                                                 hash_map::Entry::Vacant(entry) => {
6532                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6533                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6534                                                         {
6535                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6536                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6537                                                                 match pending_intercepts.entry(intercept_id) {
6538                                                                         hash_map::Entry::Vacant(entry) => {
6539                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6540                                                                                         requested_next_hop_scid: scid,
6541                                                                                         payment_hash: forward_info.payment_hash,
6542                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6543                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6544                                                                                         intercept_id
6545                                                                                 }, None));
6546                                                                                 entry.insert(PendingAddHTLCInfo {
6547                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6548                                                                         },
6549                                                                         hash_map::Entry::Occupied(_) => {
6550                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6551                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6552                                                                                         short_channel_id: prev_short_channel_id,
6553                                                                                         user_channel_id: Some(prev_user_channel_id),
6554                                                                                         outpoint: prev_funding_outpoint,
6555                                                                                         htlc_id: prev_htlc_id,
6556                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6557                                                                                         phantom_shared_secret: None,
6558                                                                                 });
6559
6560                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6561                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6562                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6563                                                                                 ));
6564                                                                         }
6565                                                                 }
6566                                                         } else {
6567                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6568                                                                 // payments are being processed.
6569                                                                 if forward_htlcs_empty {
6570                                                                         push_forward_event = true;
6571                                                                 }
6572                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6573                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6574                                                         }
6575                                                 }
6576                                         }
6577                                 }
6578                         }
6579
6580                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6581                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6582                         }
6583
6584                         if !new_intercept_events.is_empty() {
6585                                 let mut events = self.pending_events.lock().unwrap();
6586                                 events.append(&mut new_intercept_events);
6587                         }
6588                         if push_forward_event { self.push_pending_forwards_ev() }
6589                 }
6590         }
6591
6592         fn push_pending_forwards_ev(&self) {
6593                 let mut pending_events = self.pending_events.lock().unwrap();
6594                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6595                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6596                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6597                 ).count();
6598                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6599                 // events is done in batches and they are not removed until we're done processing each
6600                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6601                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6602                 // payments will need an additional forwarding event before being claimed to make them look
6603                 // real by taking more time.
6604                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6605                         pending_events.push_back((Event::PendingHTLCsForwardable {
6606                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6607                         }, None));
6608                 }
6609         }
6610
6611         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6612         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6613         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6614         /// the [`ChannelMonitorUpdate`] in question.
6615         fn raa_monitor_updates_held(&self,
6616                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6617                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6618         ) -> bool {
6619                 actions_blocking_raa_monitor_updates
6620                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6621                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6622                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6623                                 channel_funding_outpoint,
6624                                 counterparty_node_id,
6625                         })
6626                 })
6627         }
6628
6629         #[cfg(any(test, feature = "_test_utils"))]
6630         pub(crate) fn test_raa_monitor_updates_held(&self,
6631                 counterparty_node_id: PublicKey, channel_id: ChannelId
6632         ) -> bool {
6633                 let per_peer_state = self.per_peer_state.read().unwrap();
6634                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6635                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6636                         let peer_state = &mut *peer_state_lck;
6637
6638                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6639                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6640                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6641                         }
6642                 }
6643                 false
6644         }
6645
6646         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6647                 let htlcs_to_fail = {
6648                         let per_peer_state = self.per_peer_state.read().unwrap();
6649                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6650                                 .ok_or_else(|| {
6651                                         debug_assert!(false);
6652                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6653                                 }).map(|mtx| mtx.lock().unwrap())?;
6654                         let peer_state = &mut *peer_state_lock;
6655                         match peer_state.channel_by_id.entry(msg.channel_id) {
6656                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6657                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6658                                                 let funding_txo_opt = chan.context.get_funding_txo();
6659                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6660                                                         self.raa_monitor_updates_held(
6661                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6662                                                                 *counterparty_node_id)
6663                                                 } else { false };
6664                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
6665                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &self.logger, mon_update_blocked), chan_phase_entry);
6666                                                 if let Some(monitor_update) = monitor_update_opt {
6667                                                         let funding_txo = funding_txo_opt
6668                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
6669                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
6670                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6671                                                 }
6672                                                 htlcs_to_fail
6673                                         } else {
6674                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6675                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
6676                                         }
6677                                 },
6678                                 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))
6679                         }
6680                 };
6681                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6682                 Ok(())
6683         }
6684
6685         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6686                 let per_peer_state = self.per_peer_state.read().unwrap();
6687                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6688                         .ok_or_else(|| {
6689                                 debug_assert!(false);
6690                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6691                         })?;
6692                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6693                 let peer_state = &mut *peer_state_lock;
6694                 match peer_state.channel_by_id.entry(msg.channel_id) {
6695                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6696                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6697                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &self.logger), chan_phase_entry);
6698                                 } else {
6699                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6700                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
6701                                 }
6702                         },
6703                         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))
6704                 }
6705                 Ok(())
6706         }
6707
6708         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6709                 let per_peer_state = self.per_peer_state.read().unwrap();
6710                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6711                         .ok_or_else(|| {
6712                                 debug_assert!(false);
6713                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6714                         })?;
6715                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6716                 let peer_state = &mut *peer_state_lock;
6717                 match peer_state.channel_by_id.entry(msg.channel_id) {
6718                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6719                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6720                                         if !chan.context.is_usable() {
6721                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6722                                         }
6723
6724                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6725                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6726                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
6727                                                         msg, &self.default_configuration
6728                                                 ), chan_phase_entry),
6729                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6730                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6731                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
6732                                         });
6733                                 } else {
6734                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6735                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
6736                                 }
6737                         },
6738                         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))
6739                 }
6740                 Ok(())
6741         }
6742
6743         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
6744         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6745                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6746                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6747                         None => {
6748                                 // It's not a local channel
6749                                 return Ok(NotifyOption::SkipPersistNoEvents)
6750                         }
6751                 };
6752                 let per_peer_state = self.per_peer_state.read().unwrap();
6753                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6754                 if peer_state_mutex_opt.is_none() {
6755                         return Ok(NotifyOption::SkipPersistNoEvents)
6756                 }
6757                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6758                 let peer_state = &mut *peer_state_lock;
6759                 match peer_state.channel_by_id.entry(chan_id) {
6760                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6761                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6762                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
6763                                                 if chan.context.should_announce() {
6764                                                         // If the announcement is about a channel of ours which is public, some
6765                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
6766                                                         // a scary-looking error message and return Ok instead.
6767                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6768                                                 }
6769                                                 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));
6770                                         }
6771                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
6772                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
6773                                         if were_node_one == msg_from_node_one {
6774                                                 return Ok(NotifyOption::SkipPersistNoEvents);
6775                                         } else {
6776                                                 log_debug!(self.logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
6777                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
6778                                                 // If nothing changed after applying their update, we don't need to bother
6779                                                 // persisting.
6780                                                 if !did_change {
6781                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6782                                                 }
6783                                         }
6784                                 } else {
6785                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6786                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
6787                                 }
6788                         },
6789                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
6790                 }
6791                 Ok(NotifyOption::DoPersist)
6792         }
6793
6794         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
6795                 let htlc_forwards;
6796                 let need_lnd_workaround = {
6797                         let per_peer_state = self.per_peer_state.read().unwrap();
6798
6799                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6800                                 .ok_or_else(|| {
6801                                         debug_assert!(false);
6802                                         MsgHandleErrInternal::send_err_msg_no_close(
6803                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6804                                                 msg.channel_id
6805                                         )
6806                                 })?;
6807                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6808                         let peer_state = &mut *peer_state_lock;
6809                         match peer_state.channel_by_id.entry(msg.channel_id) {
6810                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6811                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6812                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
6813                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
6814                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
6815                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6816                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
6817                                                         msg, &self.logger, &self.node_signer, self.chain_hash,
6818                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
6819                                                 let mut channel_update = None;
6820                                                 if let Some(msg) = responses.shutdown_msg {
6821                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6822                                                                 node_id: counterparty_node_id.clone(),
6823                                                                 msg,
6824                                                         });
6825                                                 } else if chan.context.is_usable() {
6826                                                         // If the channel is in a usable state (ie the channel is not being shut
6827                                                         // down), send a unicast channel_update to our counterparty to make sure
6828                                                         // they have the latest channel parameters.
6829                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6830                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
6831                                                                         node_id: chan.context.get_counterparty_node_id(),
6832                                                                         msg,
6833                                                                 });
6834                                                         }
6835                                                 }
6836                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
6837                                                 htlc_forwards = self.handle_channel_resumption(
6838                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
6839                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
6840                                                 if let Some(upd) = channel_update {
6841                                                         peer_state.pending_msg_events.push(upd);
6842                                                 }
6843                                                 need_lnd_workaround
6844                                         } else {
6845                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6846                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
6847                                         }
6848                                 },
6849                                 hash_map::Entry::Vacant(_) => {
6850                                         log_debug!(self.logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
6851                                                 log_bytes!(msg.channel_id.0));
6852                                         // Unfortunately, lnd doesn't force close on errors
6853                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
6854                                         // One of the few ways to get an lnd counterparty to force close is by
6855                                         // replicating what they do when restoring static channel backups (SCBs). They
6856                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
6857                                         // invalid `your_last_per_commitment_secret`.
6858                                         //
6859                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
6860                                         // can assume it's likely the channel closed from our point of view, but it
6861                                         // remains open on the counterparty's side. By sending this bogus
6862                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
6863                                         // force close broadcasting their latest state. If the closing transaction from
6864                                         // our point of view remains unconfirmed, it'll enter a race with the
6865                                         // counterparty's to-be-broadcast latest commitment transaction.
6866                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
6867                                                 node_id: *counterparty_node_id,
6868                                                 msg: msgs::ChannelReestablish {
6869                                                         channel_id: msg.channel_id,
6870                                                         next_local_commitment_number: 0,
6871                                                         next_remote_commitment_number: 0,
6872                                                         your_last_per_commitment_secret: [1u8; 32],
6873                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
6874                                                         next_funding_txid: None,
6875                                                 },
6876                                         });
6877                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6878                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
6879                                                         counterparty_node_id), msg.channel_id)
6880                                         )
6881                                 }
6882                         }
6883                 };
6884
6885                 let mut persist = NotifyOption::SkipPersistHandleEvents;
6886                 if let Some(forwards) = htlc_forwards {
6887                         self.forward_htlcs(&mut [forwards][..]);
6888                         persist = NotifyOption::DoPersist;
6889                 }
6890
6891                 if let Some(channel_ready_msg) = need_lnd_workaround {
6892                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
6893                 }
6894                 Ok(persist)
6895         }
6896
6897         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
6898         fn process_pending_monitor_events(&self) -> bool {
6899                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
6900
6901                 let mut failed_channels = Vec::new();
6902                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
6903                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
6904                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
6905                         for monitor_event in monitor_events.drain(..) {
6906                                 match monitor_event {
6907                                         MonitorEvent::HTLCEvent(htlc_update) => {
6908                                                 if let Some(preimage) = htlc_update.payment_preimage {
6909                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", preimage);
6910                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
6911                                                 } else {
6912                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
6913                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
6914                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6915                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
6916                                                 }
6917                                         },
6918                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
6919                                                 let counterparty_node_id_opt = match counterparty_node_id {
6920                                                         Some(cp_id) => Some(cp_id),
6921                                                         None => {
6922                                                                 // TODO: Once we can rely on the counterparty_node_id from the
6923                                                                 // monitor event, this and the id_to_peer map should be removed.
6924                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
6925                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
6926                                                         }
6927                                                 };
6928                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
6929                                                         let per_peer_state = self.per_peer_state.read().unwrap();
6930                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
6931                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6932                                                                 let peer_state = &mut *peer_state_lock;
6933                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6934                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
6935                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
6936                                                                                 failed_channels.push(chan.context.force_shutdown(false));
6937                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6938                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6939                                                                                                 msg: update
6940                                                                                         });
6941                                                                                 }
6942                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
6943                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
6944                                                                                         node_id: chan.context.get_counterparty_node_id(),
6945                                                                                         action: msgs::ErrorAction::DisconnectPeer {
6946                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
6947                                                                                         },
6948                                                                                 });
6949                                                                         }
6950                                                                 }
6951                                                         }
6952                                                 }
6953                                         },
6954                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
6955                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
6956                                         },
6957                                 }
6958                         }
6959                 }
6960
6961                 for failure in failed_channels.drain(..) {
6962                         self.finish_close_channel(failure);
6963                 }
6964
6965                 has_pending_monitor_events
6966         }
6967
6968         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
6969         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
6970         /// update events as a separate process method here.
6971         #[cfg(fuzzing)]
6972         pub fn process_monitor_events(&self) {
6973                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6974                 self.process_pending_monitor_events();
6975         }
6976
6977         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
6978         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
6979         /// update was applied.
6980         fn check_free_holding_cells(&self) -> bool {
6981                 let mut has_monitor_update = false;
6982                 let mut failed_htlcs = Vec::new();
6983
6984                 // Walk our list of channels and find any that need to update. Note that when we do find an
6985                 // update, if it includes actions that must be taken afterwards, we have to drop the
6986                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
6987                 // manage to go through all our peers without finding a single channel to update.
6988                 'peer_loop: loop {
6989                         let per_peer_state = self.per_peer_state.read().unwrap();
6990                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6991                                 'chan_loop: loop {
6992                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6993                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
6994                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
6995                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
6996                                         ) {
6997                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
6998                                                 let funding_txo = chan.context.get_funding_txo();
6999                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7000                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
7001                                                 if !holding_cell_failed_htlcs.is_empty() {
7002                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7003                                                 }
7004                                                 if let Some(monitor_update) = monitor_opt {
7005                                                         has_monitor_update = true;
7006
7007                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7008                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7009                                                         continue 'peer_loop;
7010                                                 }
7011                                         }
7012                                         break 'chan_loop;
7013                                 }
7014                         }
7015                         break 'peer_loop;
7016                 }
7017
7018                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7019                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7020                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7021                 }
7022
7023                 has_update
7024         }
7025
7026         /// Check whether any channels have finished removing all pending updates after a shutdown
7027         /// exchange and can now send a closing_signed.
7028         /// Returns whether any closing_signed messages were generated.
7029         fn maybe_generate_initial_closing_signed(&self) -> bool {
7030                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7031                 let mut has_update = false;
7032                 let mut shutdown_results = Vec::new();
7033                 {
7034                         let per_peer_state = self.per_peer_state.read().unwrap();
7035
7036                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7037                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7038                                 let peer_state = &mut *peer_state_lock;
7039                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7040                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7041                                         match phase {
7042                                                 ChannelPhase::Funded(chan) => {
7043                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
7044                                                                 Ok((msg_opt, tx_opt, shutdown_result_opt)) => {
7045                                                                         if let Some(msg) = msg_opt {
7046                                                                                 has_update = true;
7047                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7048                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7049                                                                                 });
7050                                                                         }
7051                                                                         debug_assert_eq!(shutdown_result_opt.is_some(), chan.is_shutdown());
7052                                                                         if let Some(shutdown_result) = shutdown_result_opt {
7053                                                                                 shutdown_results.push(shutdown_result);
7054                                                                         }
7055                                                                         if let Some(tx) = tx_opt {
7056                                                                                 // We're done with this channel. We got a closing_signed and sent back
7057                                                                                 // a closing_signed with a closing transaction to broadcast.
7058                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7059                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7060                                                                                                 msg: update
7061                                                                                         });
7062                                                                                 }
7063
7064                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
7065
7066                                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
7067                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7068                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7069                                                                                 false
7070                                                                         } else { true }
7071                                                                 },
7072                                                                 Err(e) => {
7073                                                                         has_update = true;
7074                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7075                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7076                                                                         !close_channel
7077                                                                 }
7078                                                         }
7079                                                 },
7080                                                 _ => true, // Retain unfunded channels if present.
7081                                         }
7082                                 });
7083                         }
7084                 }
7085
7086                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7087                         let _ = handle_error!(self, err, counterparty_node_id);
7088                 }
7089
7090                 for shutdown_result in shutdown_results.drain(..) {
7091                         self.finish_close_channel(shutdown_result);
7092                 }
7093
7094                 has_update
7095         }
7096
7097         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7098         /// pushing the channel monitor update (if any) to the background events queue and removing the
7099         /// Channel object.
7100         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7101                 for mut failure in failed_channels.drain(..) {
7102                         // Either a commitment transactions has been confirmed on-chain or
7103                         // Channel::block_disconnected detected that the funding transaction has been
7104                         // reorganized out of the main chain.
7105                         // We cannot broadcast our latest local state via monitor update (as
7106                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7107                         // so we track the update internally and handle it when the user next calls
7108                         // timer_tick_occurred, guaranteeing we're running normally.
7109                         if let Some((counterparty_node_id, funding_txo, update)) = failure.monitor_update.take() {
7110                                 assert_eq!(update.updates.len(), 1);
7111                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7112                                         assert!(should_broadcast);
7113                                 } else { unreachable!(); }
7114                                 self.pending_background_events.lock().unwrap().push(
7115                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7116                                                 counterparty_node_id, funding_txo, update
7117                                         });
7118                         }
7119                         self.finish_close_channel(failure);
7120                 }
7121         }
7122
7123         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7124         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7125         /// not have an expiration unless otherwise set on the builder.
7126         ///
7127         /// # Privacy
7128         ///
7129         /// Uses a one-hop [`BlindedPath`] for the offer with [`ChannelManager::get_our_node_id`] as the
7130         /// introduction node and a derived signing pubkey for recipient privacy. As such, currently,
7131         /// the node must be announced. Otherwise, there is no way to find a path to the introduction
7132         /// node in order to send the [`InvoiceRequest`].
7133         ///
7134         /// # Limitations
7135         ///
7136         /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
7137         /// reply path.
7138         ///
7139         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7140         ///
7141         /// [`Offer`]: crate::offers::offer::Offer
7142         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7143         pub fn create_offer_builder(
7144                 &self, description: String
7145         ) -> OfferBuilder<DerivedMetadata, secp256k1::All> {
7146                 let node_id = self.get_our_node_id();
7147                 let expanded_key = &self.inbound_payment_key;
7148                 let entropy = &*self.entropy_source;
7149                 let secp_ctx = &self.secp_ctx;
7150                 let path = self.create_one_hop_blinded_path();
7151
7152                 OfferBuilder::deriving_signing_pubkey(description, node_id, expanded_key, entropy, secp_ctx)
7153                         .chain_hash(self.chain_hash)
7154                         .path(path)
7155         }
7156
7157         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7158         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7159         ///
7160         /// # Payment
7161         ///
7162         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7163         /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
7164         ///
7165         /// The builder will have the provided expiration set. Any changes to the expiration on the
7166         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7167         /// block time minus two hours is used for the current time when determining if the refund has
7168         /// expired.
7169         ///
7170         /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
7171         /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
7172         /// with an [`Event::InvoiceRequestFailed`].
7173         ///
7174         /// If `max_total_routing_fee_msat` is not specified, The default from
7175         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7176         ///
7177         /// # Privacy
7178         ///
7179         /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
7180         /// the introduction node and a derived payer id for payer privacy. As such, currently, the
7181         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7182         /// in order to send the [`Bolt12Invoice`].
7183         ///
7184         /// # Limitations
7185         ///
7186         /// Requires a direct connection to an introduction node in the responding
7187         /// [`Bolt12Invoice::payment_paths`].
7188         ///
7189         /// # Errors
7190         ///
7191         /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link
7192         /// or if `amount_msats` is invalid.
7193         ///
7194         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7195         ///
7196         /// [`Refund`]: crate::offers::refund::Refund
7197         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7198         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7199         pub fn create_refund_builder(
7200                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7201                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7202         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7203                 let node_id = self.get_our_node_id();
7204                 let expanded_key = &self.inbound_payment_key;
7205                 let entropy = &*self.entropy_source;
7206                 let secp_ctx = &self.secp_ctx;
7207                 let path = self.create_one_hop_blinded_path();
7208
7209                 let builder = RefundBuilder::deriving_payer_id(
7210                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7211                 )?
7212                         .chain_hash(self.chain_hash)
7213                         .absolute_expiry(absolute_expiry)
7214                         .path(path);
7215
7216                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7217                 self.pending_outbound_payments
7218                         .add_new_awaiting_invoice(
7219                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7220                         )
7221                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7222
7223                 Ok(builder)
7224         }
7225
7226         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7227         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7228         /// [`Bolt12Invoice`] once it is received.
7229         ///
7230         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7231         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7232         /// The optional parameters are used in the builder, if `Some`:
7233         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7234         ///   [`Offer::expects_quantity`] is `true`.
7235         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7236         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7237         ///
7238         /// If `max_total_routing_fee_msat` is not specified, The default from
7239         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7240         ///
7241         /// # Payment
7242         ///
7243         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7244         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7245         /// been sent.
7246         ///
7247         /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
7248         /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
7249         /// payment will fail with an [`Event::InvoiceRequestFailed`].
7250         ///
7251         /// # Privacy
7252         ///
7253         /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
7254         /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
7255         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7256         /// in order to send the [`Bolt12Invoice`].
7257         ///
7258         /// # Limitations
7259         ///
7260         /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
7261         /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
7262         /// [`Bolt12Invoice::payment_paths`].
7263         ///
7264         /// # Errors
7265         ///
7266         /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link
7267         /// or if the provided parameters are invalid for the offer.
7268         ///
7269         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7270         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7271         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7272         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7273         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7274         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7275         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7276         pub fn pay_for_offer(
7277                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7278                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7279                 max_total_routing_fee_msat: Option<u64>
7280         ) -> Result<(), Bolt12SemanticError> {
7281                 let expanded_key = &self.inbound_payment_key;
7282                 let entropy = &*self.entropy_source;
7283                 let secp_ctx = &self.secp_ctx;
7284
7285                 let builder = offer
7286                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7287                         .chain_hash(self.chain_hash)?;
7288                 let builder = match quantity {
7289                         None => builder,
7290                         Some(quantity) => builder.quantity(quantity)?,
7291                 };
7292                 let builder = match amount_msats {
7293                         None => builder,
7294                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7295                 };
7296                 let builder = match payer_note {
7297                         None => builder,
7298                         Some(payer_note) => builder.payer_note(payer_note),
7299                 };
7300
7301                 let invoice_request = builder.build_and_sign()?;
7302                 let reply_path = self.create_one_hop_blinded_path();
7303
7304                 let expiration = StaleExpiration::TimerTicks(1);
7305                 self.pending_outbound_payments
7306                         .add_new_awaiting_invoice(
7307                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7308                         )
7309                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7310
7311                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7312                 if offer.paths().is_empty() {
7313                         let message = new_pending_onion_message(
7314                                 OffersMessage::InvoiceRequest(invoice_request),
7315                                 Destination::Node(offer.signing_pubkey()),
7316                                 Some(reply_path),
7317                         );
7318                         pending_offers_messages.push(message);
7319                 } else {
7320                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7321                         // Using only one path could result in a failure if the path no longer exists. But only
7322                         // one invoice for a given payment id will be paid, even if more than one is received.
7323                         const REQUEST_LIMIT: usize = 10;
7324                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7325                                 let message = new_pending_onion_message(
7326                                         OffersMessage::InvoiceRequest(invoice_request.clone()),
7327                                         Destination::BlindedPath(path.clone()),
7328                                         Some(reply_path.clone()),
7329                                 );
7330                                 pending_offers_messages.push(message);
7331                         }
7332                 }
7333
7334                 Ok(())
7335         }
7336
7337         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7338         /// message.
7339         ///
7340         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7341         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7342         /// [`PaymentPreimage`].
7343         ///
7344         /// # Limitations
7345         ///
7346         /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
7347         /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
7348         /// node meeting the aforementioned criteria, but there's no guarantee that they will be
7349         /// received and no retries will be made.
7350         ///
7351         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7352         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7353                 let expanded_key = &self.inbound_payment_key;
7354                 let entropy = &*self.entropy_source;
7355                 let secp_ctx = &self.secp_ctx;
7356
7357                 let amount_msats = refund.amount_msats();
7358                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7359
7360                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7361                         Ok((payment_hash, payment_secret)) => {
7362                                 let payment_paths = vec![
7363                                         self.create_one_hop_blinded_payment_path(payment_secret),
7364                                 ];
7365                                 #[cfg(not(feature = "no-std"))]
7366                                 let builder = refund.respond_using_derived_keys(
7367                                         payment_paths, payment_hash, expanded_key, entropy
7368                                 )?;
7369                                 #[cfg(feature = "no-std")]
7370                                 let created_at = Duration::from_secs(
7371                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7372                                 );
7373                                 #[cfg(feature = "no-std")]
7374                                 let builder = refund.respond_using_derived_keys_no_std(
7375                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7376                                 )?;
7377                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7378                                 let reply_path = self.create_one_hop_blinded_path();
7379
7380                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7381                                 if refund.paths().is_empty() {
7382                                         let message = new_pending_onion_message(
7383                                                 OffersMessage::Invoice(invoice),
7384                                                 Destination::Node(refund.payer_id()),
7385                                                 Some(reply_path),
7386                                         );
7387                                         pending_offers_messages.push(message);
7388                                 } else {
7389                                         for path in refund.paths() {
7390                                                 let message = new_pending_onion_message(
7391                                                         OffersMessage::Invoice(invoice.clone()),
7392                                                         Destination::BlindedPath(path.clone()),
7393                                                         Some(reply_path.clone()),
7394                                                 );
7395                                                 pending_offers_messages.push(message);
7396                                         }
7397                                 }
7398
7399                                 Ok(())
7400                         },
7401                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7402                 }
7403         }
7404
7405         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7406         /// to pay us.
7407         ///
7408         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7409         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7410         ///
7411         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7412         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7413         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7414         /// passed directly to [`claim_funds`].
7415         ///
7416         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7417         ///
7418         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7419         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7420         ///
7421         /// # Note
7422         ///
7423         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7424         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7425         ///
7426         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7427         ///
7428         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7429         /// on versions of LDK prior to 0.0.114.
7430         ///
7431         /// [`claim_funds`]: Self::claim_funds
7432         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7433         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7434         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7435         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7436         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7437         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7438                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7439                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7440                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7441                         min_final_cltv_expiry_delta)
7442         }
7443
7444         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7445         /// stored external to LDK.
7446         ///
7447         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7448         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7449         /// the `min_value_msat` provided here, if one is provided.
7450         ///
7451         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7452         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7453         /// payments.
7454         ///
7455         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7456         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7457         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7458         /// sender "proof-of-payment" unless they have paid the required amount.
7459         ///
7460         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7461         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7462         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7463         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7464         /// invoices when no timeout is set.
7465         ///
7466         /// Note that we use block header time to time-out pending inbound payments (with some margin
7467         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7468         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7469         /// If you need exact expiry semantics, you should enforce them upon receipt of
7470         /// [`PaymentClaimable`].
7471         ///
7472         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7473         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7474         ///
7475         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7476         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7477         ///
7478         /// # Note
7479         ///
7480         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7481         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7482         ///
7483         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7484         ///
7485         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7486         /// on versions of LDK prior to 0.0.114.
7487         ///
7488         /// [`create_inbound_payment`]: Self::create_inbound_payment
7489         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7490         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7491                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7492                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7493                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7494                         min_final_cltv_expiry)
7495         }
7496
7497         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7498         /// previously returned from [`create_inbound_payment`].
7499         ///
7500         /// [`create_inbound_payment`]: Self::create_inbound_payment
7501         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7502                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7503         }
7504
7505         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7506         /// node.
7507         fn create_one_hop_blinded_path(&self) -> BlindedPath {
7508                 let entropy_source = self.entropy_source.deref();
7509                 let secp_ctx = &self.secp_ctx;
7510                 BlindedPath::one_hop_for_message(self.get_our_node_id(), entropy_source, secp_ctx).unwrap()
7511         }
7512
7513         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7514         /// node.
7515         fn create_one_hop_blinded_payment_path(
7516                 &self, payment_secret: PaymentSecret
7517         ) -> (BlindedPayInfo, BlindedPath) {
7518                 let entropy_source = self.entropy_source.deref();
7519                 let secp_ctx = &self.secp_ctx;
7520
7521                 let payee_node_id = self.get_our_node_id();
7522                 let max_cltv_expiry = self.best_block.read().unwrap().height() + LATENCY_GRACE_PERIOD_BLOCKS;
7523                 let payee_tlvs = ReceiveTlvs {
7524                         payment_secret,
7525                         payment_constraints: PaymentConstraints {
7526                                 max_cltv_expiry,
7527                                 htlc_minimum_msat: 1,
7528                         },
7529                 };
7530                 // TODO: Err for overflow?
7531                 BlindedPath::one_hop_for_payment(
7532                         payee_node_id, payee_tlvs, entropy_source, secp_ctx
7533                 ).unwrap()
7534         }
7535
7536         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
7537         /// are used when constructing the phantom invoice's route hints.
7538         ///
7539         /// [phantom node payments]: crate::sign::PhantomKeysManager
7540         pub fn get_phantom_scid(&self) -> u64 {
7541                 let best_block_height = self.best_block.read().unwrap().height();
7542                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7543                 loop {
7544                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7545                         // Ensure the generated scid doesn't conflict with a real channel.
7546                         match short_to_chan_info.get(&scid_candidate) {
7547                                 Some(_) => continue,
7548                                 None => return scid_candidate
7549                         }
7550                 }
7551         }
7552
7553         /// Gets route hints for use in receiving [phantom node payments].
7554         ///
7555         /// [phantom node payments]: crate::sign::PhantomKeysManager
7556         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
7557                 PhantomRouteHints {
7558                         channels: self.list_usable_channels(),
7559                         phantom_scid: self.get_phantom_scid(),
7560                         real_node_pubkey: self.get_our_node_id(),
7561                 }
7562         }
7563
7564         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
7565         /// used when constructing the route hints for HTLCs intended to be intercepted. See
7566         /// [`ChannelManager::forward_intercepted_htlc`].
7567         ///
7568         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
7569         /// times to get a unique scid.
7570         pub fn get_intercept_scid(&self) -> u64 {
7571                 let best_block_height = self.best_block.read().unwrap().height();
7572                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7573                 loop {
7574                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7575                         // Ensure the generated scid doesn't conflict with a real channel.
7576                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
7577                         return scid_candidate
7578                 }
7579         }
7580
7581         /// Gets inflight HTLC information by processing pending outbound payments that are in
7582         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
7583         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
7584                 let mut inflight_htlcs = InFlightHtlcs::new();
7585
7586                 let per_peer_state = self.per_peer_state.read().unwrap();
7587                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7588                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7589                         let peer_state = &mut *peer_state_lock;
7590                         for chan in peer_state.channel_by_id.values().filter_map(
7591                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7592                         ) {
7593                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
7594                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
7595                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
7596                                         }
7597                                 }
7598                         }
7599                 }
7600
7601                 inflight_htlcs
7602         }
7603
7604         #[cfg(any(test, feature = "_test_utils"))]
7605         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
7606                 let events = core::cell::RefCell::new(Vec::new());
7607                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
7608                 self.process_pending_events(&event_handler);
7609                 events.into_inner()
7610         }
7611
7612         #[cfg(feature = "_test_utils")]
7613         pub fn push_pending_event(&self, event: events::Event) {
7614                 let mut events = self.pending_events.lock().unwrap();
7615                 events.push_back((event, None));
7616         }
7617
7618         #[cfg(test)]
7619         pub fn pop_pending_event(&self) -> Option<events::Event> {
7620                 let mut events = self.pending_events.lock().unwrap();
7621                 events.pop_front().map(|(e, _)| e)
7622         }
7623
7624         #[cfg(test)]
7625         pub fn has_pending_payments(&self) -> bool {
7626                 self.pending_outbound_payments.has_pending_payments()
7627         }
7628
7629         #[cfg(test)]
7630         pub fn clear_pending_payments(&self) {
7631                 self.pending_outbound_payments.clear_pending_payments()
7632         }
7633
7634         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
7635         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
7636         /// operation. It will double-check that nothing *else* is also blocking the same channel from
7637         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
7638         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
7639                 loop {
7640                         let per_peer_state = self.per_peer_state.read().unwrap();
7641                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7642                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7643                                 let peer_state = &mut *peer_state_lck;
7644
7645                                 if let Some(blocker) = completed_blocker.take() {
7646                                         // Only do this on the first iteration of the loop.
7647                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
7648                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
7649                                         {
7650                                                 blockers.retain(|iter| iter != &blocker);
7651                                         }
7652                                 }
7653
7654                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7655                                         channel_funding_outpoint, counterparty_node_id) {
7656                                         // Check that, while holding the peer lock, we don't have anything else
7657                                         // blocking monitor updates for this channel. If we do, release the monitor
7658                                         // update(s) when those blockers complete.
7659                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
7660                                                 &channel_funding_outpoint.to_channel_id());
7661                                         break;
7662                                 }
7663
7664                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
7665                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7666                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
7667                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
7668                                                         log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
7669                                                                 channel_funding_outpoint.to_channel_id());
7670                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
7671                                                                 peer_state_lck, peer_state, per_peer_state, chan);
7672                                                         if further_update_exists {
7673                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
7674                                                                 // top of the loop.
7675                                                                 continue;
7676                                                         }
7677                                                 } else {
7678                                                         log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
7679                                                                 channel_funding_outpoint.to_channel_id());
7680                                                 }
7681                                         }
7682                                 }
7683                         } else {
7684                                 log_debug!(self.logger,
7685                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
7686                                         log_pubkey!(counterparty_node_id));
7687                         }
7688                         break;
7689                 }
7690         }
7691
7692         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
7693                 for action in actions {
7694                         match action {
7695                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7696                                         channel_funding_outpoint, counterparty_node_id
7697                                 } => {
7698                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
7699                                 }
7700                         }
7701                 }
7702         }
7703
7704         /// Processes any events asynchronously in the order they were generated since the last call
7705         /// using the given event handler.
7706         ///
7707         /// See the trait-level documentation of [`EventsProvider`] for requirements.
7708         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
7709                 &self, handler: H
7710         ) {
7711                 let mut ev;
7712                 process_events_body!(self, ev, { handler(ev).await });
7713         }
7714 }
7715
7716 fn create_fwd_pending_htlc_info(
7717         msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
7718         new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
7719         next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
7720 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
7721         debug_assert!(next_packet_pubkey_opt.is_some());
7722         let outgoing_packet = msgs::OnionPacket {
7723                 version: 0,
7724                 public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
7725                 hop_data: new_packet_bytes,
7726                 hmac: hop_hmac,
7727         };
7728
7729         let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
7730                 msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
7731                         (short_channel_id, amt_to_forward, outgoing_cltv_value),
7732                 msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
7733                         return Err(InboundOnionErr {
7734                                 msg: "Final Node OnionHopData provided for us as an intermediary node",
7735                                 err_code: 0x4000 | 22,
7736                                 err_data: Vec::new(),
7737                         }),
7738         };
7739
7740         Ok(PendingHTLCInfo {
7741                 routing: PendingHTLCRouting::Forward {
7742                         onion_packet: outgoing_packet,
7743                         short_channel_id,
7744                 },
7745                 payment_hash: msg.payment_hash,
7746                 incoming_shared_secret: shared_secret,
7747                 incoming_amt_msat: Some(msg.amount_msat),
7748                 outgoing_amt_msat: amt_to_forward,
7749                 outgoing_cltv_value,
7750                 skimmed_fee_msat: None,
7751         })
7752 }
7753
7754 fn create_recv_pending_htlc_info(
7755         hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
7756         amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
7757         counterparty_skimmed_fee_msat: Option<u64>, current_height: u32, accept_mpp_keysend: bool,
7758 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
7759         let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
7760                 msgs::InboundOnionPayload::Receive {
7761                         payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
7762                 } =>
7763                         (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
7764                 msgs::InboundOnionPayload::BlindedReceive {
7765                         amt_msat, total_msat, outgoing_cltv_value, payment_secret, ..
7766                 } => {
7767                         let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
7768                         (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
7769                 }
7770                 msgs::InboundOnionPayload::Forward { .. } => {
7771                         return Err(InboundOnionErr {
7772                                 err_code: 0x4000|22,
7773                                 err_data: Vec::new(),
7774                                 msg: "Got non final data with an HMAC of 0",
7775                         })
7776                 },
7777         };
7778         // final_incorrect_cltv_expiry
7779         if outgoing_cltv_value > cltv_expiry {
7780                 return Err(InboundOnionErr {
7781                         msg: "Upstream node set CLTV to less than the CLTV set by the sender",
7782                         err_code: 18,
7783                         err_data: cltv_expiry.to_be_bytes().to_vec()
7784                 })
7785         }
7786         // final_expiry_too_soon
7787         // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
7788         // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
7789         //
7790         // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
7791         // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
7792         // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
7793         if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
7794                 let mut err_data = Vec::with_capacity(12);
7795                 err_data.extend_from_slice(&amt_msat.to_be_bytes());
7796                 err_data.extend_from_slice(&current_height.to_be_bytes());
7797                 return Err(InboundOnionErr {
7798                         err_code: 0x4000 | 15, err_data,
7799                         msg: "The final CLTV expiry is too soon to handle",
7800                 });
7801         }
7802         if (!allow_underpay && onion_amt_msat > amt_msat) ||
7803                 (allow_underpay && onion_amt_msat >
7804                  amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
7805         {
7806                 return Err(InboundOnionErr {
7807                         err_code: 19,
7808                         err_data: amt_msat.to_be_bytes().to_vec(),
7809                         msg: "Upstream node sent less than we were supposed to receive in payment",
7810                 });
7811         }
7812
7813         let routing = if let Some(payment_preimage) = keysend_preimage {
7814                 // We need to check that the sender knows the keysend preimage before processing this
7815                 // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
7816                 // could discover the final destination of X, by probing the adjacent nodes on the route
7817                 // with a keysend payment of identical payment hash to X and observing the processing
7818                 // time discrepancies due to a hash collision with X.
7819                 let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
7820                 if hashed_preimage != payment_hash {
7821                         return Err(InboundOnionErr {
7822                                 err_code: 0x4000|22,
7823                                 err_data: Vec::new(),
7824                                 msg: "Payment preimage didn't match payment hash",
7825                         });
7826                 }
7827                 if !accept_mpp_keysend && payment_data.is_some() {
7828                         return Err(InboundOnionErr {
7829                                 err_code: 0x4000|22,
7830                                 err_data: Vec::new(),
7831                                 msg: "We don't support MPP keysend payments",
7832                         });
7833                 }
7834                 PendingHTLCRouting::ReceiveKeysend {
7835                         payment_data,
7836                         payment_preimage,
7837                         payment_metadata,
7838                         incoming_cltv_expiry: outgoing_cltv_value,
7839                         custom_tlvs,
7840                 }
7841         } else if let Some(data) = payment_data {
7842                 PendingHTLCRouting::Receive {
7843                         payment_data: data,
7844                         payment_metadata,
7845                         incoming_cltv_expiry: outgoing_cltv_value,
7846                         phantom_shared_secret,
7847                         custom_tlvs,
7848                 }
7849         } else {
7850                 return Err(InboundOnionErr {
7851                         err_code: 0x4000|0x2000|3,
7852                         err_data: Vec::new(),
7853                         msg: "We require payment_secrets",
7854                 });
7855         };
7856         Ok(PendingHTLCInfo {
7857                 routing,
7858                 payment_hash,
7859                 incoming_shared_secret: shared_secret,
7860                 incoming_amt_msat: Some(amt_msat),
7861                 outgoing_amt_msat: onion_amt_msat,
7862                 outgoing_cltv_value,
7863                 skimmed_fee_msat: counterparty_skimmed_fee_msat,
7864         })
7865 }
7866
7867 /// Peel one layer off an incoming onion, returning [`PendingHTLCInfo`] (either Forward or Receive).
7868 /// This does all the relevant context-free checks that LDK requires for payment relay or
7869 /// acceptance. If the payment is to be received, and the amount matches the expected amount for
7870 /// a given invoice, this indicates the [`msgs::UpdateAddHTLC`], once fully committed in the
7871 /// channel, will generate an [`Event::PaymentClaimable`].
7872 pub fn peel_payment_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
7873         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
7874         cur_height: u32, accept_mpp_keysend: bool,
7875 ) -> Result<PendingHTLCInfo, InboundOnionErr>
7876 where
7877         NS::Target: NodeSigner,
7878         L::Target: Logger,
7879 {
7880         let (hop, shared_secret, next_packet_details_opt) =
7881                 decode_incoming_update_add_htlc_onion(msg, node_signer, logger, secp_ctx
7882         ).map_err(|e| {
7883                 let (err_code, err_data) = match e {
7884                         HTLCFailureMsg::Malformed(m) => (m.failure_code, Vec::new()),
7885                         HTLCFailureMsg::Relay(r) => (0x4000 | 22, r.reason.data),
7886                 };
7887                 let msg = "Failed to decode update add htlc onion";
7888                 InboundOnionErr { msg, err_code, err_data }
7889         })?;
7890         Ok(match hop {
7891                 onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
7892                         let NextPacketDetails {
7893                                 next_packet_pubkey, outgoing_amt_msat: _, outgoing_scid: _, outgoing_cltv_value
7894                         } = match next_packet_details_opt {
7895                                 Some(next_packet_details) => next_packet_details,
7896                                 // Forward should always include the next hop details
7897                                 None => return Err(InboundOnionErr {
7898                                         msg: "Failed to decode update add htlc onion",
7899                                         err_code: 0x4000 | 22,
7900                                         err_data: Vec::new(),
7901                                 }),
7902                         };
7903
7904                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
7905                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
7906                         ) {
7907                                 return Err(InboundOnionErr {
7908                                         msg: err_msg,
7909                                         err_code: code,
7910                                         err_data: Vec::new(),
7911                                 });
7912                         }
7913                         create_fwd_pending_htlc_info(
7914                                 msg, next_hop_data, next_hop_hmac, new_packet_bytes, shared_secret,
7915                                 Some(next_packet_pubkey)
7916                         )?
7917                 },
7918                 onion_utils::Hop::Receive(received_data) => {
7919                         create_recv_pending_htlc_info(
7920                                 received_data, shared_secret, msg.payment_hash, msg.amount_msat, msg.cltv_expiry,
7921                                 None, false, msg.skimmed_fee_msat, cur_height, accept_mpp_keysend,
7922                         )?
7923                 }
7924         })
7925 }
7926
7927 struct NextPacketDetails {
7928         next_packet_pubkey: Result<PublicKey, secp256k1::Error>,
7929         outgoing_scid: u64,
7930         outgoing_amt_msat: u64,
7931         outgoing_cltv_value: u32,
7932 }
7933
7934 fn decode_incoming_update_add_htlc_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
7935         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
7936 ) -> Result<(onion_utils::Hop, [u8; 32], Option<NextPacketDetails>), HTLCFailureMsg>
7937 where
7938         NS::Target: NodeSigner,
7939         L::Target: Logger,
7940 {
7941         macro_rules! return_malformed_err {
7942                 ($msg: expr, $err_code: expr) => {
7943                         {
7944                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
7945                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7946                                         channel_id: msg.channel_id,
7947                                         htlc_id: msg.htlc_id,
7948                                         sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
7949                                         failure_code: $err_code,
7950                                 }));
7951                         }
7952                 }
7953         }
7954
7955         if let Err(_) = msg.onion_routing_packet.public_key {
7956                 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
7957         }
7958
7959         let shared_secret = node_signer.ecdh(
7960                 Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
7961         ).unwrap().secret_bytes();
7962
7963         if msg.onion_routing_packet.version != 0 {
7964                 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
7965                 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
7966                 //the hash doesn't really serve any purpose - in the case of hashing all data, the
7967                 //receiving node would have to brute force to figure out which version was put in the
7968                 //packet by the node that send us the message, in the case of hashing the hop_data, the
7969                 //node knows the HMAC matched, so they already know what is there...
7970                 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
7971         }
7972         macro_rules! return_err {
7973                 ($msg: expr, $err_code: expr, $data: expr) => {
7974                         {
7975                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
7976                                 return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
7977                                         channel_id: msg.channel_id,
7978                                         htlc_id: msg.htlc_id,
7979                                         reason: HTLCFailReason::reason($err_code, $data.to_vec())
7980                                                 .get_encrypted_failure_packet(&shared_secret, &None),
7981                                 }));
7982                         }
7983                 }
7984         }
7985
7986         let next_hop = match onion_utils::decode_next_payment_hop(
7987                 shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
7988                 msg.payment_hash, node_signer
7989         ) {
7990                 Ok(res) => res,
7991                 Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
7992                         return_malformed_err!(err_msg, err_code);
7993                 },
7994                 Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
7995                         return_err!(err_msg, err_code, &[0; 0]);
7996                 },
7997         };
7998
7999         let next_packet_details = match next_hop {
8000                 onion_utils::Hop::Forward {
8001                         next_hop_data: msgs::InboundOnionPayload::Forward {
8002                                 short_channel_id, amt_to_forward, outgoing_cltv_value
8003                         }, ..
8004                 } => {
8005                         let next_packet_pubkey = onion_utils::next_hop_pubkey(secp_ctx,
8006                                 msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
8007                         NextPacketDetails {
8008                                 next_packet_pubkey, outgoing_scid: short_channel_id,
8009                                 outgoing_amt_msat: amt_to_forward, outgoing_cltv_value
8010                         }
8011                 },
8012                 onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
8013                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
8014                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
8015                 {
8016                         return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
8017                 }
8018         };
8019
8020         Ok((next_hop, shared_secret, Some(next_packet_details)))
8021 }
8022
8023 fn check_incoming_htlc_cltv(
8024         cur_height: u32, outgoing_cltv_value: u32, cltv_expiry: u32
8025 ) -> Result<(), (&'static str, u16)> {
8026         if (cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
8027                 return Err((
8028                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
8029                         0x1000 | 13, // incorrect_cltv_expiry
8030                 ));
8031         }
8032         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
8033         // but we want to be robust wrt to counterparty packet sanitization (see
8034         // HTLC_FAIL_BACK_BUFFER rationale).
8035         if cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
8036                 return Err(("CLTV expiry is too close", 0x1000 | 14));
8037         }
8038         if cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
8039                 return Err(("CLTV expiry is too far in the future", 21));
8040         }
8041         // If the HTLC expires ~now, don't bother trying to forward it to our
8042         // counterparty. They should fail it anyway, but we don't want to bother with
8043         // the round-trips or risk them deciding they definitely want the HTLC and
8044         // force-closing to ensure they get it if we're offline.
8045         // We previously had a much more aggressive check here which tried to ensure
8046         // our counterparty receives an HTLC which has *our* risk threshold met on it,
8047         // but there is no need to do that, and since we're a bit conservative with our
8048         // risk threshold it just results in failing to forward payments.
8049         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
8050                 return Err(("Outgoing CLTV value is too soon", 0x1000 | 14));
8051         }
8052
8053         Ok(())
8054 }
8055
8056 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>
8057 where
8058         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8059         T::Target: BroadcasterInterface,
8060         ES::Target: EntropySource,
8061         NS::Target: NodeSigner,
8062         SP::Target: SignerProvider,
8063         F::Target: FeeEstimator,
8064         R::Target: Router,
8065         L::Target: Logger,
8066 {
8067         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
8068         /// The returned array will contain `MessageSendEvent`s for different peers if
8069         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
8070         /// is always placed next to each other.
8071         ///
8072         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
8073         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
8074         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
8075         /// will randomly be placed first or last in the returned array.
8076         ///
8077         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
8078         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
8079         /// the `MessageSendEvent`s to the specific peer they were generated under.
8080         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
8081                 let events = RefCell::new(Vec::new());
8082                 PersistenceNotifierGuard::optionally_notify(self, || {
8083                         let mut result = NotifyOption::SkipPersistNoEvents;
8084
8085                         // TODO: This behavior should be documented. It's unintuitive that we query
8086                         // ChannelMonitors when clearing other events.
8087                         if self.process_pending_monitor_events() {
8088                                 result = NotifyOption::DoPersist;
8089                         }
8090
8091                         if self.check_free_holding_cells() {
8092                                 result = NotifyOption::DoPersist;
8093                         }
8094                         if self.maybe_generate_initial_closing_signed() {
8095                                 result = NotifyOption::DoPersist;
8096                         }
8097
8098                         let mut pending_events = Vec::new();
8099                         let per_peer_state = self.per_peer_state.read().unwrap();
8100                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8101                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8102                                 let peer_state = &mut *peer_state_lock;
8103                                 if peer_state.pending_msg_events.len() > 0 {
8104                                         pending_events.append(&mut peer_state.pending_msg_events);
8105                                 }
8106                         }
8107
8108                         if !pending_events.is_empty() {
8109                                 events.replace(pending_events);
8110                         }
8111
8112                         result
8113                 });
8114                 events.into_inner()
8115         }
8116 }
8117
8118 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>
8119 where
8120         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8121         T::Target: BroadcasterInterface,
8122         ES::Target: EntropySource,
8123         NS::Target: NodeSigner,
8124         SP::Target: SignerProvider,
8125         F::Target: FeeEstimator,
8126         R::Target: Router,
8127         L::Target: Logger,
8128 {
8129         /// Processes events that must be periodically handled.
8130         ///
8131         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
8132         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
8133         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
8134                 let mut ev;
8135                 process_events_body!(self, ev, handler.handle_event(ev));
8136         }
8137 }
8138
8139 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>
8140 where
8141         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8142         T::Target: BroadcasterInterface,
8143         ES::Target: EntropySource,
8144         NS::Target: NodeSigner,
8145         SP::Target: SignerProvider,
8146         F::Target: FeeEstimator,
8147         R::Target: Router,
8148         L::Target: Logger,
8149 {
8150         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
8151                 {
8152                         let best_block = self.best_block.read().unwrap();
8153                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
8154                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
8155                         assert_eq!(best_block.height(), height - 1,
8156                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
8157                 }
8158
8159                 self.transactions_confirmed(header, txdata, height);
8160                 self.best_block_updated(header, height);
8161         }
8162
8163         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
8164                 let _persistence_guard =
8165                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8166                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8167                 let new_height = height - 1;
8168                 {
8169                         let mut best_block = self.best_block.write().unwrap();
8170                         assert_eq!(best_block.block_hash(), header.block_hash(),
8171                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
8172                         assert_eq!(best_block.height(), height,
8173                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
8174                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
8175                 }
8176
8177                 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));
8178         }
8179 }
8180
8181 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>
8182 where
8183         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8184         T::Target: BroadcasterInterface,
8185         ES::Target: EntropySource,
8186         NS::Target: NodeSigner,
8187         SP::Target: SignerProvider,
8188         F::Target: FeeEstimator,
8189         R::Target: Router,
8190         L::Target: Logger,
8191 {
8192         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
8193                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8194                 // during initialization prior to the chain_monitor being fully configured in some cases.
8195                 // See the docs for `ChannelManagerReadArgs` for more.
8196
8197                 let block_hash = header.block_hash();
8198                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
8199
8200                 let _persistence_guard =
8201                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8202                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8203                 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)
8204                         .map(|(a, b)| (a, Vec::new(), b)));
8205
8206                 let last_best_block_height = self.best_block.read().unwrap().height();
8207                 if height < last_best_block_height {
8208                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
8209                         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));
8210                 }
8211         }
8212
8213         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
8214                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8215                 // during initialization prior to the chain_monitor being fully configured in some cases.
8216                 // See the docs for `ChannelManagerReadArgs` for more.
8217
8218                 let block_hash = header.block_hash();
8219                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
8220
8221                 let _persistence_guard =
8222                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8223                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8224                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
8225
8226                 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));
8227
8228                 macro_rules! max_time {
8229                         ($timestamp: expr) => {
8230                                 loop {
8231                                         // Update $timestamp to be the max of its current value and the block
8232                                         // timestamp. This should keep us close to the current time without relying on
8233                                         // having an explicit local time source.
8234                                         // Just in case we end up in a race, we loop until we either successfully
8235                                         // update $timestamp or decide we don't need to.
8236                                         let old_serial = $timestamp.load(Ordering::Acquire);
8237                                         if old_serial >= header.time as usize { break; }
8238                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8239                                                 break;
8240                                         }
8241                                 }
8242                         }
8243                 }
8244                 max_time!(self.highest_seen_timestamp);
8245                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8246                 payment_secrets.retain(|_, inbound_payment| {
8247                         inbound_payment.expiry_time > header.time as u64
8248                 });
8249         }
8250
8251         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
8252                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8253                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8254                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8255                         let peer_state = &mut *peer_state_lock;
8256                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8257                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
8258                                         res.push((funding_txo.txid, Some(block_hash)));
8259                                 }
8260                         }
8261                 }
8262                 res
8263         }
8264
8265         fn transaction_unconfirmed(&self, txid: &Txid) {
8266                 let _persistence_guard =
8267                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8268                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8269                 self.do_chain_event(None, |channel| {
8270                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8271                                 if funding_txo.txid == *txid {
8272                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
8273                                 } else { Ok((None, Vec::new(), None)) }
8274                         } else { Ok((None, Vec::new(), None)) }
8275                 });
8276         }
8277 }
8278
8279 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>
8280 where
8281         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8282         T::Target: BroadcasterInterface,
8283         ES::Target: EntropySource,
8284         NS::Target: NodeSigner,
8285         SP::Target: SignerProvider,
8286         F::Target: FeeEstimator,
8287         R::Target: Router,
8288         L::Target: Logger,
8289 {
8290         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8291         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8292         /// the function.
8293         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8294                         (&self, height_opt: Option<u32>, f: FN) {
8295                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8296                 // during initialization prior to the chain_monitor being fully configured in some cases.
8297                 // See the docs for `ChannelManagerReadArgs` for more.
8298
8299                 let mut failed_channels = Vec::new();
8300                 let mut timed_out_htlcs = Vec::new();
8301                 {
8302                         let per_peer_state = self.per_peer_state.read().unwrap();
8303                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8304                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8305                                 let peer_state = &mut *peer_state_lock;
8306                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8307                                 peer_state.channel_by_id.retain(|_, phase| {
8308                                         match phase {
8309                                                 // Retain unfunded channels.
8310                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8311                                                 ChannelPhase::Funded(channel) => {
8312                                                         let res = f(channel);
8313                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8314                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8315                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8316                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8317                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8318                                                                 }
8319                                                                 if let Some(channel_ready) = channel_ready_opt {
8320                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8321                                                                         if channel.context.is_usable() {
8322                                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8323                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8324                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8325                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8326                                                                                                 msg,
8327                                                                                         });
8328                                                                                 }
8329                                                                         } else {
8330                                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8331                                                                         }
8332                                                                 }
8333
8334                                                                 {
8335                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8336                                                                         emit_channel_ready_event!(pending_events, channel);
8337                                                                 }
8338
8339                                                                 if let Some(announcement_sigs) = announcement_sigs {
8340                                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8341                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8342                                                                                 node_id: channel.context.get_counterparty_node_id(),
8343                                                                                 msg: announcement_sigs,
8344                                                                         });
8345                                                                         if let Some(height) = height_opt {
8346                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8347                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8348                                                                                                 msg: announcement,
8349                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8350                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8351                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8352                                                                                         });
8353                                                                                 }
8354                                                                         }
8355                                                                 }
8356                                                                 if channel.is_our_channel_ready() {
8357                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8358                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8359                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8360                                                                                 // can relay using the real SCID at relay-time (i.e.
8361                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8362                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8363                                                                                 // is always consistent.
8364                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8365                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8366                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8367                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8368                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8369                                                                         }
8370                                                                 }
8371                                                         } else if let Err(reason) = res {
8372                                                                 update_maps_on_chan_removal!(self, &channel.context);
8373                                                                 // It looks like our counterparty went on-chain or funding transaction was
8374                                                                 // reorged out of the main chain. Close the channel.
8375                                                                 failed_channels.push(channel.context.force_shutdown(true));
8376                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8377                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
8378                                                                                 msg: update
8379                                                                         });
8380                                                                 }
8381                                                                 let reason_message = format!("{}", reason);
8382                                                                 self.issue_channel_close_events(&channel.context, reason);
8383                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8384                                                                         node_id: channel.context.get_counterparty_node_id(),
8385                                                                         action: msgs::ErrorAction::DisconnectPeer {
8386                                                                                 msg: Some(msgs::ErrorMessage {
8387                                                                                         channel_id: channel.context.channel_id(),
8388                                                                                         data: reason_message,
8389                                                                                 })
8390                                                                         },
8391                                                                 });
8392                                                                 return false;
8393                                                         }
8394                                                         true
8395                                                 }
8396                                         }
8397                                 });
8398                         }
8399                 }
8400
8401                 if let Some(height) = height_opt {
8402                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8403                                 payment.htlcs.retain(|htlc| {
8404                                         // If height is approaching the number of blocks we think it takes us to get
8405                                         // our commitment transaction confirmed before the HTLC expires, plus the
8406                                         // number of blocks we generally consider it to take to do a commitment update,
8407                                         // just give up on it and fail the HTLC.
8408                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8409                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8410                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8411
8412                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8413                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8414                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8415                                                 false
8416                                         } else { true }
8417                                 });
8418                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8419                         });
8420
8421                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8422                         intercepted_htlcs.retain(|_, htlc| {
8423                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8424                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8425                                                 short_channel_id: htlc.prev_short_channel_id,
8426                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8427                                                 htlc_id: htlc.prev_htlc_id,
8428                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8429                                                 phantom_shared_secret: None,
8430                                                 outpoint: htlc.prev_funding_outpoint,
8431                                         });
8432
8433                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8434                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8435                                                 _ => unreachable!(),
8436                                         };
8437                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8438                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8439                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8440                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8441                                         false
8442                                 } else { true }
8443                         });
8444                 }
8445
8446                 self.handle_init_event_channel_failures(failed_channels);
8447
8448                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8449                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8450                 }
8451         }
8452
8453         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8454         /// may have events that need processing.
8455         ///
8456         /// In order to check if this [`ChannelManager`] needs persisting, call
8457         /// [`Self::get_and_clear_needs_persistence`].
8458         ///
8459         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8460         /// [`ChannelManager`] and should instead register actions to be taken later.
8461         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8462                 self.event_persist_notifier.get_future()
8463         }
8464
8465         /// Returns true if this [`ChannelManager`] needs to be persisted.
8466         pub fn get_and_clear_needs_persistence(&self) -> bool {
8467                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8468         }
8469
8470         #[cfg(any(test, feature = "_test_utils"))]
8471         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8472                 self.event_persist_notifier.notify_pending()
8473         }
8474
8475         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8476         /// [`chain::Confirm`] interfaces.
8477         pub fn current_best_block(&self) -> BestBlock {
8478                 self.best_block.read().unwrap().clone()
8479         }
8480
8481         /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
8482         /// [`ChannelManager`].
8483         pub fn node_features(&self) -> NodeFeatures {
8484                 provided_node_features(&self.default_configuration)
8485         }
8486
8487         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
8488         /// [`ChannelManager`].
8489         ///
8490         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8491         /// or not. Thus, this method is not public.
8492         #[cfg(any(feature = "_test_utils", test))]
8493         pub fn bolt11_invoice_features(&self) -> Bolt11InvoiceFeatures {
8494                 provided_bolt11_invoice_features(&self.default_configuration)
8495         }
8496
8497         /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
8498         /// [`ChannelManager`].
8499         fn bolt12_invoice_features(&self) -> Bolt12InvoiceFeatures {
8500                 provided_bolt12_invoice_features(&self.default_configuration)
8501         }
8502
8503         /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
8504         /// [`ChannelManager`].
8505         pub fn channel_features(&self) -> ChannelFeatures {
8506                 provided_channel_features(&self.default_configuration)
8507         }
8508
8509         /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
8510         /// [`ChannelManager`].
8511         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8512                 provided_channel_type_features(&self.default_configuration)
8513         }
8514
8515         /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
8516         /// [`ChannelManager`].
8517         pub fn init_features(&self) -> InitFeatures {
8518                 provided_init_features(&self.default_configuration)
8519         }
8520 }
8521
8522 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8523         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8524 where
8525         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8526         T::Target: BroadcasterInterface,
8527         ES::Target: EntropySource,
8528         NS::Target: NodeSigner,
8529         SP::Target: SignerProvider,
8530         F::Target: FeeEstimator,
8531         R::Target: Router,
8532         L::Target: Logger,
8533 {
8534         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8535                 // Note that we never need to persist the updated ChannelManager for an inbound
8536                 // open_channel message - pre-funded channels are never written so there should be no
8537                 // change to the contents.
8538                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8539                         let res = self.internal_open_channel(counterparty_node_id, msg);
8540                         let persist = match &res {
8541                                 Err(e) if e.closes_channel() => {
8542                                         debug_assert!(false, "We shouldn't close a new channel");
8543                                         NotifyOption::DoPersist
8544                                 },
8545                                 _ => NotifyOption::SkipPersistHandleEvents,
8546                         };
8547                         let _ = handle_error!(self, res, *counterparty_node_id);
8548                         persist
8549                 });
8550         }
8551
8552         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8553                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8554                         "Dual-funded channels not supported".to_owned(),
8555                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8556         }
8557
8558         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8559                 // Note that we never need to persist the updated ChannelManager for an inbound
8560                 // accept_channel message - pre-funded channels are never written so there should be no
8561                 // change to the contents.
8562                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8563                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8564                         NotifyOption::SkipPersistHandleEvents
8565                 });
8566         }
8567
8568         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8569                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8570                         "Dual-funded channels not supported".to_owned(),
8571                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8572         }
8573
8574         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8575                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8576                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8577         }
8578
8579         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8580                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8581                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8582         }
8583
8584         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8585                 // Note that we never need to persist the updated ChannelManager for an inbound
8586                 // channel_ready message - while the channel's state will change, any channel_ready message
8587                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8588                 // will not force-close the channel on startup.
8589                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8590                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8591                         let persist = match &res {
8592                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8593                                 _ => NotifyOption::SkipPersistHandleEvents,
8594                         };
8595                         let _ = handle_error!(self, res, *counterparty_node_id);
8596                         persist
8597                 });
8598         }
8599
8600         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8601                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8602                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8603         }
8604
8605         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8606                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8607                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8608         }
8609
8610         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8611                 // Note that we never need to persist the updated ChannelManager for an inbound
8612                 // update_add_htlc message - the message itself doesn't change our channel state only the
8613                 // `commitment_signed` message afterwards will.
8614                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8615                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8616                         let persist = match &res {
8617                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8618                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8619                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8620                         };
8621                         let _ = handle_error!(self, res, *counterparty_node_id);
8622                         persist
8623                 });
8624         }
8625
8626         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8627                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8628                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8629         }
8630
8631         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8632                 // Note that we never need to persist the updated ChannelManager for an inbound
8633                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8634                 // `commitment_signed` message afterwards will.
8635                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8636                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8637                         let persist = match &res {
8638                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8639                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8640                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8641                         };
8642                         let _ = handle_error!(self, res, *counterparty_node_id);
8643                         persist
8644                 });
8645         }
8646
8647         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8648                 // Note that we never need to persist the updated ChannelManager for an inbound
8649                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8650                 // only the `commitment_signed` message afterwards will.
8651                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8652                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8653                         let persist = match &res {
8654                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8655                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8656                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8657                         };
8658                         let _ = handle_error!(self, res, *counterparty_node_id);
8659                         persist
8660                 });
8661         }
8662
8663         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8664                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8665                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8666         }
8667
8668         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8669                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8670                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8671         }
8672
8673         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8674                 // Note that we never need to persist the updated ChannelManager for an inbound
8675                 // update_fee message - the message itself doesn't change our channel state only the
8676                 // `commitment_signed` message afterwards will.
8677                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8678                         let res = self.internal_update_fee(counterparty_node_id, msg);
8679                         let persist = match &res {
8680                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8681                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8682                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8683                         };
8684                         let _ = handle_error!(self, res, *counterparty_node_id);
8685                         persist
8686                 });
8687         }
8688
8689         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8690                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8691                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8692         }
8693
8694         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8695                 PersistenceNotifierGuard::optionally_notify(self, || {
8696                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8697                                 persist
8698                         } else {
8699                                 NotifyOption::DoPersist
8700                         }
8701                 });
8702         }
8703
8704         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8705                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8706                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8707                         let persist = match &res {
8708                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8709                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8710                                 Ok(persist) => *persist,
8711                         };
8712                         let _ = handle_error!(self, res, *counterparty_node_id);
8713                         persist
8714                 });
8715         }
8716
8717         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8718                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8719                         self, || NotifyOption::SkipPersistHandleEvents);
8720                 let mut failed_channels = Vec::new();
8721                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8722                 let remove_peer = {
8723                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
8724                                 log_pubkey!(counterparty_node_id));
8725                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8726                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8727                                 let peer_state = &mut *peer_state_lock;
8728                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8729                                 peer_state.channel_by_id.retain(|_, phase| {
8730                                         let context = match phase {
8731                                                 ChannelPhase::Funded(chan) => {
8732                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger).is_ok() {
8733                                                                 // We only retain funded channels that are not shutdown.
8734                                                                 return true;
8735                                                         }
8736                                                         &mut chan.context
8737                                                 },
8738                                                 // Unfunded channels will always be removed.
8739                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8740                                                         &mut chan.context
8741                                                 },
8742                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8743                                                         &mut chan.context
8744                                                 },
8745                                         };
8746                                         // Clean up for removal.
8747                                         update_maps_on_chan_removal!(self, &context);
8748                                         self.issue_channel_close_events(&context, ClosureReason::DisconnectedPeer);
8749                                         failed_channels.push(context.force_shutdown(false));
8750                                         false
8751                                 });
8752                                 // Note that we don't bother generating any events for pre-accept channels -
8753                                 // they're not considered "channels" yet from the PoV of our events interface.
8754                                 peer_state.inbound_channel_request_by_id.clear();
8755                                 pending_msg_events.retain(|msg| {
8756                                         match msg {
8757                                                 // V1 Channel Establishment
8758                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8759                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8760                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8761                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8762                                                 // V2 Channel Establishment
8763                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8764                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8765                                                 // Common Channel Establishment
8766                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8767                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8768                                                 // Interactive Transaction Construction
8769                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8770                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8771                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8772                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8773                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8774                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8775                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8776                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8777                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8778                                                 // Channel Operations
8779                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8780                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8781                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8782                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8783                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8784                                                 &events::MessageSendEvent::HandleError { .. } => false,
8785                                                 // Gossip
8786                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8787                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8788                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8789                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8790                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8791                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8792                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8793                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8794                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8795                                         }
8796                                 });
8797                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8798                                 peer_state.is_connected = false;
8799                                 peer_state.ok_to_remove(true)
8800                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8801                 };
8802                 if remove_peer {
8803                         per_peer_state.remove(counterparty_node_id);
8804                 }
8805                 mem::drop(per_peer_state);
8806
8807                 for failure in failed_channels.drain(..) {
8808                         self.finish_close_channel(failure);
8809                 }
8810         }
8811
8812         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8813                 if !init_msg.features.supports_static_remote_key() {
8814                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8815                         return Err(());
8816                 }
8817
8818                 let mut res = Ok(());
8819
8820                 PersistenceNotifierGuard::optionally_notify(self, || {
8821                         // If we have too many peers connected which don't have funded channels, disconnect the
8822                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8823                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8824                         // peers connect, but we'll reject new channels from them.
8825                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8826                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8827
8828                         {
8829                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8830                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8831                                         hash_map::Entry::Vacant(e) => {
8832                                                 if inbound_peer_limited {
8833                                                         res = Err(());
8834                                                         return NotifyOption::SkipPersistNoEvents;
8835                                                 }
8836                                                 e.insert(Mutex::new(PeerState {
8837                                                         channel_by_id: HashMap::new(),
8838                                                         inbound_channel_request_by_id: HashMap::new(),
8839                                                         latest_features: init_msg.features.clone(),
8840                                                         pending_msg_events: Vec::new(),
8841                                                         in_flight_monitor_updates: BTreeMap::new(),
8842                                                         monitor_update_blocked_actions: BTreeMap::new(),
8843                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
8844                                                         is_connected: true,
8845                                                 }));
8846                                         },
8847                                         hash_map::Entry::Occupied(e) => {
8848                                                 let mut peer_state = e.get().lock().unwrap();
8849                                                 peer_state.latest_features = init_msg.features.clone();
8850
8851                                                 let best_block_height = self.best_block.read().unwrap().height();
8852                                                 if inbound_peer_limited &&
8853                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
8854                                                         peer_state.channel_by_id.len()
8855                                                 {
8856                                                         res = Err(());
8857                                                         return NotifyOption::SkipPersistNoEvents;
8858                                                 }
8859
8860                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
8861                                                 peer_state.is_connected = true;
8862                                         },
8863                                 }
8864                         }
8865
8866                         log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
8867
8868                         let per_peer_state = self.per_peer_state.read().unwrap();
8869                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8870                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8871                                 let peer_state = &mut *peer_state_lock;
8872                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8873
8874                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
8875                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else {
8876                                                 // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
8877                                                 // (so won't be recovered after a crash), they shouldn't exist here and we would never need to
8878                                                 // worry about closing and removing them.
8879                                                 debug_assert!(false);
8880                                                 None
8881                                         }
8882                                 ).for_each(|chan| {
8883                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
8884                                                 node_id: chan.context.get_counterparty_node_id(),
8885                                                 msg: chan.get_channel_reestablish(&self.logger),
8886                                         });
8887                                 });
8888                         }
8889
8890                         return NotifyOption::SkipPersistHandleEvents;
8891                         //TODO: Also re-broadcast announcement_signatures
8892                 });
8893                 res
8894         }
8895
8896         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
8897                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8898
8899                 match &msg.data as &str {
8900                         "cannot co-op close channel w/ active htlcs"|
8901                         "link failed to shutdown" =>
8902                         {
8903                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
8904                                 // send one while HTLCs are still present. The issue is tracked at
8905                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
8906                                 // to fix it but none so far have managed to land upstream. The issue appears to be
8907                                 // very low priority for the LND team despite being marked "P1".
8908                                 // We're not going to bother handling this in a sensible way, instead simply
8909                                 // repeating the Shutdown message on repeat until morale improves.
8910                                 if !msg.channel_id.is_zero() {
8911                                         let per_peer_state = self.per_peer_state.read().unwrap();
8912                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8913                                         if peer_state_mutex_opt.is_none() { return; }
8914                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
8915                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
8916                                                 if let Some(msg) = chan.get_outbound_shutdown() {
8917                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
8918                                                                 node_id: *counterparty_node_id,
8919                                                                 msg,
8920                                                         });
8921                                                 }
8922                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
8923                                                         node_id: *counterparty_node_id,
8924                                                         action: msgs::ErrorAction::SendWarningMessage {
8925                                                                 msg: msgs::WarningMessage {
8926                                                                         channel_id: msg.channel_id,
8927                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
8928                                                                 },
8929                                                                 log_level: Level::Trace,
8930                                                         }
8931                                                 });
8932                                         }
8933                                 }
8934                                 return;
8935                         }
8936                         _ => {}
8937                 }
8938
8939                 if msg.channel_id.is_zero() {
8940                         let channel_ids: Vec<ChannelId> = {
8941                                 let per_peer_state = self.per_peer_state.read().unwrap();
8942                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8943                                 if peer_state_mutex_opt.is_none() { return; }
8944                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8945                                 let peer_state = &mut *peer_state_lock;
8946                                 // Note that we don't bother generating any events for pre-accept channels -
8947                                 // they're not considered "channels" yet from the PoV of our events interface.
8948                                 peer_state.inbound_channel_request_by_id.clear();
8949                                 peer_state.channel_by_id.keys().cloned().collect()
8950                         };
8951                         for channel_id in channel_ids {
8952                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8953                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
8954                         }
8955                 } else {
8956                         {
8957                                 // First check if we can advance the channel type and try again.
8958                                 let per_peer_state = self.per_peer_state.read().unwrap();
8959                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8960                                 if peer_state_mutex_opt.is_none() { return; }
8961                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8962                                 let peer_state = &mut *peer_state_lock;
8963                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8964                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
8965                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
8966                                                         node_id: *counterparty_node_id,
8967                                                         msg,
8968                                                 });
8969                                                 return;
8970                                         }
8971                                 }
8972                         }
8973
8974                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8975                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
8976                 }
8977         }
8978
8979         fn provided_node_features(&self) -> NodeFeatures {
8980                 provided_node_features(&self.default_configuration)
8981         }
8982
8983         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
8984                 provided_init_features(&self.default_configuration)
8985         }
8986
8987         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8988                 Some(vec![self.chain_hash])
8989         }
8990
8991         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
8992                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8993                         "Dual-funded channels not supported".to_owned(),
8994                          msg.channel_id.clone())), *counterparty_node_id);
8995         }
8996
8997         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
8998                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8999                         "Dual-funded channels not supported".to_owned(),
9000                          msg.channel_id.clone())), *counterparty_node_id);
9001         }
9002
9003         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
9004                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9005                         "Dual-funded channels not supported".to_owned(),
9006                          msg.channel_id.clone())), *counterparty_node_id);
9007         }
9008
9009         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
9010                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9011                         "Dual-funded channels not supported".to_owned(),
9012                          msg.channel_id.clone())), *counterparty_node_id);
9013         }
9014
9015         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
9016                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9017                         "Dual-funded channels not supported".to_owned(),
9018                          msg.channel_id.clone())), *counterparty_node_id);
9019         }
9020
9021         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
9022                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9023                         "Dual-funded channels not supported".to_owned(),
9024                          msg.channel_id.clone())), *counterparty_node_id);
9025         }
9026
9027         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
9028                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9029                         "Dual-funded channels not supported".to_owned(),
9030                          msg.channel_id.clone())), *counterparty_node_id);
9031         }
9032
9033         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
9034                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9035                         "Dual-funded channels not supported".to_owned(),
9036                          msg.channel_id.clone())), *counterparty_node_id);
9037         }
9038
9039         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
9040                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9041                         "Dual-funded channels not supported".to_owned(),
9042                          msg.channel_id.clone())), *counterparty_node_id);
9043         }
9044 }
9045
9046 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9047 OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
9048 where
9049         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9050         T::Target: BroadcasterInterface,
9051         ES::Target: EntropySource,
9052         NS::Target: NodeSigner,
9053         SP::Target: SignerProvider,
9054         F::Target: FeeEstimator,
9055         R::Target: Router,
9056         L::Target: Logger,
9057 {
9058         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
9059                 let secp_ctx = &self.secp_ctx;
9060                 let expanded_key = &self.inbound_payment_key;
9061
9062                 match message {
9063                         OffersMessage::InvoiceRequest(invoice_request) => {
9064                                 let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
9065                                         &invoice_request
9066                                 ) {
9067                                         Ok(amount_msats) => Some(amount_msats),
9068                                         Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
9069                                 };
9070                                 let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
9071                                         Ok(invoice_request) => invoice_request,
9072                                         Err(()) => {
9073                                                 let error = Bolt12SemanticError::InvalidMetadata;
9074                                                 return Some(OffersMessage::InvoiceError(error.into()));
9075                                         },
9076                                 };
9077                                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9078
9079                                 match self.create_inbound_payment(amount_msats, relative_expiry, None) {
9080                                         Ok((payment_hash, payment_secret)) if invoice_request.keys.is_some() => {
9081                                                 let payment_paths = vec![
9082                                                         self.create_one_hop_blinded_payment_path(payment_secret),
9083                                                 ];
9084                                                 #[cfg(not(feature = "no-std"))]
9085                                                 let builder = invoice_request.respond_using_derived_keys(
9086                                                         payment_paths, payment_hash
9087                                                 );
9088                                                 #[cfg(feature = "no-std")]
9089                                                 let created_at = Duration::from_secs(
9090                                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9091                                                 );
9092                                                 #[cfg(feature = "no-std")]
9093                                                 let builder = invoice_request.respond_using_derived_keys_no_std(
9094                                                         payment_paths, payment_hash, created_at
9095                                                 );
9096                                                 match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
9097                                                         Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
9098                                                         Err(error) => Some(OffersMessage::InvoiceError(error.into())),
9099                                                 }
9100                                         },
9101                                         Ok((payment_hash, payment_secret)) => {
9102                                                 let payment_paths = vec![
9103                                                         self.create_one_hop_blinded_payment_path(payment_secret),
9104                                                 ];
9105                                                 #[cfg(not(feature = "no-std"))]
9106                                                 let builder = invoice_request.respond_with(payment_paths, payment_hash);
9107                                                 #[cfg(feature = "no-std")]
9108                                                 let created_at = Duration::from_secs(
9109                                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9110                                                 );
9111                                                 #[cfg(feature = "no-std")]
9112                                                 let builder = invoice_request.respond_with_no_std(
9113                                                         payment_paths, payment_hash, created_at
9114                                                 );
9115                                                 let response = builder.and_then(|builder| builder.allow_mpp().build())
9116                                                         .map_err(|e| OffersMessage::InvoiceError(e.into()))
9117                                                         .and_then(|invoice|
9118                                                                 match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
9119                                                                         Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
9120                                                                         Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
9121                                                                                         InvoiceError::from_string("Failed signing invoice".to_string())
9122                                                                         )),
9123                                                                         Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
9124                                                                                         InvoiceError::from_string("Failed invoice signature verification".to_string())
9125                                                                         )),
9126                                                                 });
9127                                                 match response {
9128                                                         Ok(invoice) => Some(invoice),
9129                                                         Err(error) => Some(error),
9130                                                 }
9131                                         },
9132                                         Err(()) => {
9133                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::InvalidAmount.into()))
9134                                         },
9135                                 }
9136                         },
9137                         OffersMessage::Invoice(invoice) => {
9138                                 match invoice.verify(expanded_key, secp_ctx) {
9139                                         Err(()) => {
9140                                                 Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
9141                                         },
9142                                         Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
9143                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
9144                                         },
9145                                         Ok(payment_id) => {
9146                                                 if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
9147                                                         log_trace!(self.logger, "Failed paying invoice: {:?}", e);
9148                                                         Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
9149                                                 } else {
9150                                                         None
9151                                                 }
9152                                         },
9153                                 }
9154                         },
9155                         OffersMessage::InvoiceError(invoice_error) => {
9156                                 log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
9157                                 None
9158                         },
9159                 }
9160         }
9161
9162         fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> {
9163                 core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
9164         }
9165 }
9166
9167 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
9168 /// [`ChannelManager`].
9169 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
9170         let mut node_features = provided_init_features(config).to_context();
9171         node_features.set_keysend_optional();
9172         node_features
9173 }
9174
9175 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
9176 /// [`ChannelManager`].
9177 ///
9178 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
9179 /// or not. Thus, this method is not public.
9180 #[cfg(any(feature = "_test_utils", test))]
9181 pub(crate) fn provided_bolt11_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
9182         provided_init_features(config).to_context()
9183 }
9184
9185 /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
9186 /// [`ChannelManager`].
9187 pub(crate) fn provided_bolt12_invoice_features(config: &UserConfig) -> Bolt12InvoiceFeatures {
9188         provided_init_features(config).to_context()
9189 }
9190
9191 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
9192 /// [`ChannelManager`].
9193 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
9194         provided_init_features(config).to_context()
9195 }
9196
9197 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
9198 /// [`ChannelManager`].
9199 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
9200         ChannelTypeFeatures::from_init(&provided_init_features(config))
9201 }
9202
9203 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
9204 /// [`ChannelManager`].
9205 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
9206         // Note that if new features are added here which other peers may (eventually) require, we
9207         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
9208         // [`ErroringMessageHandler`].
9209         let mut features = InitFeatures::empty();
9210         features.set_data_loss_protect_required();
9211         features.set_upfront_shutdown_script_optional();
9212         features.set_variable_length_onion_required();
9213         features.set_static_remote_key_required();
9214         features.set_payment_secret_required();
9215         features.set_basic_mpp_optional();
9216         features.set_wumbo_optional();
9217         features.set_shutdown_any_segwit_optional();
9218         features.set_channel_type_optional();
9219         features.set_scid_privacy_optional();
9220         features.set_zero_conf_optional();
9221         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
9222                 features.set_anchors_zero_fee_htlc_tx_optional();
9223         }
9224         features
9225 }
9226
9227 const SERIALIZATION_VERSION: u8 = 1;
9228 const MIN_SERIALIZATION_VERSION: u8 = 1;
9229
9230 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
9231         (2, fee_base_msat, required),
9232         (4, fee_proportional_millionths, required),
9233         (6, cltv_expiry_delta, required),
9234 });
9235
9236 impl_writeable_tlv_based!(ChannelCounterparty, {
9237         (2, node_id, required),
9238         (4, features, required),
9239         (6, unspendable_punishment_reserve, required),
9240         (8, forwarding_info, option),
9241         (9, outbound_htlc_minimum_msat, option),
9242         (11, outbound_htlc_maximum_msat, option),
9243 });
9244
9245 impl Writeable for ChannelDetails {
9246         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9247                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9248                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9249                 let user_channel_id_low = self.user_channel_id as u64;
9250                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
9251                 write_tlv_fields!(writer, {
9252                         (1, self.inbound_scid_alias, option),
9253                         (2, self.channel_id, required),
9254                         (3, self.channel_type, option),
9255                         (4, self.counterparty, required),
9256                         (5, self.outbound_scid_alias, option),
9257                         (6, self.funding_txo, option),
9258                         (7, self.config, option),
9259                         (8, self.short_channel_id, option),
9260                         (9, self.confirmations, option),
9261                         (10, self.channel_value_satoshis, required),
9262                         (12, self.unspendable_punishment_reserve, option),
9263                         (14, user_channel_id_low, required),
9264                         (16, self.balance_msat, required),
9265                         (18, self.outbound_capacity_msat, required),
9266                         (19, self.next_outbound_htlc_limit_msat, required),
9267                         (20, self.inbound_capacity_msat, required),
9268                         (21, self.next_outbound_htlc_minimum_msat, required),
9269                         (22, self.confirmations_required, option),
9270                         (24, self.force_close_spend_delay, option),
9271                         (26, self.is_outbound, required),
9272                         (28, self.is_channel_ready, required),
9273                         (30, self.is_usable, required),
9274                         (32, self.is_public, required),
9275                         (33, self.inbound_htlc_minimum_msat, option),
9276                         (35, self.inbound_htlc_maximum_msat, option),
9277                         (37, user_channel_id_high_opt, option),
9278                         (39, self.feerate_sat_per_1000_weight, option),
9279                         (41, self.channel_shutdown_state, option),
9280                 });
9281                 Ok(())
9282         }
9283 }
9284
9285 impl Readable for ChannelDetails {
9286         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9287                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9288                         (1, inbound_scid_alias, option),
9289                         (2, channel_id, required),
9290                         (3, channel_type, option),
9291                         (4, counterparty, required),
9292                         (5, outbound_scid_alias, option),
9293                         (6, funding_txo, option),
9294                         (7, config, option),
9295                         (8, short_channel_id, option),
9296                         (9, confirmations, option),
9297                         (10, channel_value_satoshis, required),
9298                         (12, unspendable_punishment_reserve, option),
9299                         (14, user_channel_id_low, required),
9300                         (16, balance_msat, required),
9301                         (18, outbound_capacity_msat, required),
9302                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
9303                         // filled in, so we can safely unwrap it here.
9304                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
9305                         (20, inbound_capacity_msat, required),
9306                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
9307                         (22, confirmations_required, option),
9308                         (24, force_close_spend_delay, option),
9309                         (26, is_outbound, required),
9310                         (28, is_channel_ready, required),
9311                         (30, is_usable, required),
9312                         (32, is_public, required),
9313                         (33, inbound_htlc_minimum_msat, option),
9314                         (35, inbound_htlc_maximum_msat, option),
9315                         (37, user_channel_id_high_opt, option),
9316                         (39, feerate_sat_per_1000_weight, option),
9317                         (41, channel_shutdown_state, option),
9318                 });
9319
9320                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9321                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9322                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
9323                 let user_channel_id = user_channel_id_low as u128 +
9324                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
9325
9326                 Ok(Self {
9327                         inbound_scid_alias,
9328                         channel_id: channel_id.0.unwrap(),
9329                         channel_type,
9330                         counterparty: counterparty.0.unwrap(),
9331                         outbound_scid_alias,
9332                         funding_txo,
9333                         config,
9334                         short_channel_id,
9335                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
9336                         unspendable_punishment_reserve,
9337                         user_channel_id,
9338                         balance_msat: balance_msat.0.unwrap(),
9339                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
9340                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
9341                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
9342                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
9343                         confirmations_required,
9344                         confirmations,
9345                         force_close_spend_delay,
9346                         is_outbound: is_outbound.0.unwrap(),
9347                         is_channel_ready: is_channel_ready.0.unwrap(),
9348                         is_usable: is_usable.0.unwrap(),
9349                         is_public: is_public.0.unwrap(),
9350                         inbound_htlc_minimum_msat,
9351                         inbound_htlc_maximum_msat,
9352                         feerate_sat_per_1000_weight,
9353                         channel_shutdown_state,
9354                 })
9355         }
9356 }
9357
9358 impl_writeable_tlv_based!(PhantomRouteHints, {
9359         (2, channels, required_vec),
9360         (4, phantom_scid, required),
9361         (6, real_node_pubkey, required),
9362 });
9363
9364 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
9365         (0, Forward) => {
9366                 (0, onion_packet, required),
9367                 (2, short_channel_id, required),
9368         },
9369         (1, Receive) => {
9370                 (0, payment_data, required),
9371                 (1, phantom_shared_secret, option),
9372                 (2, incoming_cltv_expiry, required),
9373                 (3, payment_metadata, option),
9374                 (5, custom_tlvs, optional_vec),
9375         },
9376         (2, ReceiveKeysend) => {
9377                 (0, payment_preimage, required),
9378                 (2, incoming_cltv_expiry, required),
9379                 (3, payment_metadata, option),
9380                 (4, payment_data, option), // Added in 0.0.116
9381                 (5, custom_tlvs, optional_vec),
9382         },
9383 ;);
9384
9385 impl_writeable_tlv_based!(PendingHTLCInfo, {
9386         (0, routing, required),
9387         (2, incoming_shared_secret, required),
9388         (4, payment_hash, required),
9389         (6, outgoing_amt_msat, required),
9390         (8, outgoing_cltv_value, required),
9391         (9, incoming_amt_msat, option),
9392         (10, skimmed_fee_msat, option),
9393 });
9394
9395
9396 impl Writeable for HTLCFailureMsg {
9397         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9398                 match self {
9399                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9400                                 0u8.write(writer)?;
9401                                 channel_id.write(writer)?;
9402                                 htlc_id.write(writer)?;
9403                                 reason.write(writer)?;
9404                         },
9405                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9406                                 channel_id, htlc_id, sha256_of_onion, failure_code
9407                         }) => {
9408                                 1u8.write(writer)?;
9409                                 channel_id.write(writer)?;
9410                                 htlc_id.write(writer)?;
9411                                 sha256_of_onion.write(writer)?;
9412                                 failure_code.write(writer)?;
9413                         },
9414                 }
9415                 Ok(())
9416         }
9417 }
9418
9419 impl Readable for HTLCFailureMsg {
9420         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9421                 let id: u8 = Readable::read(reader)?;
9422                 match id {
9423                         0 => {
9424                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9425                                         channel_id: Readable::read(reader)?,
9426                                         htlc_id: Readable::read(reader)?,
9427                                         reason: Readable::read(reader)?,
9428                                 }))
9429                         },
9430                         1 => {
9431                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9432                                         channel_id: Readable::read(reader)?,
9433                                         htlc_id: Readable::read(reader)?,
9434                                         sha256_of_onion: Readable::read(reader)?,
9435                                         failure_code: Readable::read(reader)?,
9436                                 }))
9437                         },
9438                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9439                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9440                         // messages contained in the variants.
9441                         // In version 0.0.101, support for reading the variants with these types was added, and
9442                         // we should migrate to writing these variants when UpdateFailHTLC or
9443                         // UpdateFailMalformedHTLC get TLV fields.
9444                         2 => {
9445                                 let length: BigSize = Readable::read(reader)?;
9446                                 let mut s = FixedLengthReader::new(reader, length.0);
9447                                 let res = Readable::read(&mut s)?;
9448                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9449                                 Ok(HTLCFailureMsg::Relay(res))
9450                         },
9451                         3 => {
9452                                 let length: BigSize = Readable::read(reader)?;
9453                                 let mut s = FixedLengthReader::new(reader, length.0);
9454                                 let res = Readable::read(&mut s)?;
9455                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9456                                 Ok(HTLCFailureMsg::Malformed(res))
9457                         },
9458                         _ => Err(DecodeError::UnknownRequiredFeature),
9459                 }
9460         }
9461 }
9462
9463 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9464         (0, Forward),
9465         (1, Fail),
9466 );
9467
9468 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9469         (0, short_channel_id, required),
9470         (1, phantom_shared_secret, option),
9471         (2, outpoint, required),
9472         (4, htlc_id, required),
9473         (6, incoming_packet_shared_secret, required),
9474         (7, user_channel_id, option),
9475 });
9476
9477 impl Writeable for ClaimableHTLC {
9478         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9479                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9480                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9481                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9482                 };
9483                 write_tlv_fields!(writer, {
9484                         (0, self.prev_hop, required),
9485                         (1, self.total_msat, required),
9486                         (2, self.value, required),
9487                         (3, self.sender_intended_value, required),
9488                         (4, payment_data, option),
9489                         (5, self.total_value_received, option),
9490                         (6, self.cltv_expiry, required),
9491                         (8, keysend_preimage, option),
9492                         (10, self.counterparty_skimmed_fee_msat, option),
9493                 });
9494                 Ok(())
9495         }
9496 }
9497
9498 impl Readable for ClaimableHTLC {
9499         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9500                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9501                         (0, prev_hop, required),
9502                         (1, total_msat, option),
9503                         (2, value_ser, required),
9504                         (3, sender_intended_value, option),
9505                         (4, payment_data_opt, option),
9506                         (5, total_value_received, option),
9507                         (6, cltv_expiry, required),
9508                         (8, keysend_preimage, option),
9509                         (10, counterparty_skimmed_fee_msat, option),
9510                 });
9511                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9512                 let value = value_ser.0.unwrap();
9513                 let onion_payload = match keysend_preimage {
9514                         Some(p) => {
9515                                 if payment_data.is_some() {
9516                                         return Err(DecodeError::InvalidValue)
9517                                 }
9518                                 if total_msat.is_none() {
9519                                         total_msat = Some(value);
9520                                 }
9521                                 OnionPayload::Spontaneous(p)
9522                         },
9523                         None => {
9524                                 if total_msat.is_none() {
9525                                         if payment_data.is_none() {
9526                                                 return Err(DecodeError::InvalidValue)
9527                                         }
9528                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9529                                 }
9530                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9531                         },
9532                 };
9533                 Ok(Self {
9534                         prev_hop: prev_hop.0.unwrap(),
9535                         timer_ticks: 0,
9536                         value,
9537                         sender_intended_value: sender_intended_value.unwrap_or(value),
9538                         total_value_received,
9539                         total_msat: total_msat.unwrap(),
9540                         onion_payload,
9541                         cltv_expiry: cltv_expiry.0.unwrap(),
9542                         counterparty_skimmed_fee_msat,
9543                 })
9544         }
9545 }
9546
9547 impl Readable for HTLCSource {
9548         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9549                 let id: u8 = Readable::read(reader)?;
9550                 match id {
9551                         0 => {
9552                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9553                                 let mut first_hop_htlc_msat: u64 = 0;
9554                                 let mut path_hops = Vec::new();
9555                                 let mut payment_id = None;
9556                                 let mut payment_params: Option<PaymentParameters> = None;
9557                                 let mut blinded_tail: Option<BlindedTail> = None;
9558                                 read_tlv_fields!(reader, {
9559                                         (0, session_priv, required),
9560                                         (1, payment_id, option),
9561                                         (2, first_hop_htlc_msat, required),
9562                                         (4, path_hops, required_vec),
9563                                         (5, payment_params, (option: ReadableArgs, 0)),
9564                                         (6, blinded_tail, option),
9565                                 });
9566                                 if payment_id.is_none() {
9567                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9568                                         // instead.
9569                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9570                                 }
9571                                 let path = Path { hops: path_hops, blinded_tail };
9572                                 if path.hops.len() == 0 {
9573                                         return Err(DecodeError::InvalidValue);
9574                                 }
9575                                 if let Some(params) = payment_params.as_mut() {
9576                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9577                                                 if final_cltv_expiry_delta == &0 {
9578                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9579                                                 }
9580                                         }
9581                                 }
9582                                 Ok(HTLCSource::OutboundRoute {
9583                                         session_priv: session_priv.0.unwrap(),
9584                                         first_hop_htlc_msat,
9585                                         path,
9586                                         payment_id: payment_id.unwrap(),
9587                                 })
9588                         }
9589                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9590                         _ => Err(DecodeError::UnknownRequiredFeature),
9591                 }
9592         }
9593 }
9594
9595 impl Writeable for HTLCSource {
9596         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9597                 match self {
9598                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9599                                 0u8.write(writer)?;
9600                                 let payment_id_opt = Some(payment_id);
9601                                 write_tlv_fields!(writer, {
9602                                         (0, session_priv, required),
9603                                         (1, payment_id_opt, option),
9604                                         (2, first_hop_htlc_msat, required),
9605                                         // 3 was previously used to write a PaymentSecret for the payment.
9606                                         (4, path.hops, required_vec),
9607                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9608                                         (6, path.blinded_tail, option),
9609                                  });
9610                         }
9611                         HTLCSource::PreviousHopData(ref field) => {
9612                                 1u8.write(writer)?;
9613                                 field.write(writer)?;
9614                         }
9615                 }
9616                 Ok(())
9617         }
9618 }
9619
9620 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9621         (0, forward_info, required),
9622         (1, prev_user_channel_id, (default_value, 0)),
9623         (2, prev_short_channel_id, required),
9624         (4, prev_htlc_id, required),
9625         (6, prev_funding_outpoint, required),
9626 });
9627
9628 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
9629         (1, FailHTLC) => {
9630                 (0, htlc_id, required),
9631                 (2, err_packet, required),
9632         };
9633         (0, AddHTLC)
9634 );
9635
9636 impl_writeable_tlv_based!(PendingInboundPayment, {
9637         (0, payment_secret, required),
9638         (2, expiry_time, required),
9639         (4, user_payment_id, required),
9640         (6, payment_preimage, required),
9641         (8, min_value_msat, required),
9642 });
9643
9644 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>
9645 where
9646         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9647         T::Target: BroadcasterInterface,
9648         ES::Target: EntropySource,
9649         NS::Target: NodeSigner,
9650         SP::Target: SignerProvider,
9651         F::Target: FeeEstimator,
9652         R::Target: Router,
9653         L::Target: Logger,
9654 {
9655         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9656                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9657
9658                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9659
9660                 self.chain_hash.write(writer)?;
9661                 {
9662                         let best_block = self.best_block.read().unwrap();
9663                         best_block.height().write(writer)?;
9664                         best_block.block_hash().write(writer)?;
9665                 }
9666
9667                 let mut serializable_peer_count: u64 = 0;
9668                 {
9669                         let per_peer_state = self.per_peer_state.read().unwrap();
9670                         let mut number_of_funded_channels = 0;
9671                         for (_, peer_state_mutex) in per_peer_state.iter() {
9672                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9673                                 let peer_state = &mut *peer_state_lock;
9674                                 if !peer_state.ok_to_remove(false) {
9675                                         serializable_peer_count += 1;
9676                                 }
9677
9678                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9679                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9680                                 ).count();
9681                         }
9682
9683                         (number_of_funded_channels as u64).write(writer)?;
9684
9685                         for (_, peer_state_mutex) in per_peer_state.iter() {
9686                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9687                                 let peer_state = &mut *peer_state_lock;
9688                                 for channel in peer_state.channel_by_id.iter().filter_map(
9689                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9690                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9691                                         } else { None }
9692                                 ) {
9693                                         channel.write(writer)?;
9694                                 }
9695                         }
9696                 }
9697
9698                 {
9699                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9700                         (forward_htlcs.len() as u64).write(writer)?;
9701                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9702                                 short_channel_id.write(writer)?;
9703                                 (pending_forwards.len() as u64).write(writer)?;
9704                                 for forward in pending_forwards {
9705                                         forward.write(writer)?;
9706                                 }
9707                         }
9708                 }
9709
9710                 let per_peer_state = self.per_peer_state.write().unwrap();
9711
9712                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9713                 let claimable_payments = self.claimable_payments.lock().unwrap();
9714                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9715
9716                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9717                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9718                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9719                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9720                         payment_hash.write(writer)?;
9721                         (payment.htlcs.len() as u64).write(writer)?;
9722                         for htlc in payment.htlcs.iter() {
9723                                 htlc.write(writer)?;
9724                         }
9725                         htlc_purposes.push(&payment.purpose);
9726                         htlc_onion_fields.push(&payment.onion_fields);
9727                 }
9728
9729                 let mut monitor_update_blocked_actions_per_peer = None;
9730                 let mut peer_states = Vec::new();
9731                 for (_, peer_state_mutex) in per_peer_state.iter() {
9732                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9733                         // of a lockorder violation deadlock - no other thread can be holding any
9734                         // per_peer_state lock at all.
9735                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9736                 }
9737
9738                 (serializable_peer_count).write(writer)?;
9739                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9740                         // Peers which we have no channels to should be dropped once disconnected. As we
9741                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9742                         // consider all peers as disconnected here. There's therefore no need write peers with
9743                         // no channels.
9744                         if !peer_state.ok_to_remove(false) {
9745                                 peer_pubkey.write(writer)?;
9746                                 peer_state.latest_features.write(writer)?;
9747                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9748                                         monitor_update_blocked_actions_per_peer
9749                                                 .get_or_insert_with(Vec::new)
9750                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9751                                 }
9752                         }
9753                 }
9754
9755                 let events = self.pending_events.lock().unwrap();
9756                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9757                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9758                 // refuse to read the new ChannelManager.
9759                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9760                 if events_not_backwards_compatible {
9761                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9762                         // well save the space and not write any events here.
9763                         0u64.write(writer)?;
9764                 } else {
9765                         (events.len() as u64).write(writer)?;
9766                         for (event, _) in events.iter() {
9767                                 event.write(writer)?;
9768                         }
9769                 }
9770
9771                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
9772                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
9773                 // the closing monitor updates were always effectively replayed on startup (either directly
9774                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
9775                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
9776                 0u64.write(writer)?;
9777
9778                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
9779                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
9780                 // likely to be identical.
9781                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9782                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9783
9784                 (pending_inbound_payments.len() as u64).write(writer)?;
9785                 for (hash, pending_payment) in pending_inbound_payments.iter() {
9786                         hash.write(writer)?;
9787                         pending_payment.write(writer)?;
9788                 }
9789
9790                 // For backwards compat, write the session privs and their total length.
9791                 let mut num_pending_outbounds_compat: u64 = 0;
9792                 for (_, outbound) in pending_outbound_payments.iter() {
9793                         if !outbound.is_fulfilled() && !outbound.abandoned() {
9794                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
9795                         }
9796                 }
9797                 num_pending_outbounds_compat.write(writer)?;
9798                 for (_, outbound) in pending_outbound_payments.iter() {
9799                         match outbound {
9800                                 PendingOutboundPayment::Legacy { session_privs } |
9801                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9802                                         for session_priv in session_privs.iter() {
9803                                                 session_priv.write(writer)?;
9804                                         }
9805                                 }
9806                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
9807                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
9808                                 PendingOutboundPayment::Fulfilled { .. } => {},
9809                                 PendingOutboundPayment::Abandoned { .. } => {},
9810                         }
9811                 }
9812
9813                 // Encode without retry info for 0.0.101 compatibility.
9814                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
9815                 for (id, outbound) in pending_outbound_payments.iter() {
9816                         match outbound {
9817                                 PendingOutboundPayment::Legacy { session_privs } |
9818                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9819                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
9820                                 },
9821                                 _ => {},
9822                         }
9823                 }
9824
9825                 let mut pending_intercepted_htlcs = None;
9826                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
9827                 if our_pending_intercepts.len() != 0 {
9828                         pending_intercepted_htlcs = Some(our_pending_intercepts);
9829                 }
9830
9831                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
9832                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
9833                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
9834                         // map. Thus, if there are no entries we skip writing a TLV for it.
9835                         pending_claiming_payments = None;
9836                 }
9837
9838                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
9839                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9840                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
9841                                 if !updates.is_empty() {
9842                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
9843                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
9844                                 }
9845                         }
9846                 }
9847
9848                 write_tlv_fields!(writer, {
9849                         (1, pending_outbound_payments_no_retry, required),
9850                         (2, pending_intercepted_htlcs, option),
9851                         (3, pending_outbound_payments, required),
9852                         (4, pending_claiming_payments, option),
9853                         (5, self.our_network_pubkey, required),
9854                         (6, monitor_update_blocked_actions_per_peer, option),
9855                         (7, self.fake_scid_rand_bytes, required),
9856                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
9857                         (9, htlc_purposes, required_vec),
9858                         (10, in_flight_monitor_updates, option),
9859                         (11, self.probing_cookie_secret, required),
9860                         (13, htlc_onion_fields, optional_vec),
9861                 });
9862
9863                 Ok(())
9864         }
9865 }
9866
9867 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
9868         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9869                 (self.len() as u64).write(w)?;
9870                 for (event, action) in self.iter() {
9871                         event.write(w)?;
9872                         action.write(w)?;
9873                         #[cfg(debug_assertions)] {
9874                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
9875                                 // be persisted and are regenerated on restart. However, if such an event has a
9876                                 // post-event-handling action we'll write nothing for the event and would have to
9877                                 // either forget the action or fail on deserialization (which we do below). Thus,
9878                                 // check that the event is sane here.
9879                                 let event_encoded = event.encode();
9880                                 let event_read: Option<Event> =
9881                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
9882                                 if action.is_some() { assert!(event_read.is_some()); }
9883                         }
9884                 }
9885                 Ok(())
9886         }
9887 }
9888 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
9889         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9890                 let len: u64 = Readable::read(reader)?;
9891                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
9892                 let mut events: Self = VecDeque::with_capacity(cmp::min(
9893                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
9894                         len) as usize);
9895                 for _ in 0..len {
9896                         let ev_opt = MaybeReadable::read(reader)?;
9897                         let action = Readable::read(reader)?;
9898                         if let Some(ev) = ev_opt {
9899                                 events.push_back((ev, action));
9900                         } else if action.is_some() {
9901                                 return Err(DecodeError::InvalidValue);
9902                         }
9903                 }
9904                 Ok(events)
9905         }
9906 }
9907
9908 impl_writeable_tlv_based_enum!(ChannelShutdownState,
9909         (0, NotShuttingDown) => {},
9910         (2, ShutdownInitiated) => {},
9911         (4, ResolvingHTLCs) => {},
9912         (6, NegotiatingClosingFee) => {},
9913         (8, ShutdownComplete) => {}, ;
9914 );
9915
9916 /// Arguments for the creation of a ChannelManager that are not deserialized.
9917 ///
9918 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
9919 /// is:
9920 /// 1) Deserialize all stored [`ChannelMonitor`]s.
9921 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
9922 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
9923 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
9924 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
9925 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
9926 ///    same way you would handle a [`chain::Filter`] call using
9927 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
9928 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
9929 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
9930 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
9931 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
9932 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
9933 ///    the next step.
9934 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
9935 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
9936 ///
9937 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
9938 /// call any other methods on the newly-deserialized [`ChannelManager`].
9939 ///
9940 /// Note that because some channels may be closed during deserialization, it is critical that you
9941 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
9942 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
9943 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
9944 /// not force-close the same channels but consider them live), you may end up revoking a state for
9945 /// which you've already broadcasted the transaction.
9946 ///
9947 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
9948 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9949 where
9950         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9951         T::Target: BroadcasterInterface,
9952         ES::Target: EntropySource,
9953         NS::Target: NodeSigner,
9954         SP::Target: SignerProvider,
9955         F::Target: FeeEstimator,
9956         R::Target: Router,
9957         L::Target: Logger,
9958 {
9959         /// A cryptographically secure source of entropy.
9960         pub entropy_source: ES,
9961
9962         /// A signer that is able to perform node-scoped cryptographic operations.
9963         pub node_signer: NS,
9964
9965         /// The keys provider which will give us relevant keys. Some keys will be loaded during
9966         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
9967         /// signing data.
9968         pub signer_provider: SP,
9969
9970         /// The fee_estimator for use in the ChannelManager in the future.
9971         ///
9972         /// No calls to the FeeEstimator will be made during deserialization.
9973         pub fee_estimator: F,
9974         /// The chain::Watch for use in the ChannelManager in the future.
9975         ///
9976         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
9977         /// you have deserialized ChannelMonitors separately and will add them to your
9978         /// chain::Watch after deserializing this ChannelManager.
9979         pub chain_monitor: M,
9980
9981         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
9982         /// used to broadcast the latest local commitment transactions of channels which must be
9983         /// force-closed during deserialization.
9984         pub tx_broadcaster: T,
9985         /// The router which will be used in the ChannelManager in the future for finding routes
9986         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
9987         ///
9988         /// No calls to the router will be made during deserialization.
9989         pub router: R,
9990         /// The Logger for use in the ChannelManager and which may be used to log information during
9991         /// deserialization.
9992         pub logger: L,
9993         /// Default settings used for new channels. Any existing channels will continue to use the
9994         /// runtime settings which were stored when the ChannelManager was serialized.
9995         pub default_config: UserConfig,
9996
9997         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
9998         /// value.context.get_funding_txo() should be the key).
9999         ///
10000         /// If a monitor is inconsistent with the channel state during deserialization the channel will
10001         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
10002         /// is true for missing channels as well. If there is a monitor missing for which we find
10003         /// channel data Err(DecodeError::InvalidValue) will be returned.
10004         ///
10005         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
10006         /// this struct.
10007         ///
10008         /// This is not exported to bindings users because we have no HashMap bindings
10009         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
10010 }
10011
10012 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10013                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
10014 where
10015         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
10016         T::Target: BroadcasterInterface,
10017         ES::Target: EntropySource,
10018         NS::Target: NodeSigner,
10019         SP::Target: SignerProvider,
10020         F::Target: FeeEstimator,
10021         R::Target: Router,
10022         L::Target: Logger,
10023 {
10024         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
10025         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
10026         /// populate a HashMap directly from C.
10027         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,
10028                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
10029                 Self {
10030                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
10031                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
10032                 }
10033         }
10034 }
10035
10036 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
10037 // SipmleArcChannelManager type:
10038 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10039         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
10040 where
10041         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
10042         T::Target: BroadcasterInterface,
10043         ES::Target: EntropySource,
10044         NS::Target: NodeSigner,
10045         SP::Target: SignerProvider,
10046         F::Target: FeeEstimator,
10047         R::Target: Router,
10048         L::Target: Logger,
10049 {
10050         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10051                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
10052                 Ok((blockhash, Arc::new(chan_manager)))
10053         }
10054 }
10055
10056 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10057         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
10058 where
10059         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
10060         T::Target: BroadcasterInterface,
10061         ES::Target: EntropySource,
10062         NS::Target: NodeSigner,
10063         SP::Target: SignerProvider,
10064         F::Target: FeeEstimator,
10065         R::Target: Router,
10066         L::Target: Logger,
10067 {
10068         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10069                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
10070
10071                 let chain_hash: ChainHash = Readable::read(reader)?;
10072                 let best_block_height: u32 = Readable::read(reader)?;
10073                 let best_block_hash: BlockHash = Readable::read(reader)?;
10074
10075                 let mut failed_htlcs = Vec::new();
10076
10077                 let channel_count: u64 = Readable::read(reader)?;
10078                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
10079                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10080                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10081                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10082                 let mut channel_closures = VecDeque::new();
10083                 let mut close_background_events = Vec::new();
10084                 for _ in 0..channel_count {
10085                         let mut channel: Channel<SP> = Channel::read(reader, (
10086                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
10087                         ))?;
10088                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10089                         funding_txo_set.insert(funding_txo.clone());
10090                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10091                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
10092                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
10093                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
10094                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10095                                         // But if the channel is behind of the monitor, close the channel:
10096                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
10097                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
10098                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10099                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
10100                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
10101                                         }
10102                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
10103                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
10104                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
10105                                         }
10106                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
10107                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
10108                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
10109                                         }
10110                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
10111                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
10112                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
10113                                         }
10114                                         let mut shutdown_result = channel.context.force_shutdown(true);
10115                                         if shutdown_result.unbroadcasted_batch_funding_txid.is_some() {
10116                                                 return Err(DecodeError::InvalidValue);
10117                                         }
10118                                         if let Some((counterparty_node_id, funding_txo, update)) = shutdown_result.monitor_update {
10119                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10120                                                         counterparty_node_id, funding_txo, update
10121                                                 });
10122                                         }
10123                                         failed_htlcs.append(&mut shutdown_result.dropped_outbound_htlcs);
10124                                         channel_closures.push_back((events::Event::ChannelClosed {
10125                                                 channel_id: channel.context.channel_id(),
10126                                                 user_channel_id: channel.context.get_user_id(),
10127                                                 reason: ClosureReason::OutdatedChannelManager,
10128                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10129                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10130                                         }, None));
10131                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
10132                                                 let mut found_htlc = false;
10133                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
10134                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
10135                                                 }
10136                                                 if !found_htlc {
10137                                                         // If we have some HTLCs in the channel which are not present in the newer
10138                                                         // ChannelMonitor, they have been removed and should be failed back to
10139                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
10140                                                         // were actually claimed we'd have generated and ensured the previous-hop
10141                                                         // claim update ChannelMonitor updates were persisted prior to persising
10142                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
10143                                                         // backwards leg of the HTLC will simply be rejected.
10144                                                         log_info!(args.logger,
10145                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
10146                                                                 &channel.context.channel_id(), &payment_hash);
10147                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10148                                                 }
10149                                         }
10150                                 } else {
10151                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
10152                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
10153                                                 monitor.get_latest_update_id());
10154                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
10155                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10156                                         }
10157                                         if channel.context.is_funding_broadcast() {
10158                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
10159                                         }
10160                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
10161                                                 hash_map::Entry::Occupied(mut entry) => {
10162                                                         let by_id_map = entry.get_mut();
10163                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10164                                                 },
10165                                                 hash_map::Entry::Vacant(entry) => {
10166                                                         let mut by_id_map = HashMap::new();
10167                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10168                                                         entry.insert(by_id_map);
10169                                                 }
10170                                         }
10171                                 }
10172                         } else if channel.is_awaiting_initial_mon_persist() {
10173                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
10174                                 // was in-progress, we never broadcasted the funding transaction and can still
10175                                 // safely discard the channel.
10176                                 let _ = channel.context.force_shutdown(false);
10177                                 channel_closures.push_back((events::Event::ChannelClosed {
10178                                         channel_id: channel.context.channel_id(),
10179                                         user_channel_id: channel.context.get_user_id(),
10180                                         reason: ClosureReason::DisconnectedPeer,
10181                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10182                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10183                                 }, None));
10184                         } else {
10185                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
10186                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10187                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10188                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
10189                                 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");
10190                                 return Err(DecodeError::InvalidValue);
10191                         }
10192                 }
10193
10194                 for (funding_txo, _) in args.channel_monitors.iter() {
10195                         if !funding_txo_set.contains(funding_txo) {
10196                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
10197                                         &funding_txo.to_channel_id());
10198                                 let monitor_update = ChannelMonitorUpdate {
10199                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
10200                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
10201                                 };
10202                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
10203                         }
10204                 }
10205
10206                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
10207                 let forward_htlcs_count: u64 = Readable::read(reader)?;
10208                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
10209                 for _ in 0..forward_htlcs_count {
10210                         let short_channel_id = Readable::read(reader)?;
10211                         let pending_forwards_count: u64 = Readable::read(reader)?;
10212                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
10213                         for _ in 0..pending_forwards_count {
10214                                 pending_forwards.push(Readable::read(reader)?);
10215                         }
10216                         forward_htlcs.insert(short_channel_id, pending_forwards);
10217                 }
10218
10219                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
10220                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
10221                 for _ in 0..claimable_htlcs_count {
10222                         let payment_hash = Readable::read(reader)?;
10223                         let previous_hops_len: u64 = Readable::read(reader)?;
10224                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
10225                         for _ in 0..previous_hops_len {
10226                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
10227                         }
10228                         claimable_htlcs_list.push((payment_hash, previous_hops));
10229                 }
10230
10231                 let peer_state_from_chans = |channel_by_id| {
10232                         PeerState {
10233                                 channel_by_id,
10234                                 inbound_channel_request_by_id: HashMap::new(),
10235                                 latest_features: InitFeatures::empty(),
10236                                 pending_msg_events: Vec::new(),
10237                                 in_flight_monitor_updates: BTreeMap::new(),
10238                                 monitor_update_blocked_actions: BTreeMap::new(),
10239                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
10240                                 is_connected: false,
10241                         }
10242                 };
10243
10244                 let peer_count: u64 = Readable::read(reader)?;
10245                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
10246                 for _ in 0..peer_count {
10247                         let peer_pubkey = Readable::read(reader)?;
10248                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
10249                         let mut peer_state = peer_state_from_chans(peer_chans);
10250                         peer_state.latest_features = Readable::read(reader)?;
10251                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
10252                 }
10253
10254                 let event_count: u64 = Readable::read(reader)?;
10255                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
10256                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
10257                 for _ in 0..event_count {
10258                         match MaybeReadable::read(reader)? {
10259                                 Some(event) => pending_events_read.push_back((event, None)),
10260                                 None => continue,
10261                         }
10262                 }
10263
10264                 let background_event_count: u64 = Readable::read(reader)?;
10265                 for _ in 0..background_event_count {
10266                         match <u8 as Readable>::read(reader)? {
10267                                 0 => {
10268                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
10269                                         // however we really don't (and never did) need them - we regenerate all
10270                                         // on-startup monitor updates.
10271                                         let _: OutPoint = Readable::read(reader)?;
10272                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
10273                                 }
10274                                 _ => return Err(DecodeError::InvalidValue),
10275                         }
10276                 }
10277
10278                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
10279                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
10280
10281                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
10282                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
10283                 for _ in 0..pending_inbound_payment_count {
10284                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
10285                                 return Err(DecodeError::InvalidValue);
10286                         }
10287                 }
10288
10289                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
10290                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
10291                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
10292                 for _ in 0..pending_outbound_payments_count_compat {
10293                         let session_priv = Readable::read(reader)?;
10294                         let payment = PendingOutboundPayment::Legacy {
10295                                 session_privs: [session_priv].iter().cloned().collect()
10296                         };
10297                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
10298                                 return Err(DecodeError::InvalidValue)
10299                         };
10300                 }
10301
10302                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
10303                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
10304                 let mut pending_outbound_payments = None;
10305                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
10306                 let mut received_network_pubkey: Option<PublicKey> = None;
10307                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
10308                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
10309                 let mut claimable_htlc_purposes = None;
10310                 let mut claimable_htlc_onion_fields = None;
10311                 let mut pending_claiming_payments = Some(HashMap::new());
10312                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
10313                 let mut events_override = None;
10314                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
10315                 read_tlv_fields!(reader, {
10316                         (1, pending_outbound_payments_no_retry, option),
10317                         (2, pending_intercepted_htlcs, option),
10318                         (3, pending_outbound_payments, option),
10319                         (4, pending_claiming_payments, option),
10320                         (5, received_network_pubkey, option),
10321                         (6, monitor_update_blocked_actions_per_peer, option),
10322                         (7, fake_scid_rand_bytes, option),
10323                         (8, events_override, option),
10324                         (9, claimable_htlc_purposes, optional_vec),
10325                         (10, in_flight_monitor_updates, option),
10326                         (11, probing_cookie_secret, option),
10327                         (13, claimable_htlc_onion_fields, optional_vec),
10328                 });
10329                 if fake_scid_rand_bytes.is_none() {
10330                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
10331                 }
10332
10333                 if probing_cookie_secret.is_none() {
10334                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
10335                 }
10336
10337                 if let Some(events) = events_override {
10338                         pending_events_read = events;
10339                 }
10340
10341                 if !channel_closures.is_empty() {
10342                         pending_events_read.append(&mut channel_closures);
10343                 }
10344
10345                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
10346                         pending_outbound_payments = Some(pending_outbound_payments_compat);
10347                 } else if pending_outbound_payments.is_none() {
10348                         let mut outbounds = HashMap::new();
10349                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
10350                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
10351                         }
10352                         pending_outbound_payments = Some(outbounds);
10353                 }
10354                 let pending_outbounds = OutboundPayments {
10355                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
10356                         retry_lock: Mutex::new(())
10357                 };
10358
10359                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
10360                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
10361                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
10362                 // replayed, and for each monitor update we have to replay we have to ensure there's a
10363                 // `ChannelMonitor` for it.
10364                 //
10365                 // In order to do so we first walk all of our live channels (so that we can check their
10366                 // state immediately after doing the update replays, when we have the `update_id`s
10367                 // available) and then walk any remaining in-flight updates.
10368                 //
10369                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10370                 let mut pending_background_events = Vec::new();
10371                 macro_rules! handle_in_flight_updates {
10372                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10373                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
10374                         ) => { {
10375                                 let mut max_in_flight_update_id = 0;
10376                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10377                                 for update in $chan_in_flight_upds.iter() {
10378                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10379                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
10380                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10381                                         pending_background_events.push(
10382                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10383                                                         counterparty_node_id: $counterparty_node_id,
10384                                                         funding_txo: $funding_txo,
10385                                                         update: update.clone(),
10386                                                 });
10387                                 }
10388                                 if $chan_in_flight_upds.is_empty() {
10389                                         // We had some updates to apply, but it turns out they had completed before we
10390                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10391                                         // the completion actions for any monitor updates, but otherwise are done.
10392                                         pending_background_events.push(
10393                                                 BackgroundEvent::MonitorUpdatesComplete {
10394                                                         counterparty_node_id: $counterparty_node_id,
10395                                                         channel_id: $funding_txo.to_channel_id(),
10396                                                 });
10397                                 }
10398                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10399                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
10400                                         return Err(DecodeError::InvalidValue);
10401                                 }
10402                                 max_in_flight_update_id
10403                         } }
10404                 }
10405
10406                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10407                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10408                         let peer_state = &mut *peer_state_lock;
10409                         for phase in peer_state.channel_by_id.values() {
10410                                 if let ChannelPhase::Funded(chan) = phase {
10411                                         // Channels that were persisted have to be funded, otherwise they should have been
10412                                         // discarded.
10413                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10414                                         let monitor = args.channel_monitors.get(&funding_txo)
10415                                                 .expect("We already checked for monitor presence when loading channels");
10416                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10417                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10418                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10419                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10420                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10421                                                                         funding_txo, monitor, peer_state, ""));
10422                                                 }
10423                                         }
10424                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10425                                                 // If the channel is ahead of the monitor, return InvalidValue:
10426                                                 log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10427                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10428                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10429                                                 log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10430                                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10431                                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10432                                                 log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10433                                                 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");
10434                                                 return Err(DecodeError::InvalidValue);
10435                                         }
10436                                 } else {
10437                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10438                                         // created in this `channel_by_id` map.
10439                                         debug_assert!(false);
10440                                         return Err(DecodeError::InvalidValue);
10441                                 }
10442                         }
10443                 }
10444
10445                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10446                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10447                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10448                                         // Now that we've removed all the in-flight monitor updates for channels that are
10449                                         // still open, we need to replay any monitor updates that are for closed channels,
10450                                         // creating the neccessary peer_state entries as we go.
10451                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10452                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
10453                                         });
10454                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10455                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10456                                                 funding_txo, monitor, peer_state, "closed ");
10457                                 } else {
10458                                         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!");
10459                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
10460                                                 &funding_txo.to_channel_id());
10461                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10462                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10463                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10464                                         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");
10465                                         return Err(DecodeError::InvalidValue);
10466                                 }
10467                         }
10468                 }
10469
10470                 // Note that we have to do the above replays before we push new monitor updates.
10471                 pending_background_events.append(&mut close_background_events);
10472
10473                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10474                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10475                 // have a fully-constructed `ChannelManager` at the end.
10476                 let mut pending_claims_to_replay = Vec::new();
10477
10478                 {
10479                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10480                         // ChannelMonitor data for any channels for which we do not have authorative state
10481                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10482                         // corresponding `Channel` at all).
10483                         // This avoids several edge-cases where we would otherwise "forget" about pending
10484                         // payments which are still in-flight via their on-chain state.
10485                         // We only rebuild the pending payments map if we were most recently serialized by
10486                         // 0.0.102+
10487                         for (_, monitor) in args.channel_monitors.iter() {
10488                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
10489                                 if counterparty_opt.is_none() {
10490                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10491                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10492                                                         if path.hops.is_empty() {
10493                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
10494                                                                 return Err(DecodeError::InvalidValue);
10495                                                         }
10496
10497                                                         let path_amt = path.final_value_msat();
10498                                                         let mut session_priv_bytes = [0; 32];
10499                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10500                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10501                                                                 hash_map::Entry::Occupied(mut entry) => {
10502                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10503                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10504                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), &htlc.payment_hash);
10505                                                                 },
10506                                                                 hash_map::Entry::Vacant(entry) => {
10507                                                                         let path_fee = path.fee_msat();
10508                                                                         entry.insert(PendingOutboundPayment::Retryable {
10509                                                                                 retry_strategy: None,
10510                                                                                 attempts: PaymentAttempts::new(),
10511                                                                                 payment_params: None,
10512                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
10513                                                                                 payment_hash: htlc.payment_hash,
10514                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10515                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10516                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10517                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10518                                                                                 pending_amt_msat: path_amt,
10519                                                                                 pending_fee_msat: Some(path_fee),
10520                                                                                 total_msat: path_amt,
10521                                                                                 starting_block_height: best_block_height,
10522                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10523                                                                         });
10524                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10525                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10526                                                                 }
10527                                                         }
10528                                                 }
10529                                         }
10530                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10531                                                 match htlc_source {
10532                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10533                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10534                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10535                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10536                                                                 };
10537                                                                 // The ChannelMonitor is now responsible for this HTLC's
10538                                                                 // failure/success and will let us know what its outcome is. If we
10539                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10540                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10541                                                                 // the monitor was when forwarding the payment.
10542                                                                 forward_htlcs.retain(|_, forwards| {
10543                                                                         forwards.retain(|forward| {
10544                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10545                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10546                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10547                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10548                                                                                                 false
10549                                                                                         } else { true }
10550                                                                                 } else { true }
10551                                                                         });
10552                                                                         !forwards.is_empty()
10553                                                                 });
10554                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10555                                                                         if pending_forward_matches_htlc(&htlc_info) {
10556                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10557                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10558                                                                                 pending_events_read.retain(|(event, _)| {
10559                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10560                                                                                                 intercepted_id != ev_id
10561                                                                                         } else { true }
10562                                                                                 });
10563                                                                                 false
10564                                                                         } else { true }
10565                                                                 });
10566                                                         },
10567                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10568                                                                 if let Some(preimage) = preimage_opt {
10569                                                                         let pending_events = Mutex::new(pending_events_read);
10570                                                                         // Note that we set `from_onchain` to "false" here,
10571                                                                         // deliberately keeping the pending payment around forever.
10572                                                                         // Given it should only occur when we have a channel we're
10573                                                                         // force-closing for being stale that's okay.
10574                                                                         // The alternative would be to wipe the state when claiming,
10575                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10576                                                                         // it and the `PaymentSent` on every restart until the
10577                                                                         // `ChannelMonitor` is removed.
10578                                                                         let compl_action =
10579                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10580                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10581                                                                                         counterparty_node_id: path.hops[0].pubkey,
10582                                                                                 };
10583                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10584                                                                                 path, false, compl_action, &pending_events, &args.logger);
10585                                                                         pending_events_read = pending_events.into_inner().unwrap();
10586                                                                 }
10587                                                         },
10588                                                 }
10589                                         }
10590                                 }
10591
10592                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10593                                 // preimages from it which may be needed in upstream channels for forwarded
10594                                 // payments.
10595                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10596                                         .into_iter()
10597                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10598                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10599                                                         if let Some(payment_preimage) = preimage_opt {
10600                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10601                                                                         // Check if `counterparty_opt.is_none()` to see if the
10602                                                                         // downstream chan is closed (because we don't have a
10603                                                                         // channel_id -> peer map entry).
10604                                                                         counterparty_opt.is_none(),
10605                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10606                                                                         monitor.get_funding_txo().0))
10607                                                         } else { None }
10608                                                 } else {
10609                                                         // If it was an outbound payment, we've handled it above - if a preimage
10610                                                         // came in and we persisted the `ChannelManager` we either handled it and
10611                                                         // are good to go or the channel force-closed - we don't have to handle the
10612                                                         // channel still live case here.
10613                                                         None
10614                                                 }
10615                                         });
10616                                 for tuple in outbound_claimed_htlcs_iter {
10617                                         pending_claims_to_replay.push(tuple);
10618                                 }
10619                         }
10620                 }
10621
10622                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10623                         // If we have pending HTLCs to forward, assume we either dropped a
10624                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10625                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10626                         // constant as enough time has likely passed that we should simply handle the forwards
10627                         // now, or at least after the user gets a chance to reconnect to our peers.
10628                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10629                                 time_forwardable: Duration::from_secs(2),
10630                         }, None));
10631                 }
10632
10633                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10634                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10635
10636                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10637                 if let Some(purposes) = claimable_htlc_purposes {
10638                         if purposes.len() != claimable_htlcs_list.len() {
10639                                 return Err(DecodeError::InvalidValue);
10640                         }
10641                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10642                                 if onion_fields.len() != claimable_htlcs_list.len() {
10643                                         return Err(DecodeError::InvalidValue);
10644                                 }
10645                                 for (purpose, (onion, (payment_hash, htlcs))) in
10646                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10647                                 {
10648                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10649                                                 purpose, htlcs, onion_fields: onion,
10650                                         });
10651                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10652                                 }
10653                         } else {
10654                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10655                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10656                                                 purpose, htlcs, onion_fields: None,
10657                                         });
10658                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10659                                 }
10660                         }
10661                 } else {
10662                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10663                         // include a `_legacy_hop_data` in the `OnionPayload`.
10664                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10665                                 if htlcs.is_empty() {
10666                                         return Err(DecodeError::InvalidValue);
10667                                 }
10668                                 let purpose = match &htlcs[0].onion_payload {
10669                                         OnionPayload::Invoice { _legacy_hop_data } => {
10670                                                 if let Some(hop_data) = _legacy_hop_data {
10671                                                         events::PaymentPurpose::InvoicePayment {
10672                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10673                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10674                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10675                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10676                                                                                 Err(()) => {
10677                                                                                         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);
10678                                                                                         return Err(DecodeError::InvalidValue);
10679                                                                                 }
10680                                                                         }
10681                                                                 },
10682                                                                 payment_secret: hop_data.payment_secret,
10683                                                         }
10684                                                 } else { return Err(DecodeError::InvalidValue); }
10685                                         },
10686                                         OnionPayload::Spontaneous(payment_preimage) =>
10687                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10688                                 };
10689                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10690                                         purpose, htlcs, onion_fields: None,
10691                                 });
10692                         }
10693                 }
10694
10695                 let mut secp_ctx = Secp256k1::new();
10696                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10697
10698                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10699                         Ok(key) => key,
10700                         Err(()) => return Err(DecodeError::InvalidValue)
10701                 };
10702                 if let Some(network_pubkey) = received_network_pubkey {
10703                         if network_pubkey != our_network_pubkey {
10704                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10705                                 return Err(DecodeError::InvalidValue);
10706                         }
10707                 }
10708
10709                 let mut outbound_scid_aliases = HashSet::new();
10710                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10711                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10712                         let peer_state = &mut *peer_state_lock;
10713                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10714                                 if let ChannelPhase::Funded(chan) = phase {
10715                                         if chan.context.outbound_scid_alias() == 0 {
10716                                                 let mut outbound_scid_alias;
10717                                                 loop {
10718                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10719                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10720                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10721                                                 }
10722                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10723                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10724                                                 // Note that in rare cases its possible to hit this while reading an older
10725                                                 // channel if we just happened to pick a colliding outbound alias above.
10726                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10727                                                 return Err(DecodeError::InvalidValue);
10728                                         }
10729                                         if chan.context.is_usable() {
10730                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10731                                                         // Note that in rare cases its possible to hit this while reading an older
10732                                                         // channel if we just happened to pick a colliding outbound alias above.
10733                                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10734                                                         return Err(DecodeError::InvalidValue);
10735                                                 }
10736                                         }
10737                                 } else {
10738                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10739                                         // created in this `channel_by_id` map.
10740                                         debug_assert!(false);
10741                                         return Err(DecodeError::InvalidValue);
10742                                 }
10743                         }
10744                 }
10745
10746                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10747
10748                 for (_, monitor) in args.channel_monitors.iter() {
10749                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10750                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10751                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10752                                         let mut claimable_amt_msat = 0;
10753                                         let mut receiver_node_id = Some(our_network_pubkey);
10754                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
10755                                         if phantom_shared_secret.is_some() {
10756                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
10757                                                         .expect("Failed to get node_id for phantom node recipient");
10758                                                 receiver_node_id = Some(phantom_pubkey)
10759                                         }
10760                                         for claimable_htlc in &payment.htlcs {
10761                                                 claimable_amt_msat += claimable_htlc.value;
10762
10763                                                 // Add a holding-cell claim of the payment to the Channel, which should be
10764                                                 // applied ~immediately on peer reconnection. Because it won't generate a
10765                                                 // new commitment transaction we can just provide the payment preimage to
10766                                                 // the corresponding ChannelMonitor and nothing else.
10767                                                 //
10768                                                 // We do so directly instead of via the normal ChannelMonitor update
10769                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
10770                                                 // we're not allowed to call it directly yet. Further, we do the update
10771                                                 // without incrementing the ChannelMonitor update ID as there isn't any
10772                                                 // reason to.
10773                                                 // If we were to generate a new ChannelMonitor update ID here and then
10774                                                 // crash before the user finishes block connect we'd end up force-closing
10775                                                 // this channel as well. On the flip side, there's no harm in restarting
10776                                                 // without the new monitor persisted - we'll end up right back here on
10777                                                 // restart.
10778                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
10779                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
10780                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
10781                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10782                                                         let peer_state = &mut *peer_state_lock;
10783                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
10784                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
10785                                                         }
10786                                                 }
10787                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
10788                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
10789                                                 }
10790                                         }
10791                                         pending_events_read.push_back((events::Event::PaymentClaimed {
10792                                                 receiver_node_id,
10793                                                 payment_hash,
10794                                                 purpose: payment.purpose,
10795                                                 amount_msat: claimable_amt_msat,
10796                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
10797                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
10798                                         }, None));
10799                                 }
10800                         }
10801                 }
10802
10803                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
10804                         if let Some(peer_state) = per_peer_state.get(&node_id) {
10805                                 for (_, actions) in monitor_update_blocked_actions.iter() {
10806                                         for action in actions.iter() {
10807                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
10808                                                         downstream_counterparty_and_funding_outpoint:
10809                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
10810                                                 } = action {
10811                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
10812                                                                 log_trace!(args.logger,
10813                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
10814                                                                         blocked_channel_outpoint.to_channel_id());
10815                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
10816                                                                         .entry(blocked_channel_outpoint.to_channel_id())
10817                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
10818                                                         } else {
10819                                                                 // If the channel we were blocking has closed, we don't need to
10820                                                                 // worry about it - the blocked monitor update should never have
10821                                                                 // been released from the `Channel` object so it can't have
10822                                                                 // completed, and if the channel closed there's no reason to bother
10823                                                                 // anymore.
10824                                                         }
10825                                                 }
10826                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
10827                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
10828                                                 }
10829                                         }
10830                                 }
10831                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
10832                         } else {
10833                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
10834                                 return Err(DecodeError::InvalidValue);
10835                         }
10836                 }
10837
10838                 let channel_manager = ChannelManager {
10839                         chain_hash,
10840                         fee_estimator: bounded_fee_estimator,
10841                         chain_monitor: args.chain_monitor,
10842                         tx_broadcaster: args.tx_broadcaster,
10843                         router: args.router,
10844
10845                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
10846
10847                         inbound_payment_key: expanded_inbound_key,
10848                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
10849                         pending_outbound_payments: pending_outbounds,
10850                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
10851
10852                         forward_htlcs: Mutex::new(forward_htlcs),
10853                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
10854                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
10855                         id_to_peer: Mutex::new(id_to_peer),
10856                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
10857                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
10858
10859                         probing_cookie_secret: probing_cookie_secret.unwrap(),
10860
10861                         our_network_pubkey,
10862                         secp_ctx,
10863
10864                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
10865
10866                         per_peer_state: FairRwLock::new(per_peer_state),
10867
10868                         pending_events: Mutex::new(pending_events_read),
10869                         pending_events_processor: AtomicBool::new(false),
10870                         pending_background_events: Mutex::new(pending_background_events),
10871                         total_consistency_lock: RwLock::new(()),
10872                         background_events_processed_since_startup: AtomicBool::new(false),
10873
10874                         event_persist_notifier: Notifier::new(),
10875                         needs_persist_flag: AtomicBool::new(false),
10876
10877                         funding_batch_states: Mutex::new(BTreeMap::new()),
10878
10879                         pending_offers_messages: Mutex::new(Vec::new()),
10880
10881                         entropy_source: args.entropy_source,
10882                         node_signer: args.node_signer,
10883                         signer_provider: args.signer_provider,
10884
10885                         logger: args.logger,
10886                         default_configuration: args.default_config,
10887                 };
10888
10889                 for htlc_source in failed_htlcs.drain(..) {
10890                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
10891                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
10892                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
10893                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
10894                 }
10895
10896                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
10897                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
10898                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
10899                         // channel is closed we just assume that it probably came from an on-chain claim.
10900                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
10901                                 downstream_closed, true, downstream_node_id, downstream_funding);
10902                 }
10903
10904                 //TODO: Broadcast channel update for closed channels, but only after we've made a
10905                 //connection or two.
10906
10907                 Ok((best_block_hash.clone(), channel_manager))
10908         }
10909 }
10910
10911 #[cfg(test)]
10912 mod tests {
10913         use bitcoin::hashes::Hash;
10914         use bitcoin::hashes::sha256::Hash as Sha256;
10915         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10916         use core::sync::atomic::Ordering;
10917         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
10918         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
10919         use crate::ln::ChannelId;
10920         use crate::ln::channelmanager::{create_recv_pending_htlc_info, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
10921         use crate::ln::features::{ChannelFeatures, NodeFeatures};
10922         use crate::ln::functional_test_utils::*;
10923         use crate::ln::msgs::{self, ErrorAction};
10924         use crate::ln::msgs::ChannelMessageHandler;
10925         use crate::routing::router::{Path, PaymentParameters, RouteHop, RouteParameters, find_route};
10926         use crate::util::errors::APIError;
10927         use crate::util::test_utils;
10928         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
10929         use crate::sign::EntropySource;
10930
10931         #[test]
10932         fn test_notify_limits() {
10933                 // Check that a few cases which don't require the persistence of a new ChannelManager,
10934                 // indeed, do not cause the persistence of a new ChannelManager.
10935                 let chanmon_cfgs = create_chanmon_cfgs(3);
10936                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10937                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10938                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10939
10940                 // All nodes start with a persistable update pending as `create_network` connects each node
10941                 // with all other nodes to make most tests simpler.
10942                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10943                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10944                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10945
10946                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10947
10948                 // We check that the channel info nodes have doesn't change too early, even though we try
10949                 // to connect messages with new values
10950                 chan.0.contents.fee_base_msat *= 2;
10951                 chan.1.contents.fee_base_msat *= 2;
10952                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
10953                         &nodes[1].node.get_our_node_id()).pop().unwrap();
10954                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
10955                         &nodes[0].node.get_our_node_id()).pop().unwrap();
10956
10957                 // The first two nodes (which opened a channel) should now require fresh persistence
10958                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10959                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10960                 // ... but the last node should not.
10961                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10962                 // After persisting the first two nodes they should no longer need fresh persistence.
10963                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10964                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10965
10966                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
10967                 // about the channel.
10968                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
10969                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
10970                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10971
10972                 // The nodes which are a party to the channel should also ignore messages from unrelated
10973                 // parties.
10974                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10975                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10976                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10977                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10978                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10979                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10980
10981                 // At this point the channel info given by peers should still be the same.
10982                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10983                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10984
10985                 // An earlier version of handle_channel_update didn't check the directionality of the
10986                 // update message and would always update the local fee info, even if our peer was
10987                 // (spuriously) forwarding us our own channel_update.
10988                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
10989                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
10990                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
10991
10992                 // First deliver each peers' own message, checking that the node doesn't need to be
10993                 // persisted and that its channel info remains the same.
10994                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
10995                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
10996                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10997                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10998                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10999                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11000
11001                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
11002                 // the channel info has updated.
11003                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
11004                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
11005                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11006                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11007                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
11008                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
11009         }
11010
11011         #[test]
11012         fn test_keysend_dup_hash_partial_mpp() {
11013                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
11014                 // expected.
11015                 let chanmon_cfgs = create_chanmon_cfgs(2);
11016                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11017                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11018                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11019                 create_announced_chan_between_nodes(&nodes, 0, 1);
11020
11021                 // First, send a partial MPP payment.
11022                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
11023                 let mut mpp_route = route.clone();
11024                 mpp_route.paths.push(mpp_route.paths[0].clone());
11025
11026                 let payment_id = PaymentId([42; 32]);
11027                 // Use the utility function send_payment_along_path to send the payment with MPP data which
11028                 // indicates there are more HTLCs coming.
11029                 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.
11030                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
11031                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
11032                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
11033                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
11034                 check_added_monitors!(nodes[0], 1);
11035                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11036                 assert_eq!(events.len(), 1);
11037                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
11038
11039                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
11040                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11041                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11042                 check_added_monitors!(nodes[0], 1);
11043                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11044                 assert_eq!(events.len(), 1);
11045                 let ev = events.drain(..).next().unwrap();
11046                 let payment_event = SendEvent::from_event(ev);
11047                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11048                 check_added_monitors!(nodes[1], 0);
11049                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11050                 expect_pending_htlcs_forwardable!(nodes[1]);
11051                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
11052                 check_added_monitors!(nodes[1], 1);
11053                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11054                 assert!(updates.update_add_htlcs.is_empty());
11055                 assert!(updates.update_fulfill_htlcs.is_empty());
11056                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11057                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11058                 assert!(updates.update_fee.is_none());
11059                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11060                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11061                 expect_payment_failed!(nodes[0], our_payment_hash, true);
11062
11063                 // Send the second half of the original MPP payment.
11064                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
11065                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
11066                 check_added_monitors!(nodes[0], 1);
11067                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11068                 assert_eq!(events.len(), 1);
11069                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
11070
11071                 // Claim the full MPP payment. Note that we can't use a test utility like
11072                 // claim_funds_along_route because the ordering of the messages causes the second half of the
11073                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
11074                 // lightning messages manually.
11075                 nodes[1].node.claim_funds(payment_preimage);
11076                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
11077                 check_added_monitors!(nodes[1], 2);
11078
11079                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11080                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
11081                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
11082                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
11083                 check_added_monitors!(nodes[0], 1);
11084                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11085                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
11086                 check_added_monitors!(nodes[1], 1);
11087                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11088                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
11089                 check_added_monitors!(nodes[1], 1);
11090                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11091                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
11092                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
11093                 check_added_monitors!(nodes[0], 1);
11094                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
11095                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
11096                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11097                 check_added_monitors!(nodes[0], 1);
11098                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
11099                 check_added_monitors!(nodes[1], 1);
11100                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
11101                 check_added_monitors!(nodes[1], 1);
11102                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11103                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
11104                 check_added_monitors!(nodes[0], 1);
11105
11106                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
11107                 // path's success and a PaymentPathSuccessful event for each path's success.
11108                 let events = nodes[0].node.get_and_clear_pending_events();
11109                 assert_eq!(events.len(), 2);
11110                 match events[0] {
11111                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11112                                 assert_eq!(payment_id, *actual_payment_id);
11113                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11114                                 assert_eq!(route.paths[0], *path);
11115                         },
11116                         _ => panic!("Unexpected event"),
11117                 }
11118                 match events[1] {
11119                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11120                                 assert_eq!(payment_id, *actual_payment_id);
11121                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11122                                 assert_eq!(route.paths[0], *path);
11123                         },
11124                         _ => panic!("Unexpected event"),
11125                 }
11126         }
11127
11128         #[test]
11129         fn test_keysend_dup_payment_hash() {
11130                 do_test_keysend_dup_payment_hash(false);
11131                 do_test_keysend_dup_payment_hash(true);
11132         }
11133
11134         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
11135                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
11136                 //      outbound regular payment fails as expected.
11137                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
11138                 //      fails as expected.
11139                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
11140                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
11141                 //      reject MPP keysend payments, since in this case where the payment has no payment
11142                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
11143                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
11144                 //      payment secrets and reject otherwise.
11145                 let chanmon_cfgs = create_chanmon_cfgs(2);
11146                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11147                 let mut mpp_keysend_cfg = test_default_channel_config();
11148                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
11149                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
11150                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11151                 create_announced_chan_between_nodes(&nodes, 0, 1);
11152                 let scorer = test_utils::TestScorer::new();
11153                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11154
11155                 // To start (1), send a regular payment but don't claim it.
11156                 let expected_route = [&nodes[1]];
11157                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
11158
11159                 // Next, attempt a keysend payment and make sure it fails.
11160                 let route_params = RouteParameters::from_payment_params_and_value(
11161                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
11162                         TEST_FINAL_CLTV, false), 100_000);
11163                 let route = find_route(
11164                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11165                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11166                 ).unwrap();
11167                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11168                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11169                 check_added_monitors!(nodes[0], 1);
11170                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11171                 assert_eq!(events.len(), 1);
11172                 let ev = events.drain(..).next().unwrap();
11173                 let payment_event = SendEvent::from_event(ev);
11174                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11175                 check_added_monitors!(nodes[1], 0);
11176                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11177                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
11178                 // fails), the second will process the resulting failure and fail the HTLC backward
11179                 expect_pending_htlcs_forwardable!(nodes[1]);
11180                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11181                 check_added_monitors!(nodes[1], 1);
11182                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11183                 assert!(updates.update_add_htlcs.is_empty());
11184                 assert!(updates.update_fulfill_htlcs.is_empty());
11185                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11186                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11187                 assert!(updates.update_fee.is_none());
11188                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11189                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11190                 expect_payment_failed!(nodes[0], payment_hash, true);
11191
11192                 // Finally, claim the original payment.
11193                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11194
11195                 // To start (2), send a keysend payment but don't claim it.
11196                 let payment_preimage = PaymentPreimage([42; 32]);
11197                 let route = find_route(
11198                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11199                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11200                 ).unwrap();
11201                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11202                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11203                 check_added_monitors!(nodes[0], 1);
11204                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11205                 assert_eq!(events.len(), 1);
11206                 let event = events.pop().unwrap();
11207                 let path = vec![&nodes[1]];
11208                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11209
11210                 // Next, attempt a regular payment and make sure it fails.
11211                 let payment_secret = PaymentSecret([43; 32]);
11212                 nodes[0].node.send_payment_with_route(&route, payment_hash,
11213                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
11214                 check_added_monitors!(nodes[0], 1);
11215                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11216                 assert_eq!(events.len(), 1);
11217                 let ev = events.drain(..).next().unwrap();
11218                 let payment_event = SendEvent::from_event(ev);
11219                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11220                 check_added_monitors!(nodes[1], 0);
11221                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11222                 expect_pending_htlcs_forwardable!(nodes[1]);
11223                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11224                 check_added_monitors!(nodes[1], 1);
11225                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11226                 assert!(updates.update_add_htlcs.is_empty());
11227                 assert!(updates.update_fulfill_htlcs.is_empty());
11228                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11229                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11230                 assert!(updates.update_fee.is_none());
11231                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11232                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11233                 expect_payment_failed!(nodes[0], payment_hash, true);
11234
11235                 // Finally, succeed the keysend payment.
11236                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11237
11238                 // To start (3), send a keysend payment but don't claim it.
11239                 let payment_id_1 = PaymentId([44; 32]);
11240                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11241                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
11242                 check_added_monitors!(nodes[0], 1);
11243                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11244                 assert_eq!(events.len(), 1);
11245                 let event = events.pop().unwrap();
11246                 let path = vec![&nodes[1]];
11247                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11248
11249                 // Next, attempt a keysend payment and make sure it fails.
11250                 let route_params = RouteParameters::from_payment_params_and_value(
11251                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
11252                         100_000
11253                 );
11254                 let route = find_route(
11255                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11256                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11257                 ).unwrap();
11258                 let payment_id_2 = PaymentId([45; 32]);
11259                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11260                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
11261                 check_added_monitors!(nodes[0], 1);
11262                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11263                 assert_eq!(events.len(), 1);
11264                 let ev = events.drain(..).next().unwrap();
11265                 let payment_event = SendEvent::from_event(ev);
11266                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11267                 check_added_monitors!(nodes[1], 0);
11268                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11269                 expect_pending_htlcs_forwardable!(nodes[1]);
11270                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11271                 check_added_monitors!(nodes[1], 1);
11272                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11273                 assert!(updates.update_add_htlcs.is_empty());
11274                 assert!(updates.update_fulfill_htlcs.is_empty());
11275                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11276                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11277                 assert!(updates.update_fee.is_none());
11278                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11279                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11280                 expect_payment_failed!(nodes[0], payment_hash, true);
11281
11282                 // Finally, claim the original payment.
11283                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11284         }
11285
11286         #[test]
11287         fn test_keysend_hash_mismatch() {
11288                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
11289                 // preimage doesn't match the msg's payment hash.
11290                 let chanmon_cfgs = create_chanmon_cfgs(2);
11291                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11292                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11293                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11294
11295                 let payer_pubkey = nodes[0].node.get_our_node_id();
11296                 let payee_pubkey = nodes[1].node.get_our_node_id();
11297
11298                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11299                 let route_params = RouteParameters::from_payment_params_and_value(
11300                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11301                 let network_graph = nodes[0].network_graph.clone();
11302                 let first_hops = nodes[0].node.list_usable_channels();
11303                 let scorer = test_utils::TestScorer::new();
11304                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11305                 let route = find_route(
11306                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11307                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11308                 ).unwrap();
11309
11310                 let test_preimage = PaymentPreimage([42; 32]);
11311                 let mismatch_payment_hash = PaymentHash([43; 32]);
11312                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
11313                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
11314                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
11315                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
11316                 check_added_monitors!(nodes[0], 1);
11317
11318                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11319                 assert_eq!(updates.update_add_htlcs.len(), 1);
11320                 assert!(updates.update_fulfill_htlcs.is_empty());
11321                 assert!(updates.update_fail_htlcs.is_empty());
11322                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11323                 assert!(updates.update_fee.is_none());
11324                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11325
11326                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
11327         }
11328
11329         #[test]
11330         fn test_keysend_msg_with_secret_err() {
11331                 // Test that we error as expected if we receive a keysend payment that includes a payment
11332                 // secret when we don't support MPP keysend.
11333                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
11334                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
11335                 let chanmon_cfgs = create_chanmon_cfgs(2);
11336                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11337                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
11338                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11339
11340                 let payer_pubkey = nodes[0].node.get_our_node_id();
11341                 let payee_pubkey = nodes[1].node.get_our_node_id();
11342
11343                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11344                 let route_params = RouteParameters::from_payment_params_and_value(
11345                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11346                 let network_graph = nodes[0].network_graph.clone();
11347                 let first_hops = nodes[0].node.list_usable_channels();
11348                 let scorer = test_utils::TestScorer::new();
11349                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11350                 let route = find_route(
11351                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11352                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11353                 ).unwrap();
11354
11355                 let test_preimage = PaymentPreimage([42; 32]);
11356                 let test_secret = PaymentSecret([43; 32]);
11357                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
11358                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
11359                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
11360                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
11361                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
11362                         PaymentId(payment_hash.0), None, session_privs).unwrap();
11363                 check_added_monitors!(nodes[0], 1);
11364
11365                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11366                 assert_eq!(updates.update_add_htlcs.len(), 1);
11367                 assert!(updates.update_fulfill_htlcs.is_empty());
11368                 assert!(updates.update_fail_htlcs.is_empty());
11369                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11370                 assert!(updates.update_fee.is_none());
11371                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11372
11373                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11374         }
11375
11376         #[test]
11377         fn test_multi_hop_missing_secret() {
11378                 let chanmon_cfgs = create_chanmon_cfgs(4);
11379                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11380                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11381                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11382
11383                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11384                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11385                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11386                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11387
11388                 // Marshall an MPP route.
11389                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11390                 let path = route.paths[0].clone();
11391                 route.paths.push(path);
11392                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11393                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11394                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11395                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11396                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11397                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11398
11399                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11400                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11401                 .unwrap_err() {
11402                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11403                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11404                         },
11405                         _ => panic!("unexpected error")
11406                 }
11407         }
11408
11409         #[test]
11410         fn test_drop_disconnected_peers_when_removing_channels() {
11411                 let chanmon_cfgs = create_chanmon_cfgs(2);
11412                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11413                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11414                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11415
11416                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11417
11418                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11419                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11420
11421                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11422                 check_closed_broadcast!(nodes[0], true);
11423                 check_added_monitors!(nodes[0], 1);
11424                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11425
11426                 {
11427                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11428                         // disconnected and the channel between has been force closed.
11429                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11430                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11431                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11432                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11433                 }
11434
11435                 nodes[0].node.timer_tick_occurred();
11436
11437                 {
11438                         // Assert that nodes[1] has now been removed.
11439                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11440                 }
11441         }
11442
11443         #[test]
11444         fn bad_inbound_payment_hash() {
11445                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11446                 let chanmon_cfgs = create_chanmon_cfgs(2);
11447                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11448                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11449                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11450
11451                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11452                 let payment_data = msgs::FinalOnionHopData {
11453                         payment_secret,
11454                         total_msat: 100_000,
11455                 };
11456
11457                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11458                 // payment verification fails as expected.
11459                 let mut bad_payment_hash = payment_hash.clone();
11460                 bad_payment_hash.0[0] += 1;
11461                 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) {
11462                         Ok(_) => panic!("Unexpected ok"),
11463                         Err(()) => {
11464                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11465                         }
11466                 }
11467
11468                 // Check that using the original payment hash succeeds.
11469                 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());
11470         }
11471
11472         #[test]
11473         fn test_id_to_peer_coverage() {
11474                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
11475                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11476                 // the channel is successfully closed.
11477                 let chanmon_cfgs = create_chanmon_cfgs(2);
11478                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11479                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11480                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11481
11482                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
11483                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11484                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11485                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11486                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11487
11488                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11489                 let channel_id = ChannelId::from_bytes(tx.txid().into_inner());
11490                 {
11491                         // Ensure that the `id_to_peer` map is empty until either party has received the
11492                         // funding transaction, and have the real `channel_id`.
11493                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11494                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11495                 }
11496
11497                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11498                 {
11499                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
11500                         // as it has the funding transaction.
11501                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11502                         assert_eq!(nodes_0_lock.len(), 1);
11503                         assert!(nodes_0_lock.contains_key(&channel_id));
11504                 }
11505
11506                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11507
11508                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11509
11510                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11511                 {
11512                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11513                         assert_eq!(nodes_0_lock.len(), 1);
11514                         assert!(nodes_0_lock.contains_key(&channel_id));
11515                 }
11516                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11517
11518                 {
11519                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
11520                         // as it has the funding transaction.
11521                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11522                         assert_eq!(nodes_1_lock.len(), 1);
11523                         assert!(nodes_1_lock.contains_key(&channel_id));
11524                 }
11525                 check_added_monitors!(nodes[1], 1);
11526                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11527                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11528                 check_added_monitors!(nodes[0], 1);
11529                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11530                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11531                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11532                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11533
11534                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11535                 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()));
11536                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11537                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11538
11539                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11540                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11541                 {
11542                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
11543                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11544                         // fee for the closing transaction has been negotiated and the parties has the other
11545                         // party's signature for the fee negotiated closing transaction.)
11546                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11547                         assert_eq!(nodes_0_lock.len(), 1);
11548                         assert!(nodes_0_lock.contains_key(&channel_id));
11549                 }
11550
11551                 {
11552                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11553                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11554                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11555                         // kept in the `nodes[1]`'s `id_to_peer` map.
11556                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11557                         assert_eq!(nodes_1_lock.len(), 1);
11558                         assert!(nodes_1_lock.contains_key(&channel_id));
11559                 }
11560
11561                 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()));
11562                 {
11563                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11564                         // therefore has all it needs to fully close the channel (both signatures for the
11565                         // closing transaction).
11566                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
11567                         // fully closed by `nodes[0]`.
11568                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11569
11570                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
11571                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11572                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11573                         assert_eq!(nodes_1_lock.len(), 1);
11574                         assert!(nodes_1_lock.contains_key(&channel_id));
11575                 }
11576
11577                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11578
11579                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11580                 {
11581                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
11582                         // they both have everything required to fully close the channel.
11583                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11584                 }
11585                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11586
11587                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11588                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11589         }
11590
11591         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11592                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11593                 check_api_error_message(expected_message, res_err)
11594         }
11595
11596         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11597                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11598                 check_api_error_message(expected_message, res_err)
11599         }
11600
11601         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11602                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11603                 check_api_error_message(expected_message, res_err)
11604         }
11605
11606         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11607                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11608                 check_api_error_message(expected_message, res_err)
11609         }
11610
11611         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11612                 match res_err {
11613                         Err(APIError::APIMisuseError { err }) => {
11614                                 assert_eq!(err, expected_err_message);
11615                         },
11616                         Err(APIError::ChannelUnavailable { err }) => {
11617                                 assert_eq!(err, expected_err_message);
11618                         },
11619                         Ok(_) => panic!("Unexpected Ok"),
11620                         Err(_) => panic!("Unexpected Error"),
11621                 }
11622         }
11623
11624         #[test]
11625         fn test_api_calls_with_unkown_counterparty_node() {
11626                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11627                 // expected if the `counterparty_node_id` is an unkown peer in the
11628                 // `ChannelManager::per_peer_state` map.
11629                 let chanmon_cfg = create_chanmon_cfgs(2);
11630                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11631                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11632                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11633
11634                 // Dummy values
11635                 let channel_id = ChannelId::from_bytes([4; 32]);
11636                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11637                 let intercept_id = InterceptId([0; 32]);
11638
11639                 // Test the API functions.
11640                 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);
11641
11642                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11643
11644                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11645
11646                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11647
11648                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11649
11650                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11651
11652                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11653         }
11654
11655         #[test]
11656         fn test_api_calls_with_unavailable_channel() {
11657                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11658                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11659                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11660                 // the given `channel_id`.
11661                 let chanmon_cfg = create_chanmon_cfgs(2);
11662                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11663                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11664                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11665
11666                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11667
11668                 // Dummy values
11669                 let channel_id = ChannelId::from_bytes([4; 32]);
11670
11671                 // Test the API functions.
11672                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11673
11674                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11675
11676                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11677
11678                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11679
11680                 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);
11681
11682                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11683         }
11684
11685         #[test]
11686         fn test_connection_limiting() {
11687                 // Test that we limit un-channel'd peers and un-funded channels properly.
11688                 let chanmon_cfgs = create_chanmon_cfgs(2);
11689                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11690                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11691                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11692
11693                 // Note that create_network connects the nodes together for us
11694
11695                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11696                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11697
11698                 let mut funding_tx = None;
11699                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11700                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11701                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11702
11703                         if idx == 0 {
11704                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11705                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11706                                 funding_tx = Some(tx.clone());
11707                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11708                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11709
11710                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11711                                 check_added_monitors!(nodes[1], 1);
11712                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11713
11714                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11715
11716                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11717                                 check_added_monitors!(nodes[0], 1);
11718                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11719                         }
11720                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11721                 }
11722
11723                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11724                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11725                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11726                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11727                         open_channel_msg.temporary_channel_id);
11728
11729                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11730                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11731                 // limit.
11732                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11733                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11734                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11735                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11736                         peer_pks.push(random_pk);
11737                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11738                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11739                         }, true).unwrap();
11740                 }
11741                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11742                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11743                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11744                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11745                 }, true).unwrap_err();
11746
11747                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11748                 // them if we have too many un-channel'd peers.
11749                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11750                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11751                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
11752                 for ev in chan_closed_events {
11753                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
11754                 }
11755                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11756                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11757                 }, true).unwrap();
11758                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11759                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11760                 }, true).unwrap_err();
11761
11762                 // but of course if the connection is outbound its allowed...
11763                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11764                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11765                 }, false).unwrap();
11766                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11767
11768                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
11769                 // Even though we accept one more connection from new peers, we won't actually let them
11770                 // open channels.
11771                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
11772                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11773                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
11774                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
11775                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11776                 }
11777                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11778                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11779                         open_channel_msg.temporary_channel_id);
11780
11781                 // Of course, however, outbound channels are always allowed
11782                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
11783                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
11784
11785                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
11786                 // "protected" and can connect again.
11787                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
11788                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11789                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11790                 }, true).unwrap();
11791                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
11792
11793                 // Further, because the first channel was funded, we can open another channel with
11794                 // last_random_pk.
11795                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11796                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11797         }
11798
11799         #[test]
11800         fn test_outbound_chans_unlimited() {
11801                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
11802                 let chanmon_cfgs = create_chanmon_cfgs(2);
11803                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11804                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11805                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11806
11807                 // Note that create_network connects the nodes together for us
11808
11809                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11810                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11811
11812                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11813                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11814                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11815                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11816                 }
11817
11818                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
11819                 // rejected.
11820                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11821                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11822                         open_channel_msg.temporary_channel_id);
11823
11824                 // but we can still open an outbound channel.
11825                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11826                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
11827
11828                 // but even with such an outbound channel, additional inbound channels will still fail.
11829                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11830                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11831                         open_channel_msg.temporary_channel_id);
11832         }
11833
11834         #[test]
11835         fn test_0conf_limiting() {
11836                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11837                 // flag set and (sometimes) accept channels as 0conf.
11838                 let chanmon_cfgs = create_chanmon_cfgs(2);
11839                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11840                 let mut settings = test_default_channel_config();
11841                 settings.manually_accept_inbound_channels = true;
11842                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
11843                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11844
11845                 // Note that create_network connects the nodes together for us
11846
11847                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11848                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11849
11850                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
11851                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11852                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11853                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11854                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11855                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11856                         }, true).unwrap();
11857
11858                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
11859                         let events = nodes[1].node.get_and_clear_pending_events();
11860                         match events[0] {
11861                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11862                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
11863                                 }
11864                                 _ => panic!("Unexpected event"),
11865                         }
11866                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
11867                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11868                 }
11869
11870                 // If we try to accept a channel from another peer non-0conf it will fail.
11871                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11872                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11873                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11874                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11875                 }, true).unwrap();
11876                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11877                 let events = nodes[1].node.get_and_clear_pending_events();
11878                 match events[0] {
11879                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11880                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
11881                                         Err(APIError::APIMisuseError { err }) =>
11882                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
11883                                         _ => panic!(),
11884                                 }
11885                         }
11886                         _ => panic!("Unexpected event"),
11887                 }
11888                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11889                         open_channel_msg.temporary_channel_id);
11890
11891                 // ...however if we accept the same channel 0conf it should work just fine.
11892                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11893                 let events = nodes[1].node.get_and_clear_pending_events();
11894                 match events[0] {
11895                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11896                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
11897                         }
11898                         _ => panic!("Unexpected event"),
11899                 }
11900                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11901         }
11902
11903         #[test]
11904         fn reject_excessively_underpaying_htlcs() {
11905                 let chanmon_cfg = create_chanmon_cfgs(1);
11906                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11907                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11908                 let node = create_network(1, &node_cfg, &node_chanmgr);
11909                 let sender_intended_amt_msat = 100;
11910                 let extra_fee_msat = 10;
11911                 let hop_data = msgs::InboundOnionPayload::Receive {
11912                         amt_msat: 100,
11913                         outgoing_cltv_value: 42,
11914                         payment_metadata: None,
11915                         keysend_preimage: None,
11916                         payment_data: Some(msgs::FinalOnionHopData {
11917                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11918                         }),
11919                         custom_tlvs: Vec::new(),
11920                 };
11921                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
11922                 // intended amount, we fail the payment.
11923                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11924                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
11925                         create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11926                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
11927                                 current_height, node[0].node.default_configuration.accept_mpp_keysend)
11928                 {
11929                         assert_eq!(err_code, 19);
11930                 } else { panic!(); }
11931
11932                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
11933                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
11934                         amt_msat: 100,
11935                         outgoing_cltv_value: 42,
11936                         payment_metadata: None,
11937                         keysend_preimage: None,
11938                         payment_data: Some(msgs::FinalOnionHopData {
11939                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11940                         }),
11941                         custom_tlvs: Vec::new(),
11942                 };
11943                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11944                 assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11945                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
11946                         current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
11947         }
11948
11949         #[test]
11950         fn test_final_incorrect_cltv(){
11951                 let chanmon_cfg = create_chanmon_cfgs(1);
11952                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11953                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11954                 let node = create_network(1, &node_cfg, &node_chanmgr);
11955
11956                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11957                 let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
11958                         amt_msat: 100,
11959                         outgoing_cltv_value: 22,
11960                         payment_metadata: None,
11961                         keysend_preimage: None,
11962                         payment_data: Some(msgs::FinalOnionHopData {
11963                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
11964                         }),
11965                         custom_tlvs: Vec::new(),
11966                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
11967                         node[0].node.default_configuration.accept_mpp_keysend);
11968
11969                 // Should not return an error as this condition:
11970                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
11971                 // is not satisfied.
11972                 assert!(result.is_ok());
11973         }
11974
11975         #[test]
11976         fn test_inbound_anchors_manual_acceptance() {
11977                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11978                 // flag set and (sometimes) accept channels as 0conf.
11979                 let mut anchors_cfg = test_default_channel_config();
11980                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11981
11982                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
11983                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
11984
11985                 let chanmon_cfgs = create_chanmon_cfgs(3);
11986                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11987                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
11988                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
11989                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11990
11991                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11992                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11993
11994                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11995                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11996                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
11997                 match &msg_events[0] {
11998                         MessageSendEvent::HandleError { node_id, action } => {
11999                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
12000                                 match action {
12001                                         ErrorAction::SendErrorMessage { msg } =>
12002                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
12003                                         _ => panic!("Unexpected error action"),
12004                                 }
12005                         }
12006                         _ => panic!("Unexpected event"),
12007                 }
12008
12009                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12010                 let events = nodes[2].node.get_and_clear_pending_events();
12011                 match events[0] {
12012                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
12013                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
12014                         _ => panic!("Unexpected event"),
12015                 }
12016                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12017         }
12018
12019         #[test]
12020         fn test_anchors_zero_fee_htlc_tx_fallback() {
12021                 // Tests that if both nodes support anchors, but the remote node does not want to accept
12022                 // anchor channels at the moment, an error it sent to the local node such that it can retry
12023                 // the channel without the anchors feature.
12024                 let chanmon_cfgs = create_chanmon_cfgs(2);
12025                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12026                 let mut anchors_config = test_default_channel_config();
12027                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12028                 anchors_config.manually_accept_inbound_channels = true;
12029                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
12030                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12031
12032                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
12033                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12034                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
12035
12036                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12037                 let events = nodes[1].node.get_and_clear_pending_events();
12038                 match events[0] {
12039                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12040                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
12041                         }
12042                         _ => panic!("Unexpected event"),
12043                 }
12044
12045                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
12046                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
12047
12048                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12049                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
12050
12051                 // Since nodes[1] should not have accepted the channel, it should
12052                 // not have generated any events.
12053                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12054         }
12055
12056         #[test]
12057         fn test_update_channel_config() {
12058                 let chanmon_cfg = create_chanmon_cfgs(2);
12059                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12060                 let mut user_config = test_default_channel_config();
12061                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12062                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12063                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
12064                 let channel = &nodes[0].node.list_channels()[0];
12065
12066                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12067                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12068                 assert_eq!(events.len(), 0);
12069
12070                 user_config.channel_config.forwarding_fee_base_msat += 10;
12071                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12072                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
12073                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12074                 assert_eq!(events.len(), 1);
12075                 match &events[0] {
12076                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12077                         _ => panic!("expected BroadcastChannelUpdate event"),
12078                 }
12079
12080                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
12081                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12082                 assert_eq!(events.len(), 0);
12083
12084                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
12085                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12086                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
12087                         ..Default::default()
12088                 }).unwrap();
12089                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12090                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12091                 assert_eq!(events.len(), 1);
12092                 match &events[0] {
12093                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12094                         _ => panic!("expected BroadcastChannelUpdate event"),
12095                 }
12096
12097                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
12098                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12099                         forwarding_fee_proportional_millionths: Some(new_fee),
12100                         ..Default::default()
12101                 }).unwrap();
12102                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12103                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
12104                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12105                 assert_eq!(events.len(), 1);
12106                 match &events[0] {
12107                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12108                         _ => panic!("expected BroadcastChannelUpdate event"),
12109                 }
12110
12111                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
12112                 // should be applied to ensure update atomicity as specified in the API docs.
12113                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
12114                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
12115                 let new_fee = current_fee + 100;
12116                 assert!(
12117                         matches!(
12118                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
12119                                         forwarding_fee_proportional_millionths: Some(new_fee),
12120                                         ..Default::default()
12121                                 }),
12122                                 Err(APIError::ChannelUnavailable { err: _ }),
12123                         )
12124                 );
12125                 // Check that the fee hasn't changed for the channel that exists.
12126                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
12127                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12128                 assert_eq!(events.len(), 0);
12129         }
12130
12131         #[test]
12132         fn test_payment_display() {
12133                 let payment_id = PaymentId([42; 32]);
12134                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12135                 let payment_hash = PaymentHash([42; 32]);
12136                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12137                 let payment_preimage = PaymentPreimage([42; 32]);
12138                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12139         }
12140
12141         #[test]
12142         fn test_trigger_lnd_force_close() {
12143                 let chanmon_cfg = create_chanmon_cfgs(2);
12144                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12145                 let user_config = test_default_channel_config();
12146                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12147                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12148
12149                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
12150                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
12151                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
12152                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12153                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
12154                 check_closed_broadcast(&nodes[0], 1, true);
12155                 check_added_monitors(&nodes[0], 1);
12156                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
12157                 {
12158                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
12159                         assert_eq!(txn.len(), 1);
12160                         check_spends!(txn[0], funding_tx);
12161                 }
12162
12163                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
12164                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
12165                 // their side.
12166                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
12167                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
12168                 }, true).unwrap();
12169                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12170                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12171                 }, false).unwrap();
12172                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
12173                 let channel_reestablish = get_event_msg!(
12174                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
12175                 );
12176                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
12177
12178                 // Alice should respond with an error since the channel isn't known, but a bogus
12179                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
12180                 // close even if it was an lnd node.
12181                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
12182                 assert_eq!(msg_events.len(), 2);
12183                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
12184                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
12185                         assert_eq!(msg.next_local_commitment_number, 0);
12186                         assert_eq!(msg.next_remote_commitment_number, 0);
12187                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
12188                 } else { panic!() };
12189                 check_closed_broadcast(&nodes[1], 1, true);
12190                 check_added_monitors(&nodes[1], 1);
12191                 let expected_close_reason = ClosureReason::ProcessingError {
12192                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
12193                 };
12194                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
12195                 {
12196                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
12197                         assert_eq!(txn.len(), 1);
12198                         check_spends!(txn[0], funding_tx);
12199                 }
12200         }
12201
12202         #[test]
12203         fn test_peel_payment_onion() {
12204                 use super::*;
12205                 let secp_ctx = Secp256k1::new();
12206
12207                 let bob = crate::sign::KeysManager::new(&[2; 32], 42, 42);
12208                 let bob_pk = PublicKey::from_secret_key(&secp_ctx, &bob.get_node_secret_key());
12209                 let charlie = crate::sign::KeysManager::new(&[3; 32], 42, 42);
12210                 let charlie_pk = PublicKey::from_secret_key(&secp_ctx, &charlie.get_node_secret_key());
12211
12212                 let (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
12213                         prng_seed, hops, recipient_amount, pay_secret) = payment_onion_args(bob_pk, charlie_pk);
12214
12215                 let path = Path {
12216                         hops: hops,
12217                         blinded_tail: None,
12218                 };
12219
12220                 let (amount_msat, cltv_expiry, onion) = create_payment_onion(
12221                         &secp_ctx, &path, &session_priv, total_amt_msat, recipient_onion, cur_height,
12222                         payment_hash, Some(preimage), prng_seed
12223                 ).unwrap();
12224
12225                 let msg = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, onion);
12226                 let logger = test_utils::TestLogger::with_id("bob".to_string());
12227
12228                 let peeled = peel_payment_onion(&msg, &&bob, &&logger, &secp_ctx, cur_height, true)
12229                         .map_err(|e| e.msg).unwrap();
12230
12231                 let next_onion = match peeled.routing {
12232                         PendingHTLCRouting::Forward { onion_packet, short_channel_id: _ } => {
12233                                 onion_packet
12234                         },
12235                         _ => panic!("expected a forwarded onion"),
12236                 };
12237
12238                 let msg2 = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, next_onion);
12239                 let peeled2 = peel_payment_onion(&msg2, &&charlie, &&logger, &secp_ctx, cur_height, true)
12240                         .map_err(|e| e.msg).unwrap();
12241
12242                 match peeled2.routing {
12243                         PendingHTLCRouting::ReceiveKeysend { payment_preimage, payment_data, incoming_cltv_expiry, .. } => {
12244                                 assert_eq!(payment_preimage, preimage);
12245                                 assert_eq!(peeled2.outgoing_amt_msat, recipient_amount);
12246                                 assert_eq!(incoming_cltv_expiry, peeled2.outgoing_cltv_value);
12247                                 let msgs::FinalOnionHopData{total_msat, payment_secret} = payment_data.unwrap();
12248                                 assert_eq!(total_msat, total_amt_msat);
12249                                 assert_eq!(payment_secret, pay_secret);
12250                         },
12251                         _ => panic!("expected a received keysend"),
12252                 };
12253         }
12254
12255         fn make_update_add_msg(
12256                 amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash,
12257                 onion_routing_packet: msgs::OnionPacket
12258         ) -> msgs::UpdateAddHTLC {
12259                 msgs::UpdateAddHTLC {
12260                         channel_id: ChannelId::from_bytes([0; 32]),
12261                         htlc_id: 0,
12262                         amount_msat,
12263                         cltv_expiry,
12264                         payment_hash,
12265                         onion_routing_packet,
12266                         skimmed_fee_msat: None,
12267                 }
12268         }
12269
12270         fn payment_onion_args(hop_pk: PublicKey, recipient_pk: PublicKey) -> (
12271                 SecretKey, u64, u32, RecipientOnionFields, PaymentPreimage, PaymentHash, [u8; 32],
12272                 Vec<RouteHop>, u64, PaymentSecret,
12273         ) {
12274                 let session_priv_bytes = [42; 32];
12275                 let session_priv = SecretKey::from_slice(&session_priv_bytes).unwrap();
12276                 let total_amt_msat = 1000;
12277                 let cur_height = 1000;
12278                 let pay_secret = PaymentSecret([99; 32]);
12279                 let recipient_onion = RecipientOnionFields::secret_only(pay_secret);
12280                 let preimage_bytes = [43; 32];
12281                 let preimage = PaymentPreimage(preimage_bytes);
12282                 let rhash_bytes = Sha256::hash(&preimage_bytes).into_inner();
12283                 let payment_hash = PaymentHash(rhash_bytes);
12284                 let prng_seed = [44; 32];
12285
12286                 // make a route alice -> bob -> charlie
12287                 let hop_fee = 1;
12288                 let recipient_amount = total_amt_msat - hop_fee;
12289                 let hops = vec![
12290                         RouteHop {
12291                                 pubkey: hop_pk,
12292                                 fee_msat: hop_fee,
12293                                 cltv_expiry_delta: 42,
12294                                 short_channel_id: 1,
12295                                 node_features: NodeFeatures::empty(),
12296                                 channel_features: ChannelFeatures::empty(),
12297                                 maybe_announced_channel: false,
12298                         },
12299                         RouteHop {
12300                                 pubkey: recipient_pk,
12301                                 fee_msat: recipient_amount,
12302                                 cltv_expiry_delta: 42,
12303                                 short_channel_id: 2,
12304                                 node_features: NodeFeatures::empty(),
12305                                 channel_features: ChannelFeatures::empty(),
12306                                 maybe_announced_channel: false,
12307                         }
12308                 ];
12309
12310                 (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
12311                         prng_seed, hops, recipient_amount, pay_secret)
12312         }
12313
12314         pub fn create_payment_onion<T: bitcoin::secp256k1::Signing>(
12315                 secp_ctx: &Secp256k1<T>, path: &Path, session_priv: &SecretKey, total_msat: u64,
12316                 recipient_onion: RecipientOnionFields, best_block_height: u32, payment_hash: PaymentHash,
12317                 keysend_preimage: Option<PaymentPreimage>, prng_seed: [u8; 32]
12318         ) -> Result<(u64, u32, msgs::OnionPacket), ()> {
12319                 let onion_keys = super::onion_utils::construct_onion_keys(&secp_ctx, &path, &session_priv).map_err(|_| ())?;
12320                 let (onion_payloads, htlc_msat, htlc_cltv) = super::onion_utils::build_onion_payloads(
12321                         &path,
12322                         total_msat,
12323                         recipient_onion,
12324                         best_block_height + 1,
12325                         &keysend_preimage,
12326                 ).map_err(|_| ())?;
12327                 let onion_packet = super::onion_utils::construct_onion_packet(
12328                         onion_payloads, onion_keys, prng_seed, &payment_hash
12329                 )?;
12330                 Ok((htlc_msat, htlc_cltv, onion_packet))
12331         }
12332 }
12333
12334 #[cfg(ldk_bench)]
12335 pub mod bench {
12336         use crate::chain::Listen;
12337         use crate::chain::chainmonitor::{ChainMonitor, Persist};
12338         use crate::sign::{KeysManager, InMemorySigner};
12339         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
12340         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
12341         use crate::ln::functional_test_utils::*;
12342         use crate::ln::msgs::{ChannelMessageHandler, Init};
12343         use crate::routing::gossip::NetworkGraph;
12344         use crate::routing::router::{PaymentParameters, RouteParameters};
12345         use crate::util::test_utils;
12346         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
12347
12348         use bitcoin::hashes::Hash;
12349         use bitcoin::hashes::sha256::Hash as Sha256;
12350         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
12351
12352         use crate::sync::{Arc, Mutex, RwLock};
12353
12354         use criterion::Criterion;
12355
12356         type Manager<'a, P> = ChannelManager<
12357                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
12358                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
12359                         &'a test_utils::TestLogger, &'a P>,
12360                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
12361                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
12362                 &'a test_utils::TestLogger>;
12363
12364         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
12365                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
12366         }
12367         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
12368                 type CM = Manager<'chan_mon_cfg, P>;
12369                 #[inline]
12370                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
12371                 #[inline]
12372                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
12373         }
12374
12375         pub fn bench_sends(bench: &mut Criterion) {
12376                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
12377         }
12378
12379         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
12380                 // Do a simple benchmark of sending a payment back and forth between two nodes.
12381                 // Note that this is unrealistic as each payment send will require at least two fsync
12382                 // calls per node.
12383                 let network = bitcoin::Network::Testnet;
12384                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
12385
12386                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
12387                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
12388                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
12389                 let scorer = RwLock::new(test_utils::TestScorer::new());
12390                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
12391
12392                 let mut config: UserConfig = Default::default();
12393                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
12394                 config.channel_handshake_config.minimum_depth = 1;
12395
12396                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
12397                 let seed_a = [1u8; 32];
12398                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
12399                 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 {
12400                         network,
12401                         best_block: BestBlock::from_network(network),
12402                 }, genesis_block.header.time);
12403                 let node_a_holder = ANodeHolder { node: &node_a };
12404
12405                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
12406                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
12407                 let seed_b = [2u8; 32];
12408                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
12409                 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 {
12410                         network,
12411                         best_block: BestBlock::from_network(network),
12412                 }, genesis_block.header.time);
12413                 let node_b_holder = ANodeHolder { node: &node_b };
12414
12415                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
12416                         features: node_b.init_features(), networks: None, remote_network_address: None
12417                 }, true).unwrap();
12418                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
12419                         features: node_a.init_features(), networks: None, remote_network_address: None
12420                 }, false).unwrap();
12421                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
12422                 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()));
12423                 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()));
12424
12425                 let tx;
12426                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
12427                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12428                                 value: 8_000_000, script_pubkey: output_script,
12429                         }]};
12430                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
12431                 } else { panic!(); }
12432
12433                 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()));
12434                 let events_b = node_b.get_and_clear_pending_events();
12435                 assert_eq!(events_b.len(), 1);
12436                 match events_b[0] {
12437                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12438                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12439                         },
12440                         _ => panic!("Unexpected event"),
12441                 }
12442
12443                 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()));
12444                 let events_a = node_a.get_and_clear_pending_events();
12445                 assert_eq!(events_a.len(), 1);
12446                 match events_a[0] {
12447                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12448                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12449                         },
12450                         _ => panic!("Unexpected event"),
12451                 }
12452
12453                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
12454
12455                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
12456                 Listen::block_connected(&node_a, &block, 1);
12457                 Listen::block_connected(&node_b, &block, 1);
12458
12459                 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()));
12460                 let msg_events = node_a.get_and_clear_pending_msg_events();
12461                 assert_eq!(msg_events.len(), 2);
12462                 match msg_events[0] {
12463                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
12464                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
12465                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
12466                         },
12467                         _ => panic!(),
12468                 }
12469                 match msg_events[1] {
12470                         MessageSendEvent::SendChannelUpdate { .. } => {},
12471                         _ => panic!(),
12472                 }
12473
12474                 let events_a = node_a.get_and_clear_pending_events();
12475                 assert_eq!(events_a.len(), 1);
12476                 match events_a[0] {
12477                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12478                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12479                         },
12480                         _ => panic!("Unexpected event"),
12481                 }
12482
12483                 let events_b = node_b.get_and_clear_pending_events();
12484                 assert_eq!(events_b.len(), 1);
12485                 match events_b[0] {
12486                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12487                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12488                         },
12489                         _ => panic!("Unexpected event"),
12490                 }
12491
12492                 let mut payment_count: u64 = 0;
12493                 macro_rules! send_payment {
12494                         ($node_a: expr, $node_b: expr) => {
12495                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
12496                                         .with_bolt11_features($node_b.bolt11_invoice_features()).unwrap();
12497                                 let mut payment_preimage = PaymentPreimage([0; 32]);
12498                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
12499                                 payment_count += 1;
12500                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
12501                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
12502
12503                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
12504                                         PaymentId(payment_hash.0),
12505                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12506                                         Retry::Attempts(0)).unwrap();
12507                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12508                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12509                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12510                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12511                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12512                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12513                                 $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()));
12514
12515                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12516                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12517                                 $node_b.claim_funds(payment_preimage);
12518                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12519
12520                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12521                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12522                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12523                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12524                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12525                                         },
12526                                         _ => panic!("Failed to generate claim event"),
12527                                 }
12528
12529                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12530                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12531                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12532                                 $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()));
12533
12534                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12535                         }
12536                 }
12537
12538                 bench.bench_function(bench_name, |b| b.iter(|| {
12539                         send_payment!(node_a, node_b);
12540                         send_payment!(node_b, node_a);
12541                 }));
12542         }
12543 }