Flesh out docs on `PendingHTLCRouting`
[rust-lightning] / lightning / src / ln / channelmanager.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The top-level channel management and payment tracking stuff lives here.
11 //!
12 //! The [`ChannelManager`] is the main chunk of logic implementing the lightning protocol and is
13 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
14 //! upon reconnect to the relevant peer(s).
15 //!
16 //! It does not manage routing logic (see [`Router`] for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
19
20 use bitcoin::blockdata::block::Header;
21 use bitcoin::blockdata::transaction::Transaction;
22 use bitcoin::blockdata::constants::ChainHash;
23 use bitcoin::key::constants::SECRET_KEY_SIZE;
24 use bitcoin::network::constants::Network;
25
26 use bitcoin::hashes::Hash;
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::hash_types::{BlockHash, Txid};
29
30 use bitcoin::secp256k1::{SecretKey,PublicKey};
31 use bitcoin::secp256k1::Secp256k1;
32 use bitcoin::{secp256k1, Sequence};
33
34 use crate::blinded_path::BlindedPath;
35 use crate::blinded_path::payment::{PaymentConstraints, ReceiveTlvs};
36 use crate::chain;
37 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
38 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
39 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, WithChannelMonitor, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
40 use crate::chain::transaction::{OutPoint, TransactionData};
41 use crate::events;
42 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
43 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
44 // construct one themselves.
45 use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
46 use crate::ln::channel::{Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext};
47 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
48 #[cfg(any(feature = "_test_utils", test))]
49 use crate::ln::features::Bolt11InvoiceFeatures;
50 use crate::routing::gossip::NetworkGraph;
51 use crate::routing::router::{BlindedTail, DefaultRouter, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
52 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
53 use crate::ln::onion_payment::{check_incoming_htlc_cltv, create_recv_pending_htlc_info, create_fwd_pending_htlc_info, decode_incoming_update_add_htlc_onion, InboundOnionErr, NextPacketDetails};
54 use crate::ln::msgs;
55 use crate::ln::onion_utils;
56 use crate::ln::onion_utils::{HTLCFailReason, INVALID_ONION_BLINDING};
57 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
58 #[cfg(test)]
59 use crate::ln::outbound_payment;
60 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs, StaleExpiration};
61 use crate::ln::wire::Encode;
62 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, InvoiceBuilder};
63 use crate::offers::invoice_error::InvoiceError;
64 use crate::offers::merkle::SignError;
65 use crate::offers::offer::{DerivedMetadata, Offer, OfferBuilder};
66 use crate::offers::parse::Bolt12SemanticError;
67 use crate::offers::refund::{Refund, RefundBuilder};
68 use crate::onion_message::{Destination, OffersMessage, OffersMessageHandler, PendingOnionMessage, new_pending_onion_message};
69 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider};
70 use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
71 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
72 use crate::util::wakers::{Future, Notifier};
73 use crate::util::scid_utils::fake_scid;
74 use crate::util::string::UntrustedString;
75 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
76 use crate::util::logger::{Level, Logger, WithContext};
77 use crate::util::errors::APIError;
78
79 use alloc::collections::{btree_map, BTreeMap};
80
81 use crate::io;
82 use crate::prelude::*;
83 use core::{cmp, mem};
84 use core::cell::RefCell;
85 use crate::io::Read;
86 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
87 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
88 use core::time::Duration;
89 use core::ops::Deref;
90
91 // Re-export this for use in the public API.
92 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
93 use crate::ln::script::ShutdownScript;
94
95 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
96 //
97 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
98 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
99 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
100 //
101 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
102 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
103 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
104 // before we forward it.
105 //
106 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
107 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
108 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
109 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
110 // our payment, which we can use to decode errors or inform the user that the payment was sent.
111
112 /// Information about where a received HTLC('s onion) has indicated the HTLC should go.
113 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
114 pub enum PendingHTLCRouting {
115         /// An HTLC which should be forwarded on to another node.
116         Forward {
117                 /// The onion which should be included in the forwarded HTLC, telling the next hop what to
118                 /// do with the HTLC.
119                 onion_packet: msgs::OnionPacket,
120                 /// The short channel ID of the channel which we were instructed to forward this HTLC to.
121                 ///
122                 /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning
123                 /// to the receiving node, such as one returned from
124                 /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`].
125                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
126                 /// Set if this HTLC is being forwarded within a blinded path.
127                 blinded: Option<BlindedForward>,
128         },
129         /// The onion indicates that this is a payment for an invoice (supposedly) generated by us.
130         ///
131         /// Note that at this point, we have not checked that the invoice being paid was actually
132         /// generated by us, but rather it's claiming to pay an invoice of ours.
133         Receive {
134                 /// Information about the amount the sender intended to pay and (potential) proof that this
135                 /// is a payment for an invoice we generated. This proof of payment is is also used for
136                 /// linking MPP parts of a larger payment.
137                 payment_data: msgs::FinalOnionHopData,
138                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
139                 ///
140                 /// For HTLCs received by LDK, this will ultimately be exposed in
141                 /// [`Event::PaymentClaimable::onion_fields`] as
142                 /// [`RecipientOnionFields::payment_metadata`].
143                 payment_metadata: Option<Vec<u8>>,
144                 /// CLTV expiry of the received HTLC.
145                 ///
146                 /// Used to track when we should expire pending HTLCs that go unclaimed.
147                 incoming_cltv_expiry: u32,
148                 /// If the onion had forwarding instructions to one of our phantom node SCIDs, this will
149                 /// provide the onion shared secret used to decrypt the next level of forwarding
150                 /// instructions.
151                 phantom_shared_secret: Option<[u8; 32]>,
152                 /// Custom TLVs which were set by the sender.
153                 ///
154                 /// For HTLCs received by LDK, this will ultimately be exposed in
155                 /// [`Event::PaymentClaimable::onion_fields`] as
156                 /// [`RecipientOnionFields::custom_tlvs`].
157                 custom_tlvs: Vec<(u64, Vec<u8>)>,
158         },
159         /// The onion indicates that this is for payment to us but which contains the preimage for
160         /// claiming included, and is unrelated to any invoice we'd previously generated (aka a
161         /// "keysend" or "spontaneous" payment).
162         ReceiveKeysend {
163                 /// Information about the amount the sender intended to pay and possibly a token to
164                 /// associate MPP parts of a larger payment.
165                 ///
166                 /// This will only be filled in if receiving MPP keysend payments is enabled, and it being
167                 /// present will cause deserialization to fail on versions of LDK prior to 0.0.116.
168                 payment_data: Option<msgs::FinalOnionHopData>,
169                 /// Preimage for this onion payment. This preimage is provided by the sender and will be
170                 /// used to settle the spontaneous payment.
171                 payment_preimage: PaymentPreimage,
172                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
173                 ///
174                 /// For HTLCs received by LDK, this will ultimately bubble back up as
175                 /// [`RecipientOnionFields::payment_metadata`].
176                 payment_metadata: Option<Vec<u8>>,
177                 /// CLTV expiry of the received HTLC.
178                 ///
179                 /// Used to track when we should expire pending HTLCs that go unclaimed.
180                 incoming_cltv_expiry: u32,
181                 /// Custom TLVs which were set by the sender.
182                 ///
183                 /// For HTLCs received by LDK, these will ultimately bubble back up as
184                 /// [`RecipientOnionFields::custom_tlvs`].
185                 custom_tlvs: Vec<(u64, Vec<u8>)>,
186         },
187 }
188
189 /// Information used to forward or fail this HTLC that is being forwarded within a blinded path.
190 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
191 pub struct BlindedForward {
192         /// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound
193         /// onion payload if we're the introduction node. Useful for calculating the next hop's
194         /// [`msgs::UpdateAddHTLC::blinding_point`].
195         pub inbound_blinding_point: PublicKey,
196         // Another field will be added here when we support forwarding as a non-intro node.
197 }
198
199 impl PendingHTLCRouting {
200         // Used to override the onion failure code and data if the HTLC is blinded.
201         fn blinded_failure(&self) -> Option<BlindedFailure> {
202                 // TODO: needs update when we support receiving to multi-hop blinded paths
203                 if let Self::Forward { blinded: Some(_), .. } = self {
204                         Some(BlindedFailure::FromIntroductionNode)
205                 } else {
206                         None
207                 }
208         }
209 }
210
211 /// Full details of an incoming HTLC, including routing info.
212 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
213 pub struct PendingHTLCInfo {
214         /// Further routing details based on whether the HTLC is being forwarded or received.
215         pub routing: PendingHTLCRouting,
216         /// Shared secret from the previous hop.
217         /// Used encrypt failure packets in the event that the HTLC needs to be failed backwards.
218         pub incoming_shared_secret: [u8; 32],
219         /// Hash of the payment preimage, to lock the payment until the receiver releases the preimage.
220         pub payment_hash: PaymentHash,
221         /// Amount offered by this HTLC.
222         pub incoming_amt_msat: Option<u64>, // Added in 0.0.113
223         /// Sender intended amount to forward or receive (actual amount received
224         /// may overshoot this in either case)
225         pub outgoing_amt_msat: u64,
226         /// Outgoing timelock expiration blockheight.
227         pub outgoing_cltv_value: u32,
228         /// The fee being skimmed off the top of this HTLC. If this is a forward, it'll be the fee we are
229         /// skimming. If we're receiving this HTLC, it's the fee that our counterparty skimmed.
230         pub skimmed_fee_msat: Option<u64>,
231 }
232
233 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
234 pub(super) enum HTLCFailureMsg {
235         Relay(msgs::UpdateFailHTLC),
236         Malformed(msgs::UpdateFailMalformedHTLC),
237 }
238
239 /// Stores whether we can't forward an HTLC or relevant forwarding info
240 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
241 pub(super) enum PendingHTLCStatus {
242         Forward(PendingHTLCInfo),
243         Fail(HTLCFailureMsg),
244 }
245
246 pub(super) struct PendingAddHTLCInfo {
247         pub(super) forward_info: PendingHTLCInfo,
248
249         // These fields are produced in `forward_htlcs()` and consumed in
250         // `process_pending_htlc_forwards()` for constructing the
251         // `HTLCSource::PreviousHopData` for failed and forwarded
252         // HTLCs.
253         //
254         // Note that this may be an outbound SCID alias for the associated channel.
255         prev_short_channel_id: u64,
256         prev_htlc_id: u64,
257         prev_funding_outpoint: OutPoint,
258         prev_user_channel_id: u128,
259 }
260
261 pub(super) enum HTLCForwardInfo {
262         AddHTLC(PendingAddHTLCInfo),
263         FailHTLC {
264                 htlc_id: u64,
265                 err_packet: msgs::OnionErrorPacket,
266         },
267 }
268
269 // Used for failing blinded HTLCs backwards correctly.
270 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
271 enum BlindedFailure {
272         FromIntroductionNode,
273         // Another variant will be added here for non-intro nodes.
274 }
275
276 /// Tracks the inbound corresponding to an outbound HTLC
277 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
278 pub(crate) struct HTLCPreviousHopData {
279         // Note that this may be an outbound SCID alias for the associated channel.
280         short_channel_id: u64,
281         user_channel_id: Option<u128>,
282         htlc_id: u64,
283         incoming_packet_shared_secret: [u8; 32],
284         phantom_shared_secret: Option<[u8; 32]>,
285         blinded_failure: Option<BlindedFailure>,
286
287         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
288         // channel with a preimage provided by the forward channel.
289         outpoint: OutPoint,
290 }
291
292 enum OnionPayload {
293         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
294         Invoice {
295                 /// This is only here for backwards-compatibility in serialization, in the future it can be
296                 /// removed, breaking clients running 0.0.106 and earlier.
297                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
298         },
299         /// Contains the payer-provided preimage.
300         Spontaneous(PaymentPreimage),
301 }
302
303 /// HTLCs that are to us and can be failed/claimed by the user
304 struct ClaimableHTLC {
305         prev_hop: HTLCPreviousHopData,
306         cltv_expiry: u32,
307         /// The amount (in msats) of this MPP part
308         value: u64,
309         /// The amount (in msats) that the sender intended to be sent in this MPP
310         /// part (used for validating total MPP amount)
311         sender_intended_value: u64,
312         onion_payload: OnionPayload,
313         timer_ticks: u8,
314         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
315         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
316         total_value_received: Option<u64>,
317         /// The sender intended sum total of all MPP parts specified in the onion
318         total_msat: u64,
319         /// The extra fee our counterparty skimmed off the top of this HTLC.
320         counterparty_skimmed_fee_msat: Option<u64>,
321 }
322
323 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
324         fn from(val: &ClaimableHTLC) -> Self {
325                 events::ClaimedHTLC {
326                         channel_id: val.prev_hop.outpoint.to_channel_id(),
327                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
328                         cltv_expiry: val.cltv_expiry,
329                         value_msat: val.value,
330                         counterparty_skimmed_fee_msat: val.counterparty_skimmed_fee_msat.unwrap_or(0),
331                 }
332         }
333 }
334
335 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
336 /// a payment and ensure idempotency in LDK.
337 ///
338 /// This is not exported to bindings users as we just use [u8; 32] directly
339 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
340 pub struct PaymentId(pub [u8; Self::LENGTH]);
341
342 impl PaymentId {
343         /// Number of bytes in the id.
344         pub const LENGTH: usize = 32;
345 }
346
347 impl Writeable for PaymentId {
348         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
349                 self.0.write(w)
350         }
351 }
352
353 impl Readable for PaymentId {
354         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
355                 let buf: [u8; 32] = Readable::read(r)?;
356                 Ok(PaymentId(buf))
357         }
358 }
359
360 impl core::fmt::Display for PaymentId {
361         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
362                 crate::util::logger::DebugBytes(&self.0).fmt(f)
363         }
364 }
365
366 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
367 ///
368 /// This is not exported to bindings users as we just use [u8; 32] directly
369 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
370 pub struct InterceptId(pub [u8; 32]);
371
372 impl Writeable for InterceptId {
373         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
374                 self.0.write(w)
375         }
376 }
377
378 impl Readable for InterceptId {
379         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
380                 let buf: [u8; 32] = Readable::read(r)?;
381                 Ok(InterceptId(buf))
382         }
383 }
384
385 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
386 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
387 pub(crate) enum SentHTLCId {
388         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
389         OutboundRoute { session_priv: [u8; SECRET_KEY_SIZE] },
390 }
391 impl SentHTLCId {
392         pub(crate) fn from_source(source: &HTLCSource) -> Self {
393                 match source {
394                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
395                                 short_channel_id: hop_data.short_channel_id,
396                                 htlc_id: hop_data.htlc_id,
397                         },
398                         HTLCSource::OutboundRoute { session_priv, .. } =>
399                                 Self::OutboundRoute { session_priv: session_priv.secret_bytes() },
400                 }
401         }
402 }
403 impl_writeable_tlv_based_enum!(SentHTLCId,
404         (0, PreviousHopData) => {
405                 (0, short_channel_id, required),
406                 (2, htlc_id, required),
407         },
408         (2, OutboundRoute) => {
409                 (0, session_priv, required),
410         };
411 );
412
413
414 /// Tracks the inbound corresponding to an outbound HTLC
415 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
416 #[derive(Clone, Debug, PartialEq, Eq)]
417 pub(crate) enum HTLCSource {
418         PreviousHopData(HTLCPreviousHopData),
419         OutboundRoute {
420                 path: Path,
421                 session_priv: SecretKey,
422                 /// Technically we can recalculate this from the route, but we cache it here to avoid
423                 /// doing a double-pass on route when we get a failure back
424                 first_hop_htlc_msat: u64,
425                 payment_id: PaymentId,
426         },
427 }
428 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
429 impl core::hash::Hash for HTLCSource {
430         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
431                 match self {
432                         HTLCSource::PreviousHopData(prev_hop_data) => {
433                                 0u8.hash(hasher);
434                                 prev_hop_data.hash(hasher);
435                         },
436                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
437                                 1u8.hash(hasher);
438                                 path.hash(hasher);
439                                 session_priv[..].hash(hasher);
440                                 payment_id.hash(hasher);
441                                 first_hop_htlc_msat.hash(hasher);
442                         },
443                 }
444         }
445 }
446 impl HTLCSource {
447         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
448         #[cfg(test)]
449         pub fn dummy() -> Self {
450                 HTLCSource::OutboundRoute {
451                         path: Path { hops: Vec::new(), blinded_tail: None },
452                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
453                         first_hop_htlc_msat: 0,
454                         payment_id: PaymentId([2; 32]),
455                 }
456         }
457
458         #[cfg(debug_assertions)]
459         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
460         /// transaction. Useful to ensure different datastructures match up.
461         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
462                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
463                         *first_hop_htlc_msat == htlc.amount_msat
464                 } else {
465                         // There's nothing we can check for forwarded HTLCs
466                         true
467                 }
468         }
469 }
470
471 /// This enum is used to specify which error data to send to peers when failing back an HTLC
472 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
473 ///
474 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
475 #[derive(Clone, Copy)]
476 pub enum FailureCode {
477         /// We had a temporary error processing the payment. Useful if no other error codes fit
478         /// and you want to indicate that the payer may want to retry.
479         TemporaryNodeFailure,
480         /// We have a required feature which was not in this onion. For example, you may require
481         /// some additional metadata that was not provided with this payment.
482         RequiredNodeFeatureMissing,
483         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
484         /// the HTLC is too close to the current block height for safe handling.
485         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
486         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
487         IncorrectOrUnknownPaymentDetails,
488         /// We failed to process the payload after the onion was decrypted. You may wish to
489         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
490         ///
491         /// If available, the tuple data may include the type number and byte offset in the
492         /// decrypted byte stream where the failure occurred.
493         InvalidOnionPayload(Option<(u64, u16)>),
494 }
495
496 impl Into<u16> for FailureCode {
497     fn into(self) -> u16 {
498                 match self {
499                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
500                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
501                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
502                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
503                 }
504         }
505 }
506
507 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
508 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
509 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
510 /// peer_state lock. We then return the set of things that need to be done outside the lock in
511 /// this struct and call handle_error!() on it.
512
513 struct MsgHandleErrInternal {
514         err: msgs::LightningError,
515         chan_id: Option<(ChannelId, u128)>, // If Some a channel of ours has been closed
516         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
517         channel_capacity: Option<u64>,
518 }
519 impl MsgHandleErrInternal {
520         #[inline]
521         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
522                 Self {
523                         err: LightningError {
524                                 err: err.clone(),
525                                 action: msgs::ErrorAction::SendErrorMessage {
526                                         msg: msgs::ErrorMessage {
527                                                 channel_id,
528                                                 data: err
529                                         },
530                                 },
531                         },
532                         chan_id: None,
533                         shutdown_finish: None,
534                         channel_capacity: None,
535                 }
536         }
537         #[inline]
538         fn from_no_close(err: msgs::LightningError) -> Self {
539                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
540         }
541         #[inline]
542         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 {
543                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
544                 let action = if shutdown_res.monitor_update.is_some() {
545                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
546                         // should disconnect our peer such that we force them to broadcast their latest
547                         // commitment upon reconnecting.
548                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
549                 } else {
550                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
551                 };
552                 Self {
553                         err: LightningError { err, action },
554                         chan_id: Some((channel_id, user_channel_id)),
555                         shutdown_finish: Some((shutdown_res, channel_update)),
556                         channel_capacity: Some(channel_capacity)
557                 }
558         }
559         #[inline]
560         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
561                 Self {
562                         err: match err {
563                                 ChannelError::Warn(msg) =>  LightningError {
564                                         err: msg.clone(),
565                                         action: msgs::ErrorAction::SendWarningMessage {
566                                                 msg: msgs::WarningMessage {
567                                                         channel_id,
568                                                         data: msg
569                                                 },
570                                                 log_level: Level::Warn,
571                                         },
572                                 },
573                                 ChannelError::Ignore(msg) => LightningError {
574                                         err: msg,
575                                         action: msgs::ErrorAction::IgnoreError,
576                                 },
577                                 ChannelError::Close(msg) => LightningError {
578                                         err: msg.clone(),
579                                         action: msgs::ErrorAction::SendErrorMessage {
580                                                 msg: msgs::ErrorMessage {
581                                                         channel_id,
582                                                         data: msg
583                                                 },
584                                         },
585                                 },
586                         },
587                         chan_id: None,
588                         shutdown_finish: None,
589                         channel_capacity: None,
590                 }
591         }
592
593         fn closes_channel(&self) -> bool {
594                 self.chan_id.is_some()
595         }
596 }
597
598 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
599 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
600 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
601 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
602 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
603
604 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
605 /// be sent in the order they appear in the return value, however sometimes the order needs to be
606 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
607 /// they were originally sent). In those cases, this enum is also returned.
608 #[derive(Clone, PartialEq)]
609 pub(super) enum RAACommitmentOrder {
610         /// Send the CommitmentUpdate messages first
611         CommitmentFirst,
612         /// Send the RevokeAndACK message first
613         RevokeAndACKFirst,
614 }
615
616 /// Information about a payment which is currently being claimed.
617 struct ClaimingPayment {
618         amount_msat: u64,
619         payment_purpose: events::PaymentPurpose,
620         receiver_node_id: PublicKey,
621         htlcs: Vec<events::ClaimedHTLC>,
622         sender_intended_value: Option<u64>,
623 }
624 impl_writeable_tlv_based!(ClaimingPayment, {
625         (0, amount_msat, required),
626         (2, payment_purpose, required),
627         (4, receiver_node_id, required),
628         (5, htlcs, optional_vec),
629         (7, sender_intended_value, option),
630 });
631
632 struct ClaimablePayment {
633         purpose: events::PaymentPurpose,
634         onion_fields: Option<RecipientOnionFields>,
635         htlcs: Vec<ClaimableHTLC>,
636 }
637
638 /// Information about claimable or being-claimed payments
639 struct ClaimablePayments {
640         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
641         /// failed/claimed by the user.
642         ///
643         /// Note that, no consistency guarantees are made about the channels given here actually
644         /// existing anymore by the time you go to read them!
645         ///
646         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
647         /// we don't get a duplicate payment.
648         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
649
650         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
651         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
652         /// as an [`events::Event::PaymentClaimed`].
653         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
654 }
655
656 /// Events which we process internally but cannot be processed immediately at the generation site
657 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
658 /// running normally, and specifically must be processed before any other non-background
659 /// [`ChannelMonitorUpdate`]s are applied.
660 #[derive(Debug)]
661 enum BackgroundEvent {
662         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
663         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
664         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
665         /// channel has been force-closed we do not need the counterparty node_id.
666         ///
667         /// Note that any such events are lost on shutdown, so in general they must be updates which
668         /// are regenerated on startup.
669         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
670         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
671         /// channel to continue normal operation.
672         ///
673         /// In general this should be used rather than
674         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
675         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
676         /// error the other variant is acceptable.
677         ///
678         /// Note that any such events are lost on shutdown, so in general they must be updates which
679         /// are regenerated on startup.
680         MonitorUpdateRegeneratedOnStartup {
681                 counterparty_node_id: PublicKey,
682                 funding_txo: OutPoint,
683                 update: ChannelMonitorUpdate
684         },
685         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
686         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
687         /// on a channel.
688         MonitorUpdatesComplete {
689                 counterparty_node_id: PublicKey,
690                 channel_id: ChannelId,
691         },
692 }
693
694 #[derive(Debug)]
695 pub(crate) enum MonitorUpdateCompletionAction {
696         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
697         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
698         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
699         /// event can be generated.
700         PaymentClaimed { payment_hash: PaymentHash },
701         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
702         /// operation of another channel.
703         ///
704         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
705         /// from completing a monitor update which removes the payment preimage until the inbound edge
706         /// completes a monitor update containing the payment preimage. In that case, after the inbound
707         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
708         /// outbound edge.
709         EmitEventAndFreeOtherChannel {
710                 event: events::Event,
711                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
712         },
713         /// Indicates we should immediately resume the operation of another channel, unless there is
714         /// some other reason why the channel is blocked. In practice this simply means immediately
715         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
716         ///
717         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
718         /// from completing a monitor update which removes the payment preimage until the inbound edge
719         /// completes a monitor update containing the payment preimage. However, we use this variant
720         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
721         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
722         ///
723         /// This variant should thus never be written to disk, as it is processed inline rather than
724         /// stored for later processing.
725         FreeOtherChannelImmediately {
726                 downstream_counterparty_node_id: PublicKey,
727                 downstream_funding_outpoint: OutPoint,
728                 blocking_action: RAAMonitorUpdateBlockingAction,
729         },
730 }
731
732 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
733         (0, PaymentClaimed) => { (0, payment_hash, required) },
734         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
735         // *immediately*. However, for simplicity we implement read/write here.
736         (1, FreeOtherChannelImmediately) => {
737                 (0, downstream_counterparty_node_id, required),
738                 (2, downstream_funding_outpoint, required),
739                 (4, blocking_action, required),
740         },
741         (2, EmitEventAndFreeOtherChannel) => {
742                 (0, event, upgradable_required),
743                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
744                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
745                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
746                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
747                 // downgrades to prior versions.
748                 (1, downstream_counterparty_and_funding_outpoint, option),
749         },
750 );
751
752 #[derive(Clone, Debug, PartialEq, Eq)]
753 pub(crate) enum EventCompletionAction {
754         ReleaseRAAChannelMonitorUpdate {
755                 counterparty_node_id: PublicKey,
756                 channel_funding_outpoint: OutPoint,
757         },
758 }
759 impl_writeable_tlv_based_enum!(EventCompletionAction,
760         (0, ReleaseRAAChannelMonitorUpdate) => {
761                 (0, channel_funding_outpoint, required),
762                 (2, counterparty_node_id, required),
763         };
764 );
765
766 #[derive(Clone, PartialEq, Eq, Debug)]
767 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
768 /// the blocked action here. See enum variants for more info.
769 pub(crate) enum RAAMonitorUpdateBlockingAction {
770         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
771         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
772         /// durably to disk.
773         ForwardedPaymentInboundClaim {
774                 /// The upstream channel ID (i.e. the inbound edge).
775                 channel_id: ChannelId,
776                 /// The HTLC ID on the inbound edge.
777                 htlc_id: u64,
778         },
779 }
780
781 impl RAAMonitorUpdateBlockingAction {
782         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
783                 Self::ForwardedPaymentInboundClaim {
784                         channel_id: prev_hop.outpoint.to_channel_id(),
785                         htlc_id: prev_hop.htlc_id,
786                 }
787         }
788 }
789
790 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
791         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
792 ;);
793
794
795 /// State we hold per-peer.
796 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
797         /// `channel_id` -> `ChannelPhase`
798         ///
799         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
800         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
801         /// `temporary_channel_id` -> `InboundChannelRequest`.
802         ///
803         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
804         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
805         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
806         /// the channel is rejected, then the entry is simply removed.
807         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
808         /// The latest `InitFeatures` we heard from the peer.
809         latest_features: InitFeatures,
810         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
811         /// for broadcast messages, where ordering isn't as strict).
812         pub(super) pending_msg_events: Vec<MessageSendEvent>,
813         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
814         /// user but which have not yet completed.
815         ///
816         /// Note that the channel may no longer exist. For example if the channel was closed but we
817         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
818         /// for a missing channel.
819         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
820         /// Map from a specific channel to some action(s) that should be taken when all pending
821         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
822         ///
823         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
824         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
825         /// channels with a peer this will just be one allocation and will amount to a linear list of
826         /// channels to walk, avoiding the whole hashing rigmarole.
827         ///
828         /// Note that the channel may no longer exist. For example, if a channel was closed but we
829         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
830         /// for a missing channel. While a malicious peer could construct a second channel with the
831         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
832         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
833         /// duplicates do not occur, so such channels should fail without a monitor update completing.
834         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
835         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
836         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
837         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
838         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
839         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
840         /// The peer is currently connected (i.e. we've seen a
841         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
842         /// [`ChannelMessageHandler::peer_disconnected`].
843         is_connected: bool,
844 }
845
846 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
847         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
848         /// If true is passed for `require_disconnected`, the function will return false if we haven't
849         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
850         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
851                 if require_disconnected && self.is_connected {
852                         return false
853                 }
854                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
855                         && self.monitor_update_blocked_actions.is_empty()
856                         && self.in_flight_monitor_updates.is_empty()
857         }
858
859         // Returns a count of all channels we have with this peer, including unfunded channels.
860         fn total_channel_count(&self) -> usize {
861                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
862         }
863
864         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
865         fn has_channel(&self, channel_id: &ChannelId) -> bool {
866                 self.channel_by_id.contains_key(channel_id) ||
867                         self.inbound_channel_request_by_id.contains_key(channel_id)
868         }
869 }
870
871 /// A not-yet-accepted inbound (from counterparty) channel. Once
872 /// accepted, the parameters will be used to construct a channel.
873 pub(super) struct InboundChannelRequest {
874         /// The original OpenChannel message.
875         pub open_channel_msg: msgs::OpenChannel,
876         /// The number of ticks remaining before the request expires.
877         pub ticks_remaining: i32,
878 }
879
880 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
881 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
882 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
883
884 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
885 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
886 ///
887 /// For users who don't want to bother doing their own payment preimage storage, we also store that
888 /// here.
889 ///
890 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
891 /// and instead encoding it in the payment secret.
892 struct PendingInboundPayment {
893         /// The payment secret that the sender must use for us to accept this payment
894         payment_secret: PaymentSecret,
895         /// Time at which this HTLC expires - blocks with a header time above this value will result in
896         /// this payment being removed.
897         expiry_time: u64,
898         /// Arbitrary identifier the user specifies (or not)
899         user_payment_id: u64,
900         // Other required attributes of the payment, optionally enforced:
901         payment_preimage: Option<PaymentPreimage>,
902         min_value_msat: Option<u64>,
903 }
904
905 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
906 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
907 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
908 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
909 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
910 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
911 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
912 /// of [`KeysManager`] and [`DefaultRouter`].
913 ///
914 /// This is not exported to bindings users as type aliases aren't supported in most languages.
915 #[cfg(not(c_bindings))]
916 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
917         Arc<M>,
918         Arc<T>,
919         Arc<KeysManager>,
920         Arc<KeysManager>,
921         Arc<KeysManager>,
922         Arc<F>,
923         Arc<DefaultRouter<
924                 Arc<NetworkGraph<Arc<L>>>,
925                 Arc<L>,
926                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
927                 ProbabilisticScoringFeeParameters,
928                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
929         >>,
930         Arc<L>
931 >;
932
933 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
934 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
935 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
936 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
937 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
938 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
939 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
940 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
941 /// of [`KeysManager`] and [`DefaultRouter`].
942 ///
943 /// This is not exported to bindings users as type aliases aren't supported in most languages.
944 #[cfg(not(c_bindings))]
945 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
946         ChannelManager<
947                 &'a M,
948                 &'b T,
949                 &'c KeysManager,
950                 &'c KeysManager,
951                 &'c KeysManager,
952                 &'d F,
953                 &'e DefaultRouter<
954                         &'f NetworkGraph<&'g L>,
955                         &'g L,
956                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
957                         ProbabilisticScoringFeeParameters,
958                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
959                 >,
960                 &'g L
961         >;
962
963 /// A trivial trait which describes any [`ChannelManager`].
964 ///
965 /// This is not exported to bindings users as general cover traits aren't useful in other
966 /// languages.
967 pub trait AChannelManager {
968         /// A type implementing [`chain::Watch`].
969         type Watch: chain::Watch<Self::Signer> + ?Sized;
970         /// A type that may be dereferenced to [`Self::Watch`].
971         type M: Deref<Target = Self::Watch>;
972         /// A type implementing [`BroadcasterInterface`].
973         type Broadcaster: BroadcasterInterface + ?Sized;
974         /// A type that may be dereferenced to [`Self::Broadcaster`].
975         type T: Deref<Target = Self::Broadcaster>;
976         /// A type implementing [`EntropySource`].
977         type EntropySource: EntropySource + ?Sized;
978         /// A type that may be dereferenced to [`Self::EntropySource`].
979         type ES: Deref<Target = Self::EntropySource>;
980         /// A type implementing [`NodeSigner`].
981         type NodeSigner: NodeSigner + ?Sized;
982         /// A type that may be dereferenced to [`Self::NodeSigner`].
983         type NS: Deref<Target = Self::NodeSigner>;
984         /// A type implementing [`WriteableEcdsaChannelSigner`].
985         type Signer: WriteableEcdsaChannelSigner + Sized;
986         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
987         type SignerProvider: SignerProvider<EcdsaSigner= Self::Signer> + ?Sized;
988         /// A type that may be dereferenced to [`Self::SignerProvider`].
989         type SP: Deref<Target = Self::SignerProvider>;
990         /// A type implementing [`FeeEstimator`].
991         type FeeEstimator: FeeEstimator + ?Sized;
992         /// A type that may be dereferenced to [`Self::FeeEstimator`].
993         type F: Deref<Target = Self::FeeEstimator>;
994         /// A type implementing [`Router`].
995         type Router: Router + ?Sized;
996         /// A type that may be dereferenced to [`Self::Router`].
997         type R: Deref<Target = Self::Router>;
998         /// A type implementing [`Logger`].
999         type Logger: Logger + ?Sized;
1000         /// A type that may be dereferenced to [`Self::Logger`].
1001         type L: Deref<Target = Self::Logger>;
1002         /// Returns a reference to the actual [`ChannelManager`] object.
1003         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
1004 }
1005
1006 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
1007 for ChannelManager<M, T, ES, NS, SP, F, R, L>
1008 where
1009         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1010         T::Target: BroadcasterInterface,
1011         ES::Target: EntropySource,
1012         NS::Target: NodeSigner,
1013         SP::Target: SignerProvider,
1014         F::Target: FeeEstimator,
1015         R::Target: Router,
1016         L::Target: Logger,
1017 {
1018         type Watch = M::Target;
1019         type M = M;
1020         type Broadcaster = T::Target;
1021         type T = T;
1022         type EntropySource = ES::Target;
1023         type ES = ES;
1024         type NodeSigner = NS::Target;
1025         type NS = NS;
1026         type Signer = <SP::Target as SignerProvider>::EcdsaSigner;
1027         type SignerProvider = SP::Target;
1028         type SP = SP;
1029         type FeeEstimator = F::Target;
1030         type F = F;
1031         type Router = R::Target;
1032         type R = R;
1033         type Logger = L::Target;
1034         type L = L;
1035         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
1036 }
1037
1038 /// Manager which keeps track of a number of channels and sends messages to the appropriate
1039 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
1040 ///
1041 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
1042 /// to individual Channels.
1043 ///
1044 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
1045 /// all peers during write/read (though does not modify this instance, only the instance being
1046 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
1047 /// called [`funding_transaction_generated`] for outbound channels) being closed.
1048 ///
1049 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
1050 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
1051 /// [`ChannelMonitorUpdate`] before returning from
1052 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
1053 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
1054 /// `ChannelManager` operations from occurring during the serialization process). If the
1055 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
1056 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
1057 /// will be lost (modulo on-chain transaction fees).
1058 ///
1059 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
1060 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
1061 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
1062 ///
1063 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
1064 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
1065 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
1066 /// offline for a full minute. In order to track this, you must call
1067 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1068 ///
1069 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1070 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1071 /// not have a channel with being unable to connect to us or open new channels with us if we have
1072 /// many peers with unfunded channels.
1073 ///
1074 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1075 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1076 /// never limited. Please ensure you limit the count of such channels yourself.
1077 ///
1078 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1079 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1080 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1081 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1082 /// you're using lightning-net-tokio.
1083 ///
1084 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1085 /// [`funding_created`]: msgs::FundingCreated
1086 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1087 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1088 /// [`update_channel`]: chain::Watch::update_channel
1089 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1090 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1091 /// [`read`]: ReadableArgs::read
1092 //
1093 // Lock order:
1094 // The tree structure below illustrates the lock order requirements for the different locks of the
1095 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1096 // and should then be taken in the order of the lowest to the highest level in the tree.
1097 // Note that locks on different branches shall not be taken at the same time, as doing so will
1098 // create a new lock order for those specific locks in the order they were taken.
1099 //
1100 // Lock order tree:
1101 //
1102 // `pending_offers_messages`
1103 //
1104 // `total_consistency_lock`
1105 //  |
1106 //  |__`forward_htlcs`
1107 //  |   |
1108 //  |   |__`pending_intercepted_htlcs`
1109 //  |
1110 //  |__`per_peer_state`
1111 //      |
1112 //      |__`pending_inbound_payments`
1113 //          |
1114 //          |__`claimable_payments`
1115 //          |
1116 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1117 //              |
1118 //              |__`peer_state`
1119 //                  |
1120 //                  |__`id_to_peer`
1121 //                  |
1122 //                  |__`short_to_chan_info`
1123 //                  |
1124 //                  |__`outbound_scid_aliases`
1125 //                  |
1126 //                  |__`best_block`
1127 //                  |
1128 //                  |__`pending_events`
1129 //                      |
1130 //                      |__`pending_background_events`
1131 //
1132 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1133 where
1134         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1135         T::Target: BroadcasterInterface,
1136         ES::Target: EntropySource,
1137         NS::Target: NodeSigner,
1138         SP::Target: SignerProvider,
1139         F::Target: FeeEstimator,
1140         R::Target: Router,
1141         L::Target: Logger,
1142 {
1143         default_configuration: UserConfig,
1144         chain_hash: ChainHash,
1145         fee_estimator: LowerBoundedFeeEstimator<F>,
1146         chain_monitor: M,
1147         tx_broadcaster: T,
1148         #[allow(unused)]
1149         router: R,
1150
1151         /// See `ChannelManager` struct-level documentation for lock order requirements.
1152         #[cfg(test)]
1153         pub(super) best_block: RwLock<BestBlock>,
1154         #[cfg(not(test))]
1155         best_block: RwLock<BestBlock>,
1156         secp_ctx: Secp256k1<secp256k1::All>,
1157
1158         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1159         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1160         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1161         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1162         ///
1163         /// See `ChannelManager` struct-level documentation for lock order requirements.
1164         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1165
1166         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1167         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1168         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1169         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1170         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1171         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1172         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1173         /// after reloading from disk while replaying blocks against ChannelMonitors.
1174         ///
1175         /// See `PendingOutboundPayment` documentation for more info.
1176         ///
1177         /// See `ChannelManager` struct-level documentation for lock order requirements.
1178         pending_outbound_payments: OutboundPayments,
1179
1180         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1181         ///
1182         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1183         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1184         /// and via the classic SCID.
1185         ///
1186         /// Note that no consistency guarantees are made about the existence of a channel with the
1187         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1188         ///
1189         /// See `ChannelManager` struct-level documentation for lock order requirements.
1190         #[cfg(test)]
1191         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1192         #[cfg(not(test))]
1193         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1194         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1195         /// until the user tells us what we should do with them.
1196         ///
1197         /// See `ChannelManager` struct-level documentation for lock order requirements.
1198         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1199
1200         /// The sets of payments which are claimable or currently being claimed. See
1201         /// [`ClaimablePayments`]' individual field docs for more info.
1202         ///
1203         /// See `ChannelManager` struct-level documentation for lock order requirements.
1204         claimable_payments: Mutex<ClaimablePayments>,
1205
1206         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1207         /// and some closed channels which reached a usable state prior to being closed. This is used
1208         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1209         /// active channel list on load.
1210         ///
1211         /// See `ChannelManager` struct-level documentation for lock order requirements.
1212         outbound_scid_aliases: Mutex<HashSet<u64>>,
1213
1214         /// `channel_id` -> `counterparty_node_id`.
1215         ///
1216         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1217         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1218         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1219         ///
1220         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1221         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1222         /// the handling of the events.
1223         ///
1224         /// Note that no consistency guarantees are made about the existence of a peer with the
1225         /// `counterparty_node_id` in our other maps.
1226         ///
1227         /// TODO:
1228         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1229         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1230         /// would break backwards compatability.
1231         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1232         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1233         /// required to access the channel with the `counterparty_node_id`.
1234         ///
1235         /// See `ChannelManager` struct-level documentation for lock order requirements.
1236         id_to_peer: Mutex<HashMap<ChannelId, PublicKey>>,
1237
1238         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1239         ///
1240         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1241         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1242         /// confirmation depth.
1243         ///
1244         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1245         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1246         /// channel with the `channel_id` in our other maps.
1247         ///
1248         /// See `ChannelManager` struct-level documentation for lock order requirements.
1249         #[cfg(test)]
1250         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1251         #[cfg(not(test))]
1252         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1253
1254         our_network_pubkey: PublicKey,
1255
1256         inbound_payment_key: inbound_payment::ExpandedKey,
1257
1258         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1259         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1260         /// we encrypt the namespace identifier using these bytes.
1261         ///
1262         /// [fake scids]: crate::util::scid_utils::fake_scid
1263         fake_scid_rand_bytes: [u8; 32],
1264
1265         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1266         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1267         /// keeping additional state.
1268         probing_cookie_secret: [u8; 32],
1269
1270         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1271         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1272         /// very far in the past, and can only ever be up to two hours in the future.
1273         highest_seen_timestamp: AtomicUsize,
1274
1275         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1276         /// basis, as well as the peer's latest features.
1277         ///
1278         /// If we are connected to a peer we always at least have an entry here, even if no channels
1279         /// are currently open with that peer.
1280         ///
1281         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1282         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1283         /// channels.
1284         ///
1285         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1286         ///
1287         /// See `ChannelManager` struct-level documentation for lock order requirements.
1288         #[cfg(not(any(test, feature = "_test_utils")))]
1289         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1290         #[cfg(any(test, feature = "_test_utils"))]
1291         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1292
1293         /// The set of events which we need to give to the user to handle. In some cases an event may
1294         /// require some further action after the user handles it (currently only blocking a monitor
1295         /// update from being handed to the user to ensure the included changes to the channel state
1296         /// are handled by the user before they're persisted durably to disk). In that case, the second
1297         /// element in the tuple is set to `Some` with further details of the action.
1298         ///
1299         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1300         /// could be in the middle of being processed without the direct mutex held.
1301         ///
1302         /// See `ChannelManager` struct-level documentation for lock order requirements.
1303         #[cfg(not(any(test, feature = "_test_utils")))]
1304         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1305         #[cfg(any(test, feature = "_test_utils"))]
1306         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1307
1308         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1309         pending_events_processor: AtomicBool,
1310
1311         /// If we are running during init (either directly during the deserialization method or in
1312         /// block connection methods which run after deserialization but before normal operation) we
1313         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1314         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1315         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1316         ///
1317         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1318         ///
1319         /// See `ChannelManager` struct-level documentation for lock order requirements.
1320         ///
1321         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1322         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1323         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1324         /// Essentially just when we're serializing ourselves out.
1325         /// Taken first everywhere where we are making changes before any other locks.
1326         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1327         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1328         /// Notifier the lock contains sends out a notification when the lock is released.
1329         total_consistency_lock: RwLock<()>,
1330         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1331         /// received and the monitor has been persisted.
1332         ///
1333         /// This information does not need to be persisted as funding nodes can forget
1334         /// unfunded channels upon disconnection.
1335         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1336
1337         background_events_processed_since_startup: AtomicBool,
1338
1339         event_persist_notifier: Notifier,
1340         needs_persist_flag: AtomicBool,
1341
1342         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1343
1344         entropy_source: ES,
1345         node_signer: NS,
1346         signer_provider: SP,
1347
1348         logger: L,
1349 }
1350
1351 /// Chain-related parameters used to construct a new `ChannelManager`.
1352 ///
1353 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1354 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1355 /// are not needed when deserializing a previously constructed `ChannelManager`.
1356 #[derive(Clone, Copy, PartialEq)]
1357 pub struct ChainParameters {
1358         /// The network for determining the `chain_hash` in Lightning messages.
1359         pub network: Network,
1360
1361         /// The hash and height of the latest block successfully connected.
1362         ///
1363         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1364         pub best_block: BestBlock,
1365 }
1366
1367 #[derive(Copy, Clone, PartialEq)]
1368 #[must_use]
1369 enum NotifyOption {
1370         DoPersist,
1371         SkipPersistHandleEvents,
1372         SkipPersistNoEvents,
1373 }
1374
1375 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1376 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1377 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1378 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1379 /// sending the aforementioned notification (since the lock being released indicates that the
1380 /// updates are ready for persistence).
1381 ///
1382 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1383 /// notify or not based on whether relevant changes have been made, providing a closure to
1384 /// `optionally_notify` which returns a `NotifyOption`.
1385 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1386         event_persist_notifier: &'a Notifier,
1387         needs_persist_flag: &'a AtomicBool,
1388         should_persist: F,
1389         // We hold onto this result so the lock doesn't get released immediately.
1390         _read_guard: RwLockReadGuard<'a, ()>,
1391 }
1392
1393 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1394         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1395         /// events to handle.
1396         ///
1397         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1398         /// other cases where losing the changes on restart may result in a force-close or otherwise
1399         /// isn't ideal.
1400         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1401                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1402         }
1403
1404         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1405         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1406                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1407                 let force_notify = cm.get_cm().process_background_events();
1408
1409                 PersistenceNotifierGuard {
1410                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1411                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1412                         should_persist: move || {
1413                                 // Pick the "most" action between `persist_check` and the background events
1414                                 // processing and return that.
1415                                 let notify = persist_check();
1416                                 match (notify, force_notify) {
1417                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1418                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1419                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1420                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1421                                         _ => NotifyOption::SkipPersistNoEvents,
1422                                 }
1423                         },
1424                         _read_guard: read_guard,
1425                 }
1426         }
1427
1428         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1429         /// [`ChannelManager::process_background_events`] MUST be called first (or
1430         /// [`Self::optionally_notify`] used).
1431         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1432         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1433                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1434
1435                 PersistenceNotifierGuard {
1436                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1437                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1438                         should_persist: persist_check,
1439                         _read_guard: read_guard,
1440                 }
1441         }
1442 }
1443
1444 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1445         fn drop(&mut self) {
1446                 match (self.should_persist)() {
1447                         NotifyOption::DoPersist => {
1448                                 self.needs_persist_flag.store(true, Ordering::Release);
1449                                 self.event_persist_notifier.notify()
1450                         },
1451                         NotifyOption::SkipPersistHandleEvents =>
1452                                 self.event_persist_notifier.notify(),
1453                         NotifyOption::SkipPersistNoEvents => {},
1454                 }
1455         }
1456 }
1457
1458 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1459 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1460 ///
1461 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1462 ///
1463 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1464 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1465 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1466 /// the maximum required amount in lnd as of March 2021.
1467 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1468
1469 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1470 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1471 ///
1472 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1473 ///
1474 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1475 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1476 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1477 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1478 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1479 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1480 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1481 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1482 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1483 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1484 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1485 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1486 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1487
1488 /// Minimum CLTV difference between the current block height and received inbound payments.
1489 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1490 /// this value.
1491 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1492 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1493 // a payment was being routed, so we add an extra block to be safe.
1494 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1495
1496 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1497 // ie that if the next-hop peer fails the HTLC within
1498 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1499 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1500 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1501 // LATENCY_GRACE_PERIOD_BLOCKS.
1502 #[deny(const_err)]
1503 #[allow(dead_code)]
1504 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;
1505
1506 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1507 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1508 #[deny(const_err)]
1509 #[allow(dead_code)]
1510 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1511
1512 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1513 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1514
1515 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1516 /// until we mark the channel disabled and gossip the update.
1517 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1518
1519 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1520 /// we mark the channel enabled and gossip the update.
1521 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1522
1523 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1524 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1525 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1526 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1527
1528 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1529 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1530 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1531
1532 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1533 /// many peers we reject new (inbound) connections.
1534 const MAX_NO_CHANNEL_PEERS: usize = 250;
1535
1536 /// Information needed for constructing an invoice route hint for this channel.
1537 #[derive(Clone, Debug, PartialEq)]
1538 pub struct CounterpartyForwardingInfo {
1539         /// Base routing fee in millisatoshis.
1540         pub fee_base_msat: u32,
1541         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1542         pub fee_proportional_millionths: u32,
1543         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1544         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1545         /// `cltv_expiry_delta` for more details.
1546         pub cltv_expiry_delta: u16,
1547 }
1548
1549 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1550 /// to better separate parameters.
1551 #[derive(Clone, Debug, PartialEq)]
1552 pub struct ChannelCounterparty {
1553         /// The node_id of our counterparty
1554         pub node_id: PublicKey,
1555         /// The Features the channel counterparty provided upon last connection.
1556         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1557         /// many routing-relevant features are present in the init context.
1558         pub features: InitFeatures,
1559         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1560         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1561         /// claiming at least this value on chain.
1562         ///
1563         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1564         ///
1565         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1566         pub unspendable_punishment_reserve: u64,
1567         /// Information on the fees and requirements that the counterparty requires when forwarding
1568         /// payments to us through this channel.
1569         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1570         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1571         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1572         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1573         pub outbound_htlc_minimum_msat: Option<u64>,
1574         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1575         pub outbound_htlc_maximum_msat: Option<u64>,
1576 }
1577
1578 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1579 #[derive(Clone, Debug, PartialEq)]
1580 pub struct ChannelDetails {
1581         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1582         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1583         /// Note that this means this value is *not* persistent - it can change once during the
1584         /// lifetime of the channel.
1585         pub channel_id: ChannelId,
1586         /// Parameters which apply to our counterparty. See individual fields for more information.
1587         pub counterparty: ChannelCounterparty,
1588         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1589         /// our counterparty already.
1590         ///
1591         /// Note that, if this has been set, `channel_id` will be equivalent to
1592         /// `funding_txo.unwrap().to_channel_id()`.
1593         pub funding_txo: Option<OutPoint>,
1594         /// The features which this channel operates with. See individual features for more info.
1595         ///
1596         /// `None` until negotiation completes and the channel type is finalized.
1597         pub channel_type: Option<ChannelTypeFeatures>,
1598         /// The position of the funding transaction in the chain. None if the funding transaction has
1599         /// not yet been confirmed and the channel fully opened.
1600         ///
1601         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1602         /// payments instead of this. See [`get_inbound_payment_scid`].
1603         ///
1604         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1605         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1606         ///
1607         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1608         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1609         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1610         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1611         /// [`confirmations_required`]: Self::confirmations_required
1612         pub short_channel_id: Option<u64>,
1613         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1614         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1615         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1616         /// `Some(0)`).
1617         ///
1618         /// This will be `None` as long as the channel is not available for routing outbound payments.
1619         ///
1620         /// [`short_channel_id`]: Self::short_channel_id
1621         /// [`confirmations_required`]: Self::confirmations_required
1622         pub outbound_scid_alias: Option<u64>,
1623         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1624         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1625         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1626         /// when they see a payment to be routed to us.
1627         ///
1628         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1629         /// previous values for inbound payment forwarding.
1630         ///
1631         /// [`short_channel_id`]: Self::short_channel_id
1632         pub inbound_scid_alias: Option<u64>,
1633         /// The value, in satoshis, of this channel as appears in the funding output
1634         pub channel_value_satoshis: u64,
1635         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1636         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1637         /// this value on chain.
1638         ///
1639         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1640         ///
1641         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1642         ///
1643         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1644         pub unspendable_punishment_reserve: Option<u64>,
1645         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1646         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1647         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1648         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1649         /// serialized with LDK versions prior to 0.0.113.
1650         ///
1651         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1652         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1653         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1654         pub user_channel_id: u128,
1655         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1656         /// which is applied to commitment and HTLC transactions.
1657         ///
1658         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1659         pub feerate_sat_per_1000_weight: Option<u32>,
1660         /// Our total balance.  This is the amount we would get if we close the channel.
1661         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1662         /// amount is not likely to be recoverable on close.
1663         ///
1664         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1665         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1666         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1667         /// This does not consider any on-chain fees.
1668         ///
1669         /// See also [`ChannelDetails::outbound_capacity_msat`]
1670         pub balance_msat: u64,
1671         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1672         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1673         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1674         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1675         ///
1676         /// See also [`ChannelDetails::balance_msat`]
1677         ///
1678         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1679         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1680         /// should be able to spend nearly this amount.
1681         pub outbound_capacity_msat: u64,
1682         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1683         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1684         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1685         /// to use a limit as close as possible to the HTLC limit we can currently send.
1686         ///
1687         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1688         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1689         pub next_outbound_htlc_limit_msat: u64,
1690         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1691         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1692         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1693         /// route which is valid.
1694         pub next_outbound_htlc_minimum_msat: u64,
1695         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1696         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1697         /// available for inclusion in new inbound HTLCs).
1698         /// Note that there are some corner cases not fully handled here, so the actual available
1699         /// inbound capacity may be slightly higher than this.
1700         ///
1701         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1702         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1703         /// However, our counterparty should be able to spend nearly this amount.
1704         pub inbound_capacity_msat: u64,
1705         /// The number of required confirmations on the funding transaction before the funding will be
1706         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1707         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1708         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1709         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1710         ///
1711         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1712         ///
1713         /// [`is_outbound`]: ChannelDetails::is_outbound
1714         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1715         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1716         pub confirmations_required: Option<u32>,
1717         /// The current number of confirmations on the funding transaction.
1718         ///
1719         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1720         pub confirmations: Option<u32>,
1721         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1722         /// until we can claim our funds after we force-close the channel. During this time our
1723         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1724         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1725         /// time to claim our non-HTLC-encumbered funds.
1726         ///
1727         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1728         pub force_close_spend_delay: Option<u16>,
1729         /// True if the channel was initiated (and thus funded) by us.
1730         pub is_outbound: bool,
1731         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1732         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1733         /// required confirmation count has been reached (and we were connected to the peer at some
1734         /// point after the funding transaction received enough confirmations). The required
1735         /// confirmation count is provided in [`confirmations_required`].
1736         ///
1737         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1738         pub is_channel_ready: bool,
1739         /// The stage of the channel's shutdown.
1740         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1741         pub channel_shutdown_state: Option<ChannelShutdownState>,
1742         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1743         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1744         ///
1745         /// This is a strict superset of `is_channel_ready`.
1746         pub is_usable: bool,
1747         /// True if this channel is (or will be) publicly-announced.
1748         pub is_public: bool,
1749         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1750         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1751         pub inbound_htlc_minimum_msat: Option<u64>,
1752         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1753         pub inbound_htlc_maximum_msat: Option<u64>,
1754         /// Set of configurable parameters that affect channel operation.
1755         ///
1756         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1757         pub config: Option<ChannelConfig>,
1758 }
1759
1760 impl ChannelDetails {
1761         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1762         /// This should be used for providing invoice hints or in any other context where our
1763         /// counterparty will forward a payment to us.
1764         ///
1765         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1766         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1767         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1768                 self.inbound_scid_alias.or(self.short_channel_id)
1769         }
1770
1771         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1772         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1773         /// we're sending or forwarding a payment outbound over this channel.
1774         ///
1775         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1776         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1777         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1778                 self.short_channel_id.or(self.outbound_scid_alias)
1779         }
1780
1781         fn from_channel_context<SP: Deref, F: Deref>(
1782                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1783                 fee_estimator: &LowerBoundedFeeEstimator<F>
1784         ) -> Self
1785         where
1786                 SP::Target: SignerProvider,
1787                 F::Target: FeeEstimator
1788         {
1789                 let balance = context.get_available_balances(fee_estimator);
1790                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1791                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1792                 ChannelDetails {
1793                         channel_id: context.channel_id(),
1794                         counterparty: ChannelCounterparty {
1795                                 node_id: context.get_counterparty_node_id(),
1796                                 features: latest_features,
1797                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1798                                 forwarding_info: context.counterparty_forwarding_info(),
1799                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1800                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1801                                 // message (as they are always the first message from the counterparty).
1802                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1803                                 // default `0` value set by `Channel::new_outbound`.
1804                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1805                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1806                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1807                         },
1808                         funding_txo: context.get_funding_txo(),
1809                         // Note that accept_channel (or open_channel) is always the first message, so
1810                         // `have_received_message` indicates that type negotiation has completed.
1811                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1812                         short_channel_id: context.get_short_channel_id(),
1813                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1814                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1815                         channel_value_satoshis: context.get_value_satoshis(),
1816                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1817                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1818                         balance_msat: balance.balance_msat,
1819                         inbound_capacity_msat: balance.inbound_capacity_msat,
1820                         outbound_capacity_msat: balance.outbound_capacity_msat,
1821                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1822                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1823                         user_channel_id: context.get_user_id(),
1824                         confirmations_required: context.minimum_depth(),
1825                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1826                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1827                         is_outbound: context.is_outbound(),
1828                         is_channel_ready: context.is_usable(),
1829                         is_usable: context.is_live(),
1830                         is_public: context.should_announce(),
1831                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1832                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1833                         config: Some(context.config()),
1834                         channel_shutdown_state: Some(context.shutdown_state()),
1835                 }
1836         }
1837 }
1838
1839 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1840 /// Further information on the details of the channel shutdown.
1841 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1842 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1843 /// the channel will be removed shortly.
1844 /// Also note, that in normal operation, peers could disconnect at any of these states
1845 /// and require peer re-connection before making progress onto other states
1846 pub enum ChannelShutdownState {
1847         /// Channel has not sent or received a shutdown message.
1848         NotShuttingDown,
1849         /// Local node has sent a shutdown message for this channel.
1850         ShutdownInitiated,
1851         /// Shutdown message exchanges have concluded and the channels are in the midst of
1852         /// resolving all existing open HTLCs before closing can continue.
1853         ResolvingHTLCs,
1854         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1855         NegotiatingClosingFee,
1856         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1857         /// to drop the channel.
1858         ShutdownComplete,
1859 }
1860
1861 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1862 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1863 #[derive(Debug, PartialEq)]
1864 pub enum RecentPaymentDetails {
1865         /// When an invoice was requested and thus a payment has not yet been sent.
1866         AwaitingInvoice {
1867                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1868                 /// a payment and ensure idempotency in LDK.
1869                 payment_id: PaymentId,
1870         },
1871         /// When a payment is still being sent and awaiting successful delivery.
1872         Pending {
1873                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1874                 /// a payment and ensure idempotency in LDK.
1875                 payment_id: PaymentId,
1876                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1877                 /// abandoned.
1878                 payment_hash: PaymentHash,
1879                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1880                 /// not just the amount currently inflight.
1881                 total_msat: u64,
1882         },
1883         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1884         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1885         /// payment is removed from tracking.
1886         Fulfilled {
1887                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1888                 /// a payment and ensure idempotency in LDK.
1889                 payment_id: PaymentId,
1890                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1891                 /// made before LDK version 0.0.104.
1892                 payment_hash: Option<PaymentHash>,
1893         },
1894         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1895         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1896         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1897         Abandoned {
1898                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1899                 /// a payment and ensure idempotency in LDK.
1900                 payment_id: PaymentId,
1901                 /// Hash of the payment that we have given up trying to send.
1902                 payment_hash: PaymentHash,
1903         },
1904 }
1905
1906 /// Route hints used in constructing invoices for [phantom node payents].
1907 ///
1908 /// [phantom node payments]: crate::sign::PhantomKeysManager
1909 #[derive(Clone)]
1910 pub struct PhantomRouteHints {
1911         /// The list of channels to be included in the invoice route hints.
1912         pub channels: Vec<ChannelDetails>,
1913         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1914         /// route hints.
1915         pub phantom_scid: u64,
1916         /// The pubkey of the real backing node that would ultimately receive the payment.
1917         pub real_node_pubkey: PublicKey,
1918 }
1919
1920 macro_rules! handle_error {
1921         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1922                 // In testing, ensure there are no deadlocks where the lock is already held upon
1923                 // entering the macro.
1924                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1925                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1926
1927                 match $internal {
1928                         Ok(msg) => Ok(msg),
1929                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1930                                 let mut msg_events = Vec::with_capacity(2);
1931
1932                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1933                                         $self.finish_close_channel(shutdown_res);
1934                                         if let Some(update) = update_option {
1935                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1936                                                         msg: update
1937                                                 });
1938                                         }
1939                                         if let Some((channel_id, user_channel_id)) = chan_id {
1940                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1941                                                         channel_id, user_channel_id,
1942                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1943                                                         counterparty_node_id: Some($counterparty_node_id),
1944                                                         channel_capacity_sats: channel_capacity,
1945                                                 }, None));
1946                                         }
1947                                 }
1948
1949                                 let logger = WithContext::from(
1950                                         &$self.logger, Some($counterparty_node_id), chan_id.map(|(chan_id, _)| chan_id)
1951                                 );
1952                                 log_error!(logger, "{}", err.err);
1953                                 if let msgs::ErrorAction::IgnoreError = err.action {
1954                                 } else {
1955                                         msg_events.push(events::MessageSendEvent::HandleError {
1956                                                 node_id: $counterparty_node_id,
1957                                                 action: err.action.clone()
1958                                         });
1959                                 }
1960
1961                                 if !msg_events.is_empty() {
1962                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1963                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1964                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1965                                                 peer_state.pending_msg_events.append(&mut msg_events);
1966                                         }
1967                                 }
1968
1969                                 // Return error in case higher-API need one
1970                                 Err(err)
1971                         },
1972                 }
1973         } };
1974 }
1975
1976 macro_rules! update_maps_on_chan_removal {
1977         ($self: expr, $channel_context: expr) => {{
1978                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1979                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1980                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1981                         short_to_chan_info.remove(&short_id);
1982                 } else {
1983                         // If the channel was never confirmed on-chain prior to its closure, remove the
1984                         // outbound SCID alias we used for it from the collision-prevention set. While we
1985                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1986                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1987                         // opening a million channels with us which are closed before we ever reach the funding
1988                         // stage.
1989                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1990                         debug_assert!(alias_removed);
1991                 }
1992                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1993         }}
1994 }
1995
1996 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1997 macro_rules! convert_chan_phase_err {
1998         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
1999                 match $err {
2000                         ChannelError::Warn(msg) => {
2001                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
2002                         },
2003                         ChannelError::Ignore(msg) => {
2004                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
2005                         },
2006                         ChannelError::Close(msg) => {
2007                                 let logger = WithChannelContext::from(&$self.logger, &$channel.context);
2008                                 log_error!(logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
2009                                 update_maps_on_chan_removal!($self, $channel.context);
2010                                 let shutdown_res = $channel.context.force_shutdown(true);
2011                                 let user_id = $channel.context.get_user_id();
2012                                 let channel_capacity_satoshis = $channel.context.get_value_satoshis();
2013
2014                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, user_id,
2015                                         shutdown_res, $channel_update, channel_capacity_satoshis))
2016                         },
2017                 }
2018         };
2019         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
2020                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
2021         };
2022         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
2023                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
2024         };
2025         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
2026                 match $channel_phase {
2027                         ChannelPhase::Funded(channel) => {
2028                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
2029                         },
2030                         ChannelPhase::UnfundedOutboundV1(channel) => {
2031                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2032                         },
2033                         ChannelPhase::UnfundedInboundV1(channel) => {
2034                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2035                         },
2036                 }
2037         };
2038 }
2039
2040 macro_rules! break_chan_phase_entry {
2041         ($self: ident, $res: expr, $entry: expr) => {
2042                 match $res {
2043                         Ok(res) => res,
2044                         Err(e) => {
2045                                 let key = *$entry.key();
2046                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2047                                 if drop {
2048                                         $entry.remove_entry();
2049                                 }
2050                                 break Err(res);
2051                         }
2052                 }
2053         }
2054 }
2055
2056 macro_rules! try_chan_phase_entry {
2057         ($self: ident, $res: expr, $entry: expr) => {
2058                 match $res {
2059                         Ok(res) => res,
2060                         Err(e) => {
2061                                 let key = *$entry.key();
2062                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2063                                 if drop {
2064                                         $entry.remove_entry();
2065                                 }
2066                                 return Err(res);
2067                         }
2068                 }
2069         }
2070 }
2071
2072 macro_rules! remove_channel_phase {
2073         ($self: expr, $entry: expr) => {
2074                 {
2075                         let channel = $entry.remove_entry().1;
2076                         update_maps_on_chan_removal!($self, &channel.context());
2077                         channel
2078                 }
2079         }
2080 }
2081
2082 macro_rules! send_channel_ready {
2083         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2084                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2085                         node_id: $channel.context.get_counterparty_node_id(),
2086                         msg: $channel_ready_msg,
2087                 });
2088                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2089                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2090                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2091                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2092                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2093                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2094                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2095                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2096                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2097                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2098                 }
2099         }}
2100 }
2101
2102 macro_rules! emit_channel_pending_event {
2103         ($locked_events: expr, $channel: expr) => {
2104                 if $channel.context.should_emit_channel_pending_event() {
2105                         $locked_events.push_back((events::Event::ChannelPending {
2106                                 channel_id: $channel.context.channel_id(),
2107                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2108                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2109                                 user_channel_id: $channel.context.get_user_id(),
2110                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2111                         }, None));
2112                         $channel.context.set_channel_pending_event_emitted();
2113                 }
2114         }
2115 }
2116
2117 macro_rules! emit_channel_ready_event {
2118         ($locked_events: expr, $channel: expr) => {
2119                 if $channel.context.should_emit_channel_ready_event() {
2120                         debug_assert!($channel.context.channel_pending_event_emitted());
2121                         $locked_events.push_back((events::Event::ChannelReady {
2122                                 channel_id: $channel.context.channel_id(),
2123                                 user_channel_id: $channel.context.get_user_id(),
2124                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2125                                 channel_type: $channel.context.get_channel_type().clone(),
2126                         }, None));
2127                         $channel.context.set_channel_ready_event_emitted();
2128                 }
2129         }
2130 }
2131
2132 macro_rules! handle_monitor_update_completion {
2133         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2134                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2135                 let mut updates = $chan.monitor_updating_restored(&&logger,
2136                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2137                         $self.best_block.read().unwrap().height());
2138                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2139                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2140                         // We only send a channel_update in the case where we are just now sending a
2141                         // channel_ready and the channel is in a usable state. We may re-send a
2142                         // channel_update later through the announcement_signatures process for public
2143                         // channels, but there's no reason not to just inform our counterparty of our fees
2144                         // now.
2145                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2146                                 Some(events::MessageSendEvent::SendChannelUpdate {
2147                                         node_id: counterparty_node_id,
2148                                         msg,
2149                                 })
2150                         } else { None }
2151                 } else { None };
2152
2153                 let update_actions = $peer_state.monitor_update_blocked_actions
2154                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2155
2156                 let htlc_forwards = $self.handle_channel_resumption(
2157                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2158                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2159                         updates.funding_broadcastable, updates.channel_ready,
2160                         updates.announcement_sigs);
2161                 if let Some(upd) = channel_update {
2162                         $peer_state.pending_msg_events.push(upd);
2163                 }
2164
2165                 let channel_id = $chan.context.channel_id();
2166                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2167                 core::mem::drop($peer_state_lock);
2168                 core::mem::drop($per_peer_state_lock);
2169
2170                 // If the channel belongs to a batch funding transaction, the progress of the batch
2171                 // should be updated as we have received funding_signed and persisted the monitor.
2172                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2173                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2174                         let mut batch_completed = false;
2175                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2176                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2177                                         *chan_id == channel_id &&
2178                                         *pubkey == counterparty_node_id
2179                                 ));
2180                                 if let Some(channel_state) = channel_state {
2181                                         channel_state.2 = true;
2182                                 } else {
2183                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2184                                 }
2185                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2186                         } else {
2187                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2188                         }
2189
2190                         // When all channels in a batched funding transaction have become ready, it is not necessary
2191                         // to track the progress of the batch anymore and the state of the channels can be updated.
2192                         if batch_completed {
2193                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2194                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2195                                 let mut batch_funding_tx = None;
2196                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2197                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2198                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2199                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2200                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2201                                                         chan.set_batch_ready();
2202                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2203                                                         emit_channel_pending_event!(pending_events, chan);
2204                                                 }
2205                                         }
2206                                 }
2207                                 if let Some(tx) = batch_funding_tx {
2208                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2209                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2210                                 }
2211                         }
2212                 }
2213
2214                 $self.handle_monitor_update_completion_actions(update_actions);
2215
2216                 if let Some(forwards) = htlc_forwards {
2217                         $self.forward_htlcs(&mut [forwards][..]);
2218                 }
2219                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2220                 for failure in updates.failed_htlcs.drain(..) {
2221                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2222                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2223                 }
2224         } }
2225 }
2226
2227 macro_rules! handle_new_monitor_update {
2228         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2229                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2230                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2231                 match $update_res {
2232                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2233                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2234                                 log_error!(logger, "{}", err_str);
2235                                 panic!("{}", err_str);
2236                         },
2237                         ChannelMonitorUpdateStatus::InProgress => {
2238                                 log_debug!(logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2239                                         &$chan.context.channel_id());
2240                                 false
2241                         },
2242                         ChannelMonitorUpdateStatus::Completed => {
2243                                 $completed;
2244                                 true
2245                         },
2246                 }
2247         } };
2248         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2249                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2250                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2251         };
2252         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2253                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2254                         .or_insert_with(Vec::new);
2255                 // During startup, we push monitor updates as background events through to here in
2256                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2257                 // filter for uniqueness here.
2258                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2259                         .unwrap_or_else(|| {
2260                                 in_flight_updates.push($update);
2261                                 in_flight_updates.len() - 1
2262                         });
2263                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2264                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2265                         {
2266                                 let _ = in_flight_updates.remove(idx);
2267                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2268                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2269                                 }
2270                         })
2271         } };
2272 }
2273
2274 macro_rules! process_events_body {
2275         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2276                 let mut processed_all_events = false;
2277                 while !processed_all_events {
2278                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2279                                 return;
2280                         }
2281
2282                         let mut result;
2283
2284                         {
2285                                 // We'll acquire our total consistency lock so that we can be sure no other
2286                                 // persists happen while processing monitor events.
2287                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2288
2289                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2290                                 // ensure any startup-generated background events are handled first.
2291                                 result = $self.process_background_events();
2292
2293                                 // TODO: This behavior should be documented. It's unintuitive that we query
2294                                 // ChannelMonitors when clearing other events.
2295                                 if $self.process_pending_monitor_events() {
2296                                         result = NotifyOption::DoPersist;
2297                                 }
2298                         }
2299
2300                         let pending_events = $self.pending_events.lock().unwrap().clone();
2301                         let num_events = pending_events.len();
2302                         if !pending_events.is_empty() {
2303                                 result = NotifyOption::DoPersist;
2304                         }
2305
2306                         let mut post_event_actions = Vec::new();
2307
2308                         for (event, action_opt) in pending_events {
2309                                 $event_to_handle = event;
2310                                 $handle_event;
2311                                 if let Some(action) = action_opt {
2312                                         post_event_actions.push(action);
2313                                 }
2314                         }
2315
2316                         {
2317                                 let mut pending_events = $self.pending_events.lock().unwrap();
2318                                 pending_events.drain(..num_events);
2319                                 processed_all_events = pending_events.is_empty();
2320                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2321                                 // updated here with the `pending_events` lock acquired.
2322                                 $self.pending_events_processor.store(false, Ordering::Release);
2323                         }
2324
2325                         if !post_event_actions.is_empty() {
2326                                 $self.handle_post_event_actions(post_event_actions);
2327                                 // If we had some actions, go around again as we may have more events now
2328                                 processed_all_events = false;
2329                         }
2330
2331                         match result {
2332                                 NotifyOption::DoPersist => {
2333                                         $self.needs_persist_flag.store(true, Ordering::Release);
2334                                         $self.event_persist_notifier.notify();
2335                                 },
2336                                 NotifyOption::SkipPersistHandleEvents =>
2337                                         $self.event_persist_notifier.notify(),
2338                                 NotifyOption::SkipPersistNoEvents => {},
2339                         }
2340                 }
2341         }
2342 }
2343
2344 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>
2345 where
2346         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
2347         T::Target: BroadcasterInterface,
2348         ES::Target: EntropySource,
2349         NS::Target: NodeSigner,
2350         SP::Target: SignerProvider,
2351         F::Target: FeeEstimator,
2352         R::Target: Router,
2353         L::Target: Logger,
2354 {
2355         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2356         ///
2357         /// The current time or latest block header time can be provided as the `current_timestamp`.
2358         ///
2359         /// This is the main "logic hub" for all channel-related actions, and implements
2360         /// [`ChannelMessageHandler`].
2361         ///
2362         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2363         ///
2364         /// Users need to notify the new `ChannelManager` when a new block is connected or
2365         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2366         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2367         /// more details.
2368         ///
2369         /// [`block_connected`]: chain::Listen::block_connected
2370         /// [`block_disconnected`]: chain::Listen::block_disconnected
2371         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2372         pub fn new(
2373                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2374                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2375                 current_timestamp: u32,
2376         ) -> Self {
2377                 let mut secp_ctx = Secp256k1::new();
2378                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2379                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2380                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2381                 ChannelManager {
2382                         default_configuration: config.clone(),
2383                         chain_hash: ChainHash::using_genesis_block(params.network),
2384                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2385                         chain_monitor,
2386                         tx_broadcaster,
2387                         router,
2388
2389                         best_block: RwLock::new(params.best_block),
2390
2391                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2392                         pending_inbound_payments: Mutex::new(HashMap::new()),
2393                         pending_outbound_payments: OutboundPayments::new(),
2394                         forward_htlcs: Mutex::new(HashMap::new()),
2395                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2396                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2397                         id_to_peer: Mutex::new(HashMap::new()),
2398                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2399
2400                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2401                         secp_ctx,
2402
2403                         inbound_payment_key: expanded_inbound_key,
2404                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2405
2406                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2407
2408                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2409
2410                         per_peer_state: FairRwLock::new(HashMap::new()),
2411
2412                         pending_events: Mutex::new(VecDeque::new()),
2413                         pending_events_processor: AtomicBool::new(false),
2414                         pending_background_events: Mutex::new(Vec::new()),
2415                         total_consistency_lock: RwLock::new(()),
2416                         background_events_processed_since_startup: AtomicBool::new(false),
2417                         event_persist_notifier: Notifier::new(),
2418                         needs_persist_flag: AtomicBool::new(false),
2419                         funding_batch_states: Mutex::new(BTreeMap::new()),
2420
2421                         pending_offers_messages: Mutex::new(Vec::new()),
2422
2423                         entropy_source,
2424                         node_signer,
2425                         signer_provider,
2426
2427                         logger,
2428                 }
2429         }
2430
2431         /// Gets the current configuration applied to all new channels.
2432         pub fn get_current_default_configuration(&self) -> &UserConfig {
2433                 &self.default_configuration
2434         }
2435
2436         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2437                 let height = self.best_block.read().unwrap().height();
2438                 let mut outbound_scid_alias = 0;
2439                 let mut i = 0;
2440                 loop {
2441                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2442                                 outbound_scid_alias += 1;
2443                         } else {
2444                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2445                         }
2446                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2447                                 break;
2448                         }
2449                         i += 1;
2450                         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"); }
2451                 }
2452                 outbound_scid_alias
2453         }
2454
2455         /// Creates a new outbound channel to the given remote node and with the given value.
2456         ///
2457         /// `user_channel_id` will be provided back as in
2458         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2459         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2460         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2461         /// is simply copied to events and otherwise ignored.
2462         ///
2463         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2464         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2465         ///
2466         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2467         /// generate a shutdown scriptpubkey or destination script set by
2468         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2469         ///
2470         /// Note that we do not check if you are currently connected to the given peer. If no
2471         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2472         /// the channel eventually being silently forgotten (dropped on reload).
2473         ///
2474         /// If `temporary_channel_id` is specified, it will be used as the temporary channel ID of the
2475         /// channel. Otherwise, a random one will be generated for you.
2476         ///
2477         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2478         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2479         /// [`ChannelDetails::channel_id`] until after
2480         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2481         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2482         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2483         ///
2484         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2485         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2486         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2487         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_channel_id: u128, temporary_channel_id: Option<ChannelId>, override_config: Option<UserConfig>) -> Result<ChannelId, APIError> {
2488                 if channel_value_satoshis < 1000 {
2489                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2490                 }
2491
2492                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2493                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2494                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2495
2496                 let per_peer_state = self.per_peer_state.read().unwrap();
2497
2498                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2499                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2500
2501                 let mut peer_state = peer_state_mutex.lock().unwrap();
2502
2503                 if let Some(temporary_channel_id) = temporary_channel_id {
2504                         if peer_state.channel_by_id.contains_key(&temporary_channel_id) {
2505                                 return Err(APIError::APIMisuseError{ err: format!("Channel with temporary channel ID {} already exists!", temporary_channel_id)});
2506                         }
2507                 }
2508
2509                 let channel = {
2510                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2511                         let their_features = &peer_state.latest_features;
2512                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2513                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2514                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2515                                 self.best_block.read().unwrap().height(), outbound_scid_alias, temporary_channel_id)
2516                         {
2517                                 Ok(res) => res,
2518                                 Err(e) => {
2519                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2520                                         return Err(e);
2521                                 },
2522                         }
2523                 };
2524                 let res = channel.get_open_channel(self.chain_hash);
2525
2526                 let temporary_channel_id = channel.context.channel_id();
2527                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2528                         hash_map::Entry::Occupied(_) => {
2529                                 if cfg!(fuzzing) {
2530                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2531                                 } else {
2532                                         panic!("RNG is bad???");
2533                                 }
2534                         },
2535                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2536                 }
2537
2538                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2539                         node_id: their_network_key,
2540                         msg: res,
2541                 });
2542                 Ok(temporary_channel_id)
2543         }
2544
2545         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2546                 // Allocate our best estimate of the number of channels we have in the `res`
2547                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2548                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2549                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2550                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2551                 // the same channel.
2552                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2553                 {
2554                         let best_block_height = self.best_block.read().unwrap().height();
2555                         let per_peer_state = self.per_peer_state.read().unwrap();
2556                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2557                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2558                                 let peer_state = &mut *peer_state_lock;
2559                                 res.extend(peer_state.channel_by_id.iter()
2560                                         .filter_map(|(chan_id, phase)| match phase {
2561                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2562                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2563                                                 _ => None,
2564                                         })
2565                                         .filter(f)
2566                                         .map(|(_channel_id, channel)| {
2567                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2568                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2569                                         })
2570                                 );
2571                         }
2572                 }
2573                 res
2574         }
2575
2576         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2577         /// more information.
2578         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2579                 // Allocate our best estimate of the number of channels we have in the `res`
2580                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2581                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2582                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2583                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2584                 // the same channel.
2585                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2586                 {
2587                         let best_block_height = self.best_block.read().unwrap().height();
2588                         let per_peer_state = self.per_peer_state.read().unwrap();
2589                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2590                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2591                                 let peer_state = &mut *peer_state_lock;
2592                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2593                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2594                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2595                                         res.push(details);
2596                                 }
2597                         }
2598                 }
2599                 res
2600         }
2601
2602         /// Gets the list of usable channels, in random order. Useful as an argument to
2603         /// [`Router::find_route`] to ensure non-announced channels are used.
2604         ///
2605         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2606         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2607         /// are.
2608         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2609                 // Note we use is_live here instead of usable which leads to somewhat confused
2610                 // internal/external nomenclature, but that's ok cause that's probably what the user
2611                 // really wanted anyway.
2612                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2613         }
2614
2615         /// Gets the list of channels we have with a given counterparty, in random order.
2616         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2617                 let best_block_height = self.best_block.read().unwrap().height();
2618                 let per_peer_state = self.per_peer_state.read().unwrap();
2619
2620                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2621                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2622                         let peer_state = &mut *peer_state_lock;
2623                         let features = &peer_state.latest_features;
2624                         let context_to_details = |context| {
2625                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2626                         };
2627                         return peer_state.channel_by_id
2628                                 .iter()
2629                                 .map(|(_, phase)| phase.context())
2630                                 .map(context_to_details)
2631                                 .collect();
2632                 }
2633                 vec![]
2634         }
2635
2636         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2637         /// successful path, or have unresolved HTLCs.
2638         ///
2639         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2640         /// result of a crash. If such a payment exists, is not listed here, and an
2641         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2642         ///
2643         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2644         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2645                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2646                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2647                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2648                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2649                                 },
2650                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2651                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2652                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2653                                 },
2654                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2655                                         Some(RecentPaymentDetails::Pending {
2656                                                 payment_id: *payment_id,
2657                                                 payment_hash: *payment_hash,
2658                                                 total_msat: *total_msat,
2659                                         })
2660                                 },
2661                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2662                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2663                                 },
2664                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2665                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2666                                 },
2667                                 PendingOutboundPayment::Legacy { .. } => None
2668                         })
2669                         .collect()
2670         }
2671
2672         /// Helper function that issues the channel close events
2673         fn issue_channel_close_events(&self, context: &ChannelContext<SP>, closure_reason: ClosureReason) {
2674                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2675                 match context.unbroadcasted_funding() {
2676                         Some(transaction) => {
2677                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2678                                         channel_id: context.channel_id(), transaction
2679                                 }, None));
2680                         },
2681                         None => {},
2682                 }
2683                 pending_events_lock.push_back((events::Event::ChannelClosed {
2684                         channel_id: context.channel_id(),
2685                         user_channel_id: context.get_user_id(),
2686                         reason: closure_reason,
2687                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2688                         channel_capacity_sats: Some(context.get_value_satoshis()),
2689                 }, None));
2690         }
2691
2692         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> {
2693                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2694
2695                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2696                 let shutdown_result;
2697                 loop {
2698                         let per_peer_state = self.per_peer_state.read().unwrap();
2699
2700                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2701                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2702
2703                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2704                         let peer_state = &mut *peer_state_lock;
2705
2706                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2707                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2708                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2709                                                 let funding_txo_opt = chan.context.get_funding_txo();
2710                                                 let their_features = &peer_state.latest_features;
2711                                                 let (shutdown_msg, mut monitor_update_opt, htlcs, local_shutdown_result) =
2712                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2713                                                 failed_htlcs = htlcs;
2714                                                 shutdown_result = local_shutdown_result;
2715                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
2716
2717                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2718                                                 // here as we don't need the monitor update to complete until we send a
2719                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2720                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2721                                                         node_id: *counterparty_node_id,
2722                                                         msg: shutdown_msg,
2723                                                 });
2724
2725                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2726                                                         "We can't both complete shutdown and generate a monitor update");
2727
2728                                                 // Update the monitor with the shutdown script if necessary.
2729                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2730                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2731                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2732                                                         break;
2733                                                 }
2734
2735                                                 if chan.is_shutdown() {
2736                                                         if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2737                                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2738                                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2739                                                                                 msg: channel_update
2740                                                                         });
2741                                                                 }
2742                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2743                                                         }
2744                                                 }
2745                                                 break;
2746                                         }
2747                                 },
2748                                 hash_map::Entry::Vacant(_) => {
2749                                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2750                                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2751                                         //
2752                                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2753                                         mem::drop(peer_state_lock);
2754                                         mem::drop(per_peer_state);
2755                                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2756                                 },
2757                         }
2758                 }
2759
2760                 for htlc_source in failed_htlcs.drain(..) {
2761                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2762                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2763                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2764                 }
2765
2766                 if let Some(shutdown_result) = shutdown_result {
2767                         self.finish_close_channel(shutdown_result);
2768                 }
2769
2770                 Ok(())
2771         }
2772
2773         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2774         /// will be accepted on the given channel, and after additional timeout/the closing of all
2775         /// pending HTLCs, the channel will be closed on chain.
2776         ///
2777         ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2778         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2779         ///    fee estimate.
2780         ///  * If our counterparty is the channel initiator, we will require a channel closing
2781         ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2782         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2783         ///    counterparty to pay as much fee as they'd like, however.
2784         ///
2785         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2786         ///
2787         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2788         /// generate a shutdown scriptpubkey or destination script set by
2789         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2790         /// channel.
2791         ///
2792         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2793         /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2794         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2795         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2796         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2797                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2798         }
2799
2800         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2801         /// will be accepted on the given channel, and after additional timeout/the closing of all
2802         /// pending HTLCs, the channel will be closed on chain.
2803         ///
2804         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2805         /// the channel being closed or not:
2806         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2807         ///    transaction. The upper-bound is set by
2808         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2809         ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2810         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2811         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2812         ///    will appear on a force-closure transaction, whichever is lower).
2813         ///
2814         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2815         /// Will fail if a shutdown script has already been set for this channel by
2816         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2817         /// also be compatible with our and the counterparty's features.
2818         ///
2819         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2820         ///
2821         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2822         /// generate a shutdown scriptpubkey or destination script set by
2823         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2824         /// channel.
2825         ///
2826         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2827         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2828         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2829         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> {
2830                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2831         }
2832
2833         fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) {
2834                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2835                 #[cfg(debug_assertions)]
2836                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2837                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2838                 }
2839
2840                 let logger = WithContext::from(
2841                         &self.logger, Some(shutdown_res.counterparty_node_id), Some(shutdown_res.channel_id),
2842                 );
2843                 log_debug!(logger, "Finishing closure of channel with {} HTLCs to fail", shutdown_res.dropped_outbound_htlcs.len());
2844                 for htlc_source in shutdown_res.dropped_outbound_htlcs.drain(..) {
2845                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2846                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2847                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2848                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2849                 }
2850                 if let Some((_, funding_txo, monitor_update)) = shutdown_res.monitor_update {
2851                         // There isn't anything we can do if we get an update failure - we're already
2852                         // force-closing. The monitor update on the required in-memory copy should broadcast
2853                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2854                         // ignore the result here.
2855                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2856                 }
2857                 let mut shutdown_results = Vec::new();
2858                 if let Some(txid) = shutdown_res.unbroadcasted_batch_funding_txid {
2859                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2860                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2861                         let per_peer_state = self.per_peer_state.read().unwrap();
2862                         let mut has_uncompleted_channel = None;
2863                         for (channel_id, counterparty_node_id, state) in affected_channels {
2864                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2865                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2866                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2867                                                 update_maps_on_chan_removal!(self, &chan.context());
2868                                                 self.issue_channel_close_events(&chan.context(), ClosureReason::FundingBatchClosure);
2869                                                 shutdown_results.push(chan.context_mut().force_shutdown(false));
2870                                         }
2871                                 }
2872                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2873                         }
2874                         debug_assert!(
2875                                 has_uncompleted_channel.unwrap_or(true),
2876                                 "Closing a batch where all channels have completed initial monitor update",
2877                         );
2878                 }
2879                 for shutdown_result in shutdown_results.drain(..) {
2880                         self.finish_close_channel(shutdown_result);
2881                 }
2882         }
2883
2884         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2885         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2886         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2887         -> Result<PublicKey, APIError> {
2888                 let per_peer_state = self.per_peer_state.read().unwrap();
2889                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2890                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2891                 let (update_opt, counterparty_node_id) = {
2892                         let mut peer_state = peer_state_mutex.lock().unwrap();
2893                         let closure_reason = if let Some(peer_msg) = peer_msg {
2894                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2895                         } else {
2896                                 ClosureReason::HolderForceClosed
2897                         };
2898                         let logger = WithContext::from(&self.logger, Some(*peer_node_id), Some(*channel_id));
2899                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2900                                 log_error!(logger, "Force-closing channel {}", channel_id);
2901                                 self.issue_channel_close_events(&chan_phase_entry.get().context(), closure_reason);
2902                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2903                                 mem::drop(peer_state);
2904                                 mem::drop(per_peer_state);
2905                                 match chan_phase {
2906                                         ChannelPhase::Funded(mut chan) => {
2907                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast));
2908                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2909                                         },
2910                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2911                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false));
2912                                                 // Unfunded channel has no update
2913                                                 (None, chan_phase.context().get_counterparty_node_id())
2914                                         },
2915                                 }
2916                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2917                                 log_error!(logger, "Force-closing channel {}", &channel_id);
2918                                 // N.B. that we don't send any channel close event here: we
2919                                 // don't have a user_channel_id, and we never sent any opening
2920                                 // events anyway.
2921                                 (None, *peer_node_id)
2922                         } else {
2923                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2924                         }
2925                 };
2926                 if let Some(update) = update_opt {
2927                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2928                         // not try to broadcast it via whatever peer we have.
2929                         let per_peer_state = self.per_peer_state.read().unwrap();
2930                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2931                                 .ok_or(per_peer_state.values().next());
2932                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2933                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2934                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2935                                         msg: update
2936                                 });
2937                         }
2938                 }
2939
2940                 Ok(counterparty_node_id)
2941         }
2942
2943         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2944                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2945                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2946                         Ok(counterparty_node_id) => {
2947                                 let per_peer_state = self.per_peer_state.read().unwrap();
2948                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2949                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2950                                         peer_state.pending_msg_events.push(
2951                                                 events::MessageSendEvent::HandleError {
2952                                                         node_id: counterparty_node_id,
2953                                                         action: msgs::ErrorAction::DisconnectPeer {
2954                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2955                                                         },
2956                                                 }
2957                                         );
2958                                 }
2959                                 Ok(())
2960                         },
2961                         Err(e) => Err(e)
2962                 }
2963         }
2964
2965         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2966         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2967         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2968         /// channel.
2969         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2970         -> Result<(), APIError> {
2971                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2972         }
2973
2974         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2975         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2976         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2977         ///
2978         /// You can always get the latest local transaction(s) to broadcast from
2979         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2980         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2981         -> Result<(), APIError> {
2982                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2983         }
2984
2985         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2986         /// for each to the chain and rejecting new HTLCs on each.
2987         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2988                 for chan in self.list_channels() {
2989                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2990                 }
2991         }
2992
2993         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2994         /// local transaction(s).
2995         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2996                 for chan in self.list_channels() {
2997                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2998                 }
2999         }
3000
3001         fn decode_update_add_htlc_onion(
3002                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey,
3003         ) -> Result<
3004                 (onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg
3005         > {
3006                 let (next_hop, shared_secret, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(
3007                         msg, &self.node_signer, &self.logger, &self.secp_ctx
3008                 )?;
3009
3010                 let is_blinded = match next_hop {
3011                         onion_utils::Hop::Forward {
3012                                 next_hop_data: msgs::InboundOnionPayload::BlindedForward { .. }, ..
3013                         } => true,
3014                         _ => false, // TODO: update this when we support receiving to multi-hop blinded paths
3015                 };
3016
3017                 macro_rules! return_err {
3018                         ($msg: expr, $err_code: expr, $data: expr) => {
3019                                 {
3020                                         log_info!(
3021                                                 WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id)),
3022                                                 "Failed to accept/forward incoming HTLC: {}", $msg
3023                                         );
3024                                         let (err_code, err_data) = if is_blinded {
3025                                                 (INVALID_ONION_BLINDING, &[0; 32][..])
3026                                         } else { ($err_code, $data) };
3027                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3028                                                 channel_id: msg.channel_id,
3029                                                 htlc_id: msg.htlc_id,
3030                                                 reason: HTLCFailReason::reason(err_code, err_data.to_vec())
3031                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3032                                         }));
3033                                 }
3034                         }
3035                 }
3036
3037                 let NextPacketDetails {
3038                         next_packet_pubkey, outgoing_amt_msat, outgoing_scid, outgoing_cltv_value
3039                 } = match next_packet_details_opt {
3040                         Some(next_packet_details) => next_packet_details,
3041                         // it is a receive, so no need for outbound checks
3042                         None => return Ok((next_hop, shared_secret, None)),
3043                 };
3044
3045                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3046                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3047                 if let Some((err, mut code, chan_update)) = loop {
3048                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3049                         let forwarding_chan_info_opt = match id_option {
3050                                 None => { // unknown_next_peer
3051                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3052                                         // phantom or an intercept.
3053                                         if (self.default_configuration.accept_intercept_htlcs &&
3054                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3055                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3056                                         {
3057                                                 None
3058                                         } else {
3059                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3060                                         }
3061                                 },
3062                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3063                         };
3064                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3065                                 let per_peer_state = self.per_peer_state.read().unwrap();
3066                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3067                                 if peer_state_mutex_opt.is_none() {
3068                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3069                                 }
3070                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3071                                 let peer_state = &mut *peer_state_lock;
3072                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3073                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3074                                 ).flatten() {
3075                                         None => {
3076                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3077                                                 // have no consistency guarantees.
3078                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3079                                         },
3080                                         Some(chan) => chan
3081                                 };
3082                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3083                                         // Note that the behavior here should be identical to the above block - we
3084                                         // should NOT reveal the existence or non-existence of a private channel if
3085                                         // we don't allow forwards outbound over them.
3086                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3087                                 }
3088                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3089                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3090                                         // "refuse to forward unless the SCID alias was used", so we pretend
3091                                         // we don't have the channel here.
3092                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3093                                 }
3094                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3095
3096                                 // Note that we could technically not return an error yet here and just hope
3097                                 // that the connection is reestablished or monitor updated by the time we get
3098                                 // around to doing the actual forward, but better to fail early if we can and
3099                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3100                                 // on a small/per-node/per-channel scale.
3101                                 if !chan.context.is_live() { // channel_disabled
3102                                         // If the channel_update we're going to return is disabled (i.e. the
3103                                         // peer has been disabled for some time), return `channel_disabled`,
3104                                         // otherwise return `temporary_channel_failure`.
3105                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3106                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3107                                         } else {
3108                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3109                                         }
3110                                 }
3111                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3112                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3113                                 }
3114                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3115                                         break Some((err, code, chan_update_opt));
3116                                 }
3117                                 chan_update_opt
3118                         } else {
3119                                 None
3120                         };
3121
3122                         let cur_height = self.best_block.read().unwrap().height() + 1;
3123
3124                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
3125                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
3126                         ) {
3127                                 if code & 0x1000 != 0 && chan_update_opt.is_none() {
3128                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3129                                         // forwarding over a real channel we can't generate a channel_update
3130                                         // for it. Instead we just return a generic temporary_node_failure.
3131                                         break Some((err_msg, 0x2000 | 2, None))
3132                                 }
3133                                 let chan_update_opt = if code & 0x1000 != 0 { chan_update_opt } else { None };
3134                                 break Some((err_msg, code, chan_update_opt));
3135                         }
3136
3137                         break None;
3138                 }
3139                 {
3140                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3141                         if let Some(chan_update) = chan_update {
3142                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3143                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3144                                 }
3145                                 else if code == 0x1000 | 13 {
3146                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3147                                 }
3148                                 else if code == 0x1000 | 20 {
3149                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3150                                         0u16.write(&mut res).expect("Writes cannot fail");
3151                                 }
3152                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3153                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3154                                 chan_update.write(&mut res).expect("Writes cannot fail");
3155                         } else if code & 0x1000 == 0x1000 {
3156                                 // If we're trying to return an error that requires a `channel_update` but
3157                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3158                                 // generate an update), just use the generic "temporary_node_failure"
3159                                 // instead.
3160                                 code = 0x2000 | 2;
3161                         }
3162                         return_err!(err, code, &res.0[..]);
3163                 }
3164                 Ok((next_hop, shared_secret, Some(next_packet_pubkey)))
3165         }
3166
3167         fn construct_pending_htlc_status<'a>(
3168                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, shared_secret: [u8; 32],
3169                 decoded_hop: onion_utils::Hop, allow_underpay: bool,
3170                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>,
3171         ) -> PendingHTLCStatus {
3172                 macro_rules! return_err {
3173                         ($msg: expr, $err_code: expr, $data: expr) => {
3174                                 {
3175                                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
3176                                         log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3177                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3178                                                 channel_id: msg.channel_id,
3179                                                 htlc_id: msg.htlc_id,
3180                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3181                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3182                                         }));
3183                                 }
3184                         }
3185                 }
3186                 match decoded_hop {
3187                         onion_utils::Hop::Receive(next_hop_data) => {
3188                                 // OUR PAYMENT!
3189                                 let current_height: u32 = self.best_block.read().unwrap().height();
3190                                 match create_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3191                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat,
3192                                         current_height, self.default_configuration.accept_mpp_keysend)
3193                                 {
3194                                         Ok(info) => {
3195                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3196                                                 // message, however that would leak that we are the recipient of this payment, so
3197                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3198                                                 // delay) once they've send us a commitment_signed!
3199                                                 PendingHTLCStatus::Forward(info)
3200                                         },
3201                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3202                                 }
3203                         },
3204                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3205                                 match create_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3206                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3207                                         Ok(info) => PendingHTLCStatus::Forward(info),
3208                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3209                                 }
3210                         }
3211                 }
3212         }
3213
3214         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3215         /// public, and thus should be called whenever the result is going to be passed out in a
3216         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3217         ///
3218         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3219         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3220         /// storage and the `peer_state` lock has been dropped.
3221         ///
3222         /// [`channel_update`]: msgs::ChannelUpdate
3223         /// [`internal_closing_signed`]: Self::internal_closing_signed
3224         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3225                 if !chan.context.should_announce() {
3226                         return Err(LightningError {
3227                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3228                                 action: msgs::ErrorAction::IgnoreError
3229                         });
3230                 }
3231                 if chan.context.get_short_channel_id().is_none() {
3232                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3233                 }
3234                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3235                 log_trace!(logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3236                 self.get_channel_update_for_unicast(chan)
3237         }
3238
3239         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3240         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3241         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3242         /// provided evidence that they know about the existence of the channel.
3243         ///
3244         /// Note that through [`internal_closing_signed`], this function is called without the
3245         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3246         /// removed from the storage and the `peer_state` lock has been dropped.
3247         ///
3248         /// [`channel_update`]: msgs::ChannelUpdate
3249         /// [`internal_closing_signed`]: Self::internal_closing_signed
3250         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3251                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3252                 log_trace!(logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.context.channel_id().0));
3253                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3254                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3255                         Some(id) => id,
3256                 };
3257
3258                 self.get_channel_update_for_onion(short_channel_id, chan)
3259         }
3260
3261         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3262                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3263                 log_trace!(logger, "Generating channel update for channel {}", log_bytes!(chan.context.channel_id().0));
3264                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3265
3266                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3267                         ChannelUpdateStatus::Enabled => true,
3268                         ChannelUpdateStatus::DisabledStaged(_) => true,
3269                         ChannelUpdateStatus::Disabled => false,
3270                         ChannelUpdateStatus::EnabledStaged(_) => false,
3271                 };
3272
3273                 let unsigned = msgs::UnsignedChannelUpdate {
3274                         chain_hash: self.chain_hash,
3275                         short_channel_id,
3276                         timestamp: chan.context.get_update_time_counter(),
3277                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3278                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3279                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3280                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3281                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3282                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3283                         excess_data: Vec::new(),
3284                 };
3285                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3286                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3287                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3288                 // channel.
3289                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3290
3291                 Ok(msgs::ChannelUpdate {
3292                         signature: sig,
3293                         contents: unsigned
3294                 })
3295         }
3296
3297         #[cfg(test)]
3298         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> {
3299                 let _lck = self.total_consistency_lock.read().unwrap();
3300                 self.send_payment_along_path(SendAlongPathArgs {
3301                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3302                         session_priv_bytes
3303                 })
3304         }
3305
3306         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3307                 let SendAlongPathArgs {
3308                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3309                         session_priv_bytes
3310                 } = args;
3311                 // The top-level caller should hold the total_consistency_lock read lock.
3312                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3313                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3314                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3315
3316                 let (onion_packet, htlc_msat, htlc_cltv) = onion_utils::create_payment_onion(
3317                         &self.secp_ctx, &path, &session_priv, total_value, recipient_onion, cur_height,
3318                         payment_hash, keysend_preimage, prng_seed
3319                 ).map_err(|e| {
3320                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3321                         log_error!(logger, "Failed to build an onion for path for payment hash {}", payment_hash);
3322                         e
3323                 })?;
3324
3325                 let err: Result<(), _> = loop {
3326                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3327                                 None => {
3328                                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3329                                         log_error!(logger, "Failed to find first-hop for payment hash {}", payment_hash);
3330                                         return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()})
3331                                 },
3332                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3333                         };
3334
3335                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(id));
3336                         log_trace!(logger,
3337                                 "Attempting to send payment with payment hash {} along path with next hop {}",
3338                                 payment_hash, path.hops.first().unwrap().short_channel_id);
3339
3340                         let per_peer_state = self.per_peer_state.read().unwrap();
3341                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3342                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3343                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3344                         let peer_state = &mut *peer_state_lock;
3345                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3346                                 match chan_phase_entry.get_mut() {
3347                                         ChannelPhase::Funded(chan) => {
3348                                                 if !chan.context.is_live() {
3349                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3350                                                 }
3351                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3352                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3353                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3354                                                         htlc_cltv, HTLCSource::OutboundRoute {
3355                                                                 path: path.clone(),
3356                                                                 session_priv: session_priv.clone(),
3357                                                                 first_hop_htlc_msat: htlc_msat,
3358                                                                 payment_id,
3359                                                         }, onion_packet, None, &self.fee_estimator, &&logger);
3360                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3361                                                         Some(monitor_update) => {
3362                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3363                                                                         false => {
3364                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3365                                                                                 // docs) that we will resend the commitment update once monitor
3366                                                                                 // updating completes. Therefore, we must return an error
3367                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3368                                                                                 // which we do in the send_payment check for
3369                                                                                 // MonitorUpdateInProgress, below.
3370                                                                                 return Err(APIError::MonitorUpdateInProgress);
3371                                                                         },
3372                                                                         true => {},
3373                                                                 }
3374                                                         },
3375                                                         None => {},
3376                                                 }
3377                                         },
3378                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3379                                 };
3380                         } else {
3381                                 // The channel was likely removed after we fetched the id from the
3382                                 // `short_to_chan_info` map, but before we successfully locked the
3383                                 // `channel_by_id` map.
3384                                 // This can occur as no consistency guarantees exists between the two maps.
3385                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3386                         }
3387                         return Ok(());
3388                 };
3389                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3390                         Ok(_) => unreachable!(),
3391                         Err(e) => {
3392                                 Err(APIError::ChannelUnavailable { err: e.err })
3393                         },
3394                 }
3395         }
3396
3397         /// Sends a payment along a given route.
3398         ///
3399         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3400         /// fields for more info.
3401         ///
3402         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3403         /// [`PeerManager::process_events`]).
3404         ///
3405         /// # Avoiding Duplicate Payments
3406         ///
3407         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3408         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3409         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3410         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3411         /// second payment with the same [`PaymentId`].
3412         ///
3413         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3414         /// tracking of payments, including state to indicate once a payment has completed. Because you
3415         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3416         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3417         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3418         ///
3419         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3420         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3421         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3422         /// [`ChannelManager::list_recent_payments`] for more information.
3423         ///
3424         /// # Possible Error States on [`PaymentSendFailure`]
3425         ///
3426         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3427         /// each entry matching the corresponding-index entry in the route paths, see
3428         /// [`PaymentSendFailure`] for more info.
3429         ///
3430         /// In general, a path may raise:
3431         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3432         ///    node public key) is specified.
3433         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3434         ///    closed, doesn't exist, or the peer is currently disconnected.
3435         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3436         ///    relevant updates.
3437         ///
3438         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3439         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3440         /// different route unless you intend to pay twice!
3441         ///
3442         /// [`RouteHop`]: crate::routing::router::RouteHop
3443         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3444         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3445         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3446         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3447         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3448         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3449                 let best_block_height = self.best_block.read().unwrap().height();
3450                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3451                 self.pending_outbound_payments
3452                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3453                                 &self.entropy_source, &self.node_signer, best_block_height,
3454                                 |args| self.send_payment_along_path(args))
3455         }
3456
3457         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3458         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3459         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3460                 let best_block_height = self.best_block.read().unwrap().height();
3461                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3462                 self.pending_outbound_payments
3463                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3464                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3465                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3466                                 &self.pending_events, |args| self.send_payment_along_path(args))
3467         }
3468
3469         #[cfg(test)]
3470         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> {
3471                 let best_block_height = self.best_block.read().unwrap().height();
3472                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3473                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3474                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3475                         best_block_height, |args| self.send_payment_along_path(args))
3476         }
3477
3478         #[cfg(test)]
3479         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> {
3480                 let best_block_height = self.best_block.read().unwrap().height();
3481                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3482         }
3483
3484         #[cfg(test)]
3485         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3486                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3487         }
3488
3489         pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3490                 let best_block_height = self.best_block.read().unwrap().height();
3491                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3492                 self.pending_outbound_payments
3493                         .send_payment_for_bolt12_invoice(
3494                                 invoice, payment_id, &self.router, self.list_usable_channels(),
3495                                 || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3496                                 best_block_height, &self.logger, &self.pending_events,
3497                                 |args| self.send_payment_along_path(args)
3498                         )
3499         }
3500
3501         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3502         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3503         /// retries are exhausted.
3504         ///
3505         /// # Event Generation
3506         ///
3507         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3508         /// as there are no remaining pending HTLCs for this payment.
3509         ///
3510         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3511         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3512         /// determine the ultimate status of a payment.
3513         ///
3514         /// # Requested Invoices
3515         ///
3516         /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
3517         /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
3518         /// and prevent any attempts at paying it once received. The other events may only be generated
3519         /// once the invoice has been received.
3520         ///
3521         /// # Restart Behavior
3522         ///
3523         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3524         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
3525         /// [`Event::InvoiceRequestFailed`].
3526         ///
3527         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3528         pub fn abandon_payment(&self, payment_id: PaymentId) {
3529                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3530                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3531         }
3532
3533         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3534         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3535         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3536         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3537         /// never reach the recipient.
3538         ///
3539         /// See [`send_payment`] documentation for more details on the return value of this function
3540         /// and idempotency guarantees provided by the [`PaymentId`] key.
3541         ///
3542         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3543         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3544         ///
3545         /// [`send_payment`]: Self::send_payment
3546         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3547                 let best_block_height = self.best_block.read().unwrap().height();
3548                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3549                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3550                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3551                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3552         }
3553
3554         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3555         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3556         ///
3557         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3558         /// payments.
3559         ///
3560         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3561         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> {
3562                 let best_block_height = self.best_block.read().unwrap().height();
3563                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3564                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3565                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3566                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3567                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3568         }
3569
3570         /// Send a payment that is probing the given route for liquidity. We calculate the
3571         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3572         /// us to easily discern them from real payments.
3573         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3574                 let best_block_height = self.best_block.read().unwrap().height();
3575                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3576                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3577                         &self.entropy_source, &self.node_signer, best_block_height,
3578                         |args| self.send_payment_along_path(args))
3579         }
3580
3581         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3582         /// payment probe.
3583         #[cfg(test)]
3584         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3585                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3586         }
3587
3588         /// Sends payment probes over all paths of a route that would be used to pay the given
3589         /// amount to the given `node_id`.
3590         ///
3591         /// See [`ChannelManager::send_preflight_probes`] for more information.
3592         pub fn send_spontaneous_preflight_probes(
3593                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3594                 liquidity_limit_multiplier: Option<u64>,
3595         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3596                 let payment_params =
3597                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3598
3599                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3600
3601                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3602         }
3603
3604         /// Sends payment probes over all paths of a route that would be used to pay a route found
3605         /// according to the given [`RouteParameters`].
3606         ///
3607         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3608         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3609         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3610         /// confirmation in a wallet UI.
3611         ///
3612         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3613         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3614         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3615         /// payment. To mitigate this issue, channels with available liquidity less than the required
3616         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3617         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3618         pub fn send_preflight_probes(
3619                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3620         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3621                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3622
3623                 let payer = self.get_our_node_id();
3624                 let usable_channels = self.list_usable_channels();
3625                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3626                 let inflight_htlcs = self.compute_inflight_htlcs();
3627
3628                 let route = self
3629                         .router
3630                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3631                         .map_err(|e| {
3632                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3633                                 ProbeSendFailure::RouteNotFound
3634                         })?;
3635
3636                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3637
3638                 let mut res = Vec::new();
3639
3640                 for mut path in route.paths {
3641                         // If the last hop is probably an unannounced channel we refrain from probing all the
3642                         // way through to the end and instead probe up to the second-to-last channel.
3643                         while let Some(last_path_hop) = path.hops.last() {
3644                                 if last_path_hop.maybe_announced_channel {
3645                                         // We found a potentially announced last hop.
3646                                         break;
3647                                 } else {
3648                                         // Drop the last hop, as it's likely unannounced.
3649                                         log_debug!(
3650                                                 self.logger,
3651                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3652                                                 last_path_hop.short_channel_id
3653                                         );
3654                                         let final_value_msat = path.final_value_msat();
3655                                         path.hops.pop();
3656                                         if let Some(new_last) = path.hops.last_mut() {
3657                                                 new_last.fee_msat += final_value_msat;
3658                                         }
3659                                 }
3660                         }
3661
3662                         if path.hops.len() < 2 {
3663                                 log_debug!(
3664                                         self.logger,
3665                                         "Skipped sending payment probe over path with less than two hops."
3666                                 );
3667                                 continue;
3668                         }
3669
3670                         if let Some(first_path_hop) = path.hops.first() {
3671                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3672                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3673                                 }) {
3674                                         let path_value = path.final_value_msat() + path.fee_msat();
3675                                         let used_liquidity =
3676                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3677
3678                                         if first_hop.next_outbound_htlc_limit_msat
3679                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3680                                         {
3681                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3682                                                 continue;
3683                                         } else {
3684                                                 *used_liquidity += path_value;
3685                                         }
3686                                 }
3687                         }
3688
3689                         res.push(self.send_probe(path).map_err(|e| {
3690                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3691                                 ProbeSendFailure::SendingFailed(e)
3692                         })?);
3693                 }
3694
3695                 Ok(res)
3696         }
3697
3698         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3699         /// which checks the correctness of the funding transaction given the associated channel.
3700         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3701                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3702                 mut find_funding_output: FundingOutput,
3703         ) -> Result<(), APIError> {
3704                 let per_peer_state = self.per_peer_state.read().unwrap();
3705                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3706                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3707
3708                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3709                 let peer_state = &mut *peer_state_lock;
3710                 let (chan, msg_opt) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3711                         Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
3712                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3713
3714                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3715                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &&logger)
3716                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3717                                                 let channel_id = chan.context.channel_id();
3718                                                 let user_id = chan.context.get_user_id();
3719                                                 let shutdown_res = chan.context.force_shutdown(false);
3720                                                 let channel_capacity = chan.context.get_value_satoshis();
3721                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3722                                         } else { unreachable!(); });
3723                                 match funding_res {
3724                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3725                                         Err((chan, err)) => {
3726                                                 mem::drop(peer_state_lock);
3727                                                 mem::drop(per_peer_state);
3728                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3729                                                 return Err(APIError::ChannelUnavailable {
3730                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3731                                                 });
3732                                         },
3733                                 }
3734                         },
3735                         Some(phase) => {
3736                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3737                                 return Err(APIError::APIMisuseError {
3738                                         err: format!(
3739                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3740                                                 temporary_channel_id, counterparty_node_id),
3741                                 })
3742                         },
3743                         None => return Err(APIError::ChannelUnavailable {err: format!(
3744                                 "Channel with id {} not found for the passed counterparty node_id {}",
3745                                 temporary_channel_id, counterparty_node_id),
3746                                 }),
3747                 };
3748
3749                 if let Some(msg) = msg_opt {
3750                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3751                                 node_id: chan.context.get_counterparty_node_id(),
3752                                 msg,
3753                         });
3754                 }
3755                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3756                         hash_map::Entry::Occupied(_) => {
3757                                 panic!("Generated duplicate funding txid?");
3758                         },
3759                         hash_map::Entry::Vacant(e) => {
3760                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3761                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3762                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3763                                 }
3764                                 e.insert(ChannelPhase::Funded(chan));
3765                         }
3766                 }
3767                 Ok(())
3768         }
3769
3770         #[cfg(test)]
3771         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3772                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3773                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3774                 })
3775         }
3776
3777         /// Call this upon creation of a funding transaction for the given channel.
3778         ///
3779         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3780         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3781         ///
3782         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3783         /// across the p2p network.
3784         ///
3785         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3786         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3787         ///
3788         /// May panic if the output found in the funding transaction is duplicative with some other
3789         /// channel (note that this should be trivially prevented by using unique funding transaction
3790         /// keys per-channel).
3791         ///
3792         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3793         /// counterparty's signature the funding transaction will automatically be broadcast via the
3794         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3795         ///
3796         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3797         /// not currently support replacing a funding transaction on an existing channel. Instead,
3798         /// create a new channel with a conflicting funding transaction.
3799         ///
3800         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3801         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3802         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3803         /// for more details.
3804         ///
3805         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3806         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3807         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3808                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3809         }
3810
3811         /// Call this upon creation of a batch funding transaction for the given channels.
3812         ///
3813         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3814         /// each individual channel and transaction output.
3815         ///
3816         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3817         /// will only be broadcast when we have safely received and persisted the counterparty's
3818         /// signature for each channel.
3819         ///
3820         /// If there is an error, all channels in the batch are to be considered closed.
3821         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3822                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3823                 let mut result = Ok(());
3824
3825                 if !funding_transaction.is_coin_base() {
3826                         for inp in funding_transaction.input.iter() {
3827                                 if inp.witness.is_empty() {
3828                                         result = result.and(Err(APIError::APIMisuseError {
3829                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3830                                         }));
3831                                 }
3832                         }
3833                 }
3834                 if funding_transaction.output.len() > u16::max_value() as usize {
3835                         result = result.and(Err(APIError::APIMisuseError {
3836                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3837                         }));
3838                 }
3839                 {
3840                         let height = self.best_block.read().unwrap().height();
3841                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3842                         // lower than the next block height. However, the modules constituting our Lightning
3843                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3844                         // module is ahead of LDK, only allow one more block of headroom.
3845                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) &&
3846                                 funding_transaction.lock_time.is_block_height() &&
3847                                 funding_transaction.lock_time.to_consensus_u32() > height + 1
3848                         {
3849                                 result = result.and(Err(APIError::APIMisuseError {
3850                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3851                                 }));
3852                         }
3853                 }
3854
3855                 let txid = funding_transaction.txid();
3856                 let is_batch_funding = temporary_channels.len() > 1;
3857                 let mut funding_batch_states = if is_batch_funding {
3858                         Some(self.funding_batch_states.lock().unwrap())
3859                 } else {
3860                         None
3861                 };
3862                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3863                         match states.entry(txid) {
3864                                 btree_map::Entry::Occupied(_) => {
3865                                         result = result.clone().and(Err(APIError::APIMisuseError {
3866                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3867                                         }));
3868                                         None
3869                                 },
3870                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3871                         }
3872                 });
3873                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3874                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3875                                 temporary_channel_id,
3876                                 counterparty_node_id,
3877                                 funding_transaction.clone(),
3878                                 is_batch_funding,
3879                                 |chan, tx| {
3880                                         let mut output_index = None;
3881                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3882                                         for (idx, outp) in tx.output.iter().enumerate() {
3883                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3884                                                         if output_index.is_some() {
3885                                                                 return Err(APIError::APIMisuseError {
3886                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3887                                                                 });
3888                                                         }
3889                                                         output_index = Some(idx as u16);
3890                                                 }
3891                                         }
3892                                         if output_index.is_none() {
3893                                                 return Err(APIError::APIMisuseError {
3894                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3895                                                 });
3896                                         }
3897                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3898                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3899                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3900                                         }
3901                                         Ok(outpoint)
3902                                 })
3903                         );
3904                 }
3905                 if let Err(ref e) = result {
3906                         // Remaining channels need to be removed on any error.
3907                         let e = format!("Error in transaction funding: {:?}", e);
3908                         let mut channels_to_remove = Vec::new();
3909                         channels_to_remove.extend(funding_batch_states.as_mut()
3910                                 .and_then(|states| states.remove(&txid))
3911                                 .into_iter().flatten()
3912                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3913                         );
3914                         channels_to_remove.extend(temporary_channels.iter()
3915                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3916                         );
3917                         let mut shutdown_results = Vec::new();
3918                         {
3919                                 let per_peer_state = self.per_peer_state.read().unwrap();
3920                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3921                                         per_peer_state.get(&counterparty_node_id)
3922                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3923                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3924                                                 .map(|mut chan| {
3925                                                         update_maps_on_chan_removal!(self, &chan.context());
3926                                                         self.issue_channel_close_events(&chan.context(), ClosureReason::ProcessingError { err: e.clone() });
3927                                                         shutdown_results.push(chan.context_mut().force_shutdown(false));
3928                                                 });
3929                                 }
3930                         }
3931                         for shutdown_result in shutdown_results.drain(..) {
3932                                 self.finish_close_channel(shutdown_result);
3933                         }
3934                 }
3935                 result
3936         }
3937
3938         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3939         ///
3940         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3941         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3942         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3943         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3944         ///
3945         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3946         /// `counterparty_node_id` is provided.
3947         ///
3948         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3949         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3950         ///
3951         /// If an error is returned, none of the updates should be considered applied.
3952         ///
3953         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3954         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3955         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3956         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3957         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3958         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3959         /// [`APIMisuseError`]: APIError::APIMisuseError
3960         pub fn update_partial_channel_config(
3961                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
3962         ) -> Result<(), APIError> {
3963                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
3964                         return Err(APIError::APIMisuseError {
3965                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
3966                         });
3967                 }
3968
3969                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3970                 let per_peer_state = self.per_peer_state.read().unwrap();
3971                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3972                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3973                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3974                 let peer_state = &mut *peer_state_lock;
3975                 for channel_id in channel_ids {
3976                         if !peer_state.has_channel(channel_id) {
3977                                 return Err(APIError::ChannelUnavailable {
3978                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
3979                                 });
3980                         };
3981                 }
3982                 for channel_id in channel_ids {
3983                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
3984                                 let mut config = channel_phase.context().config();
3985                                 config.apply(config_update);
3986                                 if !channel_phase.context_mut().update_config(&config) {
3987                                         continue;
3988                                 }
3989                                 if let ChannelPhase::Funded(channel) = channel_phase {
3990                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
3991                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
3992                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
3993                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
3994                                                         node_id: channel.context.get_counterparty_node_id(),
3995                                                         msg,
3996                                                 });
3997                                         }
3998                                 }
3999                                 continue;
4000                         } else {
4001                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4002                                 debug_assert!(false);
4003                                 return Err(APIError::ChannelUnavailable {
4004                                         err: format!(
4005                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4006                                                 channel_id, counterparty_node_id),
4007                                 });
4008                         };
4009                 }
4010                 Ok(())
4011         }
4012
4013         /// Atomically updates the [`ChannelConfig`] for the given channels.
4014         ///
4015         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4016         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4017         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4018         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4019         ///
4020         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4021         /// `counterparty_node_id` is provided.
4022         ///
4023         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4024         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4025         ///
4026         /// If an error is returned, none of the updates should be considered applied.
4027         ///
4028         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4029         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4030         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4031         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4032         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4033         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4034         /// [`APIMisuseError`]: APIError::APIMisuseError
4035         pub fn update_channel_config(
4036                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4037         ) -> Result<(), APIError> {
4038                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4039         }
4040
4041         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4042         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4043         ///
4044         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4045         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4046         ///
4047         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4048         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4049         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4050         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4051         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4052         ///
4053         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4054         /// you from forwarding more than you received. See
4055         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4056         /// than expected.
4057         ///
4058         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4059         /// backwards.
4060         ///
4061         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4062         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4063         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4064         // TODO: when we move to deciding the best outbound channel at forward time, only take
4065         // `next_node_id` and not `next_hop_channel_id`
4066         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> {
4067                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4068
4069                 let next_hop_scid = {
4070                         let peer_state_lock = self.per_peer_state.read().unwrap();
4071                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4072                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4073                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4074                         let peer_state = &mut *peer_state_lock;
4075                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4076                                 Some(ChannelPhase::Funded(chan)) => {
4077                                         if !chan.context.is_usable() {
4078                                                 return Err(APIError::ChannelUnavailable {
4079                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4080                                                 })
4081                                         }
4082                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4083                                 },
4084                                 Some(_) => return Err(APIError::ChannelUnavailable {
4085                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4086                                                 next_hop_channel_id, next_node_id)
4087                                 }),
4088                                 None => {
4089                                         let error = format!("Channel with id {} not found for the passed counterparty node_id {}",
4090                                                 next_hop_channel_id, next_node_id);
4091                                         let logger = WithContext::from(&self.logger, Some(next_node_id), Some(*next_hop_channel_id));
4092                                         log_error!(logger, "{} when attempting to forward intercepted HTLC", error);
4093                                         return Err(APIError::ChannelUnavailable {
4094                                                 err: error
4095                                         })
4096                                 }
4097                         }
4098                 };
4099
4100                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4101                         .ok_or_else(|| APIError::APIMisuseError {
4102                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4103                         })?;
4104
4105                 let routing = match payment.forward_info.routing {
4106                         PendingHTLCRouting::Forward { onion_packet, blinded, .. } => {
4107                                 PendingHTLCRouting::Forward {
4108                                         onion_packet, blinded, short_channel_id: next_hop_scid
4109                                 }
4110                         },
4111                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4112                 };
4113                 let skimmed_fee_msat =
4114                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4115                 let pending_htlc_info = PendingHTLCInfo {
4116                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4117                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4118                 };
4119
4120                 let mut per_source_pending_forward = [(
4121                         payment.prev_short_channel_id,
4122                         payment.prev_funding_outpoint,
4123                         payment.prev_user_channel_id,
4124                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4125                 )];
4126                 self.forward_htlcs(&mut per_source_pending_forward);
4127                 Ok(())
4128         }
4129
4130         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4131         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4132         ///
4133         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4134         /// backwards.
4135         ///
4136         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4137         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4138                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4139
4140                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4141                         .ok_or_else(|| APIError::APIMisuseError {
4142                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4143                         })?;
4144
4145                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4146                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4147                                 short_channel_id: payment.prev_short_channel_id,
4148                                 user_channel_id: Some(payment.prev_user_channel_id),
4149                                 outpoint: payment.prev_funding_outpoint,
4150                                 htlc_id: payment.prev_htlc_id,
4151                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4152                                 phantom_shared_secret: None,
4153                                 blinded_failure: payment.forward_info.routing.blinded_failure(),
4154                         });
4155
4156                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4157                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4158                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4159                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4160
4161                 Ok(())
4162         }
4163
4164         /// Processes HTLCs which are pending waiting on random forward delay.
4165         ///
4166         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4167         /// Will likely generate further events.
4168         pub fn process_pending_htlc_forwards(&self) {
4169                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4170
4171                 let mut new_events = VecDeque::new();
4172                 let mut failed_forwards = Vec::new();
4173                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4174                 {
4175                         let mut forward_htlcs = HashMap::new();
4176                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4177
4178                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4179                                 if short_chan_id != 0 {
4180                                         let mut forwarding_counterparty = None;
4181                                         macro_rules! forwarding_channel_not_found {
4182                                                 () => {
4183                                                         for forward_info in pending_forwards.drain(..) {
4184                                                                 match forward_info {
4185                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4186                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4187                                                                                 forward_info: PendingHTLCInfo {
4188                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4189                                                                                         outgoing_cltv_value, ..
4190                                                                                 }
4191                                                                         }) => {
4192                                                                                 macro_rules! failure_handler {
4193                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4194                                                                                                 let logger = WithContext::from(&self.logger, forwarding_counterparty, Some(prev_funding_outpoint.to_channel_id()));
4195                                                                                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4196
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_shared_secret: $phantom_ss,
4204                                                                                                         blinded_failure: routing.blinded_failure(),
4205                                                                                                 });
4206
4207                                                                                                 let reason = if $next_hop_unknown {
4208                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4209                                                                                                 } else {
4210                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4211                                                                                                 };
4212
4213                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4214                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4215                                                                                                         reason
4216                                                                                                 ));
4217                                                                                                 continue;
4218                                                                                         }
4219                                                                                 }
4220                                                                                 macro_rules! fail_forward {
4221                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4222                                                                                                 {
4223                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4224                                                                                                 }
4225                                                                                         }
4226                                                                                 }
4227                                                                                 macro_rules! failed_payment {
4228                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4229                                                                                                 {
4230                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4231                                                                                                 }
4232                                                                                         }
4233                                                                                 }
4234                                                                                 if let PendingHTLCRouting::Forward { ref onion_packet, .. } = routing {
4235                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4236                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4237                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4238                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4239                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4240                                                                                                         payment_hash, &self.node_signer
4241                                                                                                 ) {
4242                                                                                                         Ok(res) => res,
4243                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4244                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).to_byte_array();
4245                                                                                                                 // In this scenario, the phantom would have sent us an
4246                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4247                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4248                                                                                                                 // of the onion.
4249                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4250                                                                                                         },
4251                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4252                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4253                                                                                                         },
4254                                                                                                 };
4255                                                                                                 match next_hop {
4256                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4257                                                                                                                 let current_height: u32 = self.best_block.read().unwrap().height();
4258                                                                                                                 match create_recv_pending_htlc_info(hop_data,
4259                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4260                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None,
4261                                                                                                                         current_height, self.default_configuration.accept_mpp_keysend)
4262                                                                                                                 {
4263                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4264                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4265                                                                                                                 }
4266                                                                                                         },
4267                                                                                                         _ => panic!(),
4268                                                                                                 }
4269                                                                                         } else {
4270                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4271                                                                                         }
4272                                                                                 } else {
4273                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4274                                                                                 }
4275                                                                         },
4276                                                                         HTLCForwardInfo::FailHTLC { .. } => {
4277                                                                                 // Channel went away before we could fail it. This implies
4278                                                                                 // the channel is now on chain and our counterparty is
4279                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4280                                                                                 // problem, not ours.
4281                                                                         }
4282                                                                 }
4283                                                         }
4284                                                 }
4285                                         }
4286                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4287                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4288                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4289                                                 None => {
4290                                                         forwarding_channel_not_found!();
4291                                                         continue;
4292                                                 }
4293                                         };
4294                                         forwarding_counterparty = Some(counterparty_node_id);
4295                                         let per_peer_state = self.per_peer_state.read().unwrap();
4296                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4297                                         if peer_state_mutex_opt.is_none() {
4298                                                 forwarding_channel_not_found!();
4299                                                 continue;
4300                                         }
4301                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4302                                         let peer_state = &mut *peer_state_lock;
4303                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4304                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4305                                                 for forward_info in pending_forwards.drain(..) {
4306                                                         match forward_info {
4307                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4308                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4309                                                                         forward_info: PendingHTLCInfo {
4310                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4311                                                                                 routing: PendingHTLCRouting::Forward {
4312                                                                                         onion_packet, blinded, ..
4313                                                                                 }, skimmed_fee_msat, ..
4314                                                                         },
4315                                                                 }) => {
4316                                                                         log_trace!(logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", prev_short_channel_id, &payment_hash, short_chan_id);
4317                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4318                                                                                 short_channel_id: prev_short_channel_id,
4319                                                                                 user_channel_id: Some(prev_user_channel_id),
4320                                                                                 outpoint: prev_funding_outpoint,
4321                                                                                 htlc_id: prev_htlc_id,
4322                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4323                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4324                                                                                 phantom_shared_secret: None,
4325                                                                                 blinded_failure: blinded.map(|_| BlindedFailure::FromIntroductionNode),
4326                                                                         });
4327                                                                         let next_blinding_point = blinded.and_then(|b| {
4328                                                                                 let encrypted_tlvs_ss = self.node_signer.ecdh(
4329                                                                                         Recipient::Node, &b.inbound_blinding_point, None
4330                                                                                 ).unwrap().secret_bytes();
4331                                                                                 onion_utils::next_hop_pubkey(
4332                                                                                         &self.secp_ctx, b.inbound_blinding_point, &encrypted_tlvs_ss
4333                                                                                 ).ok()
4334                                                                         });
4335                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4336                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4337                                                                                 onion_packet, skimmed_fee_msat, next_blinding_point, &self.fee_estimator,
4338                                                                                 &&logger)
4339                                                                         {
4340                                                                                 if let ChannelError::Ignore(msg) = e {
4341                                                                                         log_trace!(logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4342                                                                                 } else {
4343                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4344                                                                                 }
4345                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4346                                                                                 failed_forwards.push((htlc_source, payment_hash,
4347                                                                                         HTLCFailReason::reason(failure_code, data),
4348                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4349                                                                                 ));
4350                                                                                 continue;
4351                                                                         }
4352                                                                 },
4353                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4354                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4355                                                                 },
4356                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4357                                                                         log_trace!(logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4358                                                                         if let Err(e) = chan.queue_fail_htlc(
4359                                                                                 htlc_id, err_packet, &&logger
4360                                                                         ) {
4361                                                                                 if let ChannelError::Ignore(msg) = e {
4362                                                                                         log_trace!(logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4363                                                                                 } else {
4364                                                                                         panic!("Stated return value requirements in queue_fail_htlc() were not met");
4365                                                                                 }
4366                                                                                 // fail-backs are best-effort, we probably already have one
4367                                                                                 // pending, and if not that's OK, if not, the channel is on
4368                                                                                 // the chain and sending the HTLC-Timeout is their problem.
4369                                                                                 continue;
4370                                                                         }
4371                                                                 },
4372                                                         }
4373                                                 }
4374                                         } else {
4375                                                 forwarding_channel_not_found!();
4376                                                 continue;
4377                                         }
4378                                 } else {
4379                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4380                                                 match forward_info {
4381                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4382                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4383                                                                 forward_info: PendingHTLCInfo {
4384                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4385                                                                         skimmed_fee_msat, ..
4386                                                                 }
4387                                                         }) => {
4388                                                                 let blinded_failure = routing.blinded_failure();
4389                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4390                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4391                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4392                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4393                                                                                                 payment_metadata, custom_tlvs };
4394                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4395                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4396                                                                         },
4397                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4398                                                                                 let onion_fields = RecipientOnionFields {
4399                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4400                                                                                         payment_metadata,
4401                                                                                         custom_tlvs,
4402                                                                                 };
4403                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4404                                                                                         payment_data, None, onion_fields)
4405                                                                         },
4406                                                                         _ => {
4407                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4408                                                                         }
4409                                                                 };
4410                                                                 let claimable_htlc = ClaimableHTLC {
4411                                                                         prev_hop: HTLCPreviousHopData {
4412                                                                                 short_channel_id: prev_short_channel_id,
4413                                                                                 user_channel_id: Some(prev_user_channel_id),
4414                                                                                 outpoint: prev_funding_outpoint,
4415                                                                                 htlc_id: prev_htlc_id,
4416                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4417                                                                                 phantom_shared_secret,
4418                                                                                 blinded_failure,
4419                                                                         },
4420                                                                         // We differentiate the received value from the sender intended value
4421                                                                         // if possible so that we don't prematurely mark MPP payments complete
4422                                                                         // if routing nodes overpay
4423                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4424                                                                         sender_intended_value: outgoing_amt_msat,
4425                                                                         timer_ticks: 0,
4426                                                                         total_value_received: None,
4427                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4428                                                                         cltv_expiry,
4429                                                                         onion_payload,
4430                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4431                                                                 };
4432
4433                                                                 let mut committed_to_claimable = false;
4434
4435                                                                 macro_rules! fail_htlc {
4436                                                                         ($htlc: expr, $payment_hash: expr) => {
4437                                                                                 debug_assert!(!committed_to_claimable);
4438                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4439                                                                                 htlc_msat_height_data.extend_from_slice(
4440                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4441                                                                                 );
4442                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4443                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4444                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4445                                                                                                 outpoint: prev_funding_outpoint,
4446                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4447                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4448                                                                                                 phantom_shared_secret,
4449                                                                                                 blinded_failure: None,
4450                                                                                         }), payment_hash,
4451                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4452                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4453                                                                                 ));
4454                                                                                 continue 'next_forwardable_htlc;
4455                                                                         }
4456                                                                 }
4457                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4458                                                                 let mut receiver_node_id = self.our_network_pubkey;
4459                                                                 if phantom_shared_secret.is_some() {
4460                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4461                                                                                 .expect("Failed to get node_id for phantom node recipient");
4462                                                                 }
4463
4464                                                                 macro_rules! check_total_value {
4465                                                                         ($purpose: expr) => {{
4466                                                                                 let mut payment_claimable_generated = false;
4467                                                                                 let is_keysend = match $purpose {
4468                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4469                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4470                                                                                 };
4471                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4472                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4473                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4474                                                                                 }
4475                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4476                                                                                         .entry(payment_hash)
4477                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4478                                                                                         .or_insert_with(|| {
4479                                                                                                 committed_to_claimable = true;
4480                                                                                                 ClaimablePayment {
4481                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4482                                                                                                 }
4483                                                                                         });
4484                                                                                 if $purpose != claimable_payment.purpose {
4485                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4486                                                                                         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));
4487                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4488                                                                                 }
4489                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4490                                                                                         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);
4491                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4492                                                                                 }
4493                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4494                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4495                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4496                                                                                         }
4497                                                                                 } else {
4498                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4499                                                                                 }
4500                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4501                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4502                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4503                                                                                 for htlc in htlcs.iter() {
4504                                                                                         total_value += htlc.sender_intended_value;
4505                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4506                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4507                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4508                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4509                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4510                                                                                         }
4511                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4512                                                                                 }
4513                                                                                 // The condition determining whether an MPP is complete must
4514                                                                                 // match exactly the condition used in `timer_tick_occurred`
4515                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4516                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4517                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4518                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4519                                                                                                 &payment_hash);
4520                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4521                                                                                 } else if total_value >= claimable_htlc.total_msat {
4522                                                                                         #[allow(unused_assignments)] {
4523                                                                                                 committed_to_claimable = true;
4524                                                                                         }
4525                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4526                                                                                         htlcs.push(claimable_htlc);
4527                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4528                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4529                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4530                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4531                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4532                                                                                                 counterparty_skimmed_fee_msat);
4533                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4534                                                                                                 receiver_node_id: Some(receiver_node_id),
4535                                                                                                 payment_hash,
4536                                                                                                 purpose: $purpose,
4537                                                                                                 amount_msat,
4538                                                                                                 counterparty_skimmed_fee_msat,
4539                                                                                                 via_channel_id: Some(prev_channel_id),
4540                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4541                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4542                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4543                                                                                         }, None));
4544                                                                                         payment_claimable_generated = true;
4545                                                                                 } else {
4546                                                                                         // Nothing to do - we haven't reached the total
4547                                                                                         // payment value yet, wait until we receive more
4548                                                                                         // MPP parts.
4549                                                                                         htlcs.push(claimable_htlc);
4550                                                                                         #[allow(unused_assignments)] {
4551                                                                                                 committed_to_claimable = true;
4552                                                                                         }
4553                                                                                 }
4554                                                                                 payment_claimable_generated
4555                                                                         }}
4556                                                                 }
4557
4558                                                                 // Check that the payment hash and secret are known. Note that we
4559                                                                 // MUST take care to handle the "unknown payment hash" and
4560                                                                 // "incorrect payment secret" cases here identically or we'd expose
4561                                                                 // that we are the ultimate recipient of the given payment hash.
4562                                                                 // Further, we must not expose whether we have any other HTLCs
4563                                                                 // associated with the same payment_hash pending or not.
4564                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4565                                                                 match payment_secrets.entry(payment_hash) {
4566                                                                         hash_map::Entry::Vacant(_) => {
4567                                                                                 match claimable_htlc.onion_payload {
4568                                                                                         OnionPayload::Invoice { .. } => {
4569                                                                                                 let payment_data = payment_data.unwrap();
4570                                                                                                 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) {
4571                                                                                                         Ok(result) => result,
4572                                                                                                         Err(()) => {
4573                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4574                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4575                                                                                                         }
4576                                                                                                 };
4577                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4578                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4579                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4580                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4581                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4582                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4583                                                                                                         }
4584                                                                                                 }
4585                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4586                                                                                                         payment_preimage: payment_preimage.clone(),
4587                                                                                                         payment_secret: payment_data.payment_secret,
4588                                                                                                 };
4589                                                                                                 check_total_value!(purpose);
4590                                                                                         },
4591                                                                                         OnionPayload::Spontaneous(preimage) => {
4592                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4593                                                                                                 check_total_value!(purpose);
4594                                                                                         }
4595                                                                                 }
4596                                                                         },
4597                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4598                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4599                                                                                         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);
4600                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4601                                                                                 }
4602                                                                                 let payment_data = payment_data.unwrap();
4603                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4604                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4605                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4606                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4607                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4608                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4609                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4610                                                                                 } else {
4611                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4612                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4613                                                                                                 payment_secret: payment_data.payment_secret,
4614                                                                                         };
4615                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4616                                                                                         if payment_claimable_generated {
4617                                                                                                 inbound_payment.remove_entry();
4618                                                                                         }
4619                                                                                 }
4620                                                                         },
4621                                                                 };
4622                                                         },
4623                                                         HTLCForwardInfo::FailHTLC { .. } => {
4624                                                                 panic!("Got pending fail of our own HTLC");
4625                                                         }
4626                                                 }
4627                                         }
4628                                 }
4629                         }
4630                 }
4631
4632                 let best_block_height = self.best_block.read().unwrap().height();
4633                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4634                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4635                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4636
4637                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4638                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4639                 }
4640                 self.forward_htlcs(&mut phantom_receives);
4641
4642                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4643                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4644                 // nice to do the work now if we can rather than while we're trying to get messages in the
4645                 // network stack.
4646                 self.check_free_holding_cells();
4647
4648                 if new_events.is_empty() { return }
4649                 let mut events = self.pending_events.lock().unwrap();
4650                 events.append(&mut new_events);
4651         }
4652
4653         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4654         ///
4655         /// Expects the caller to have a total_consistency_lock read lock.
4656         fn process_background_events(&self) -> NotifyOption {
4657                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4658
4659                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4660
4661                 let mut background_events = Vec::new();
4662                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4663                 if background_events.is_empty() {
4664                         return NotifyOption::SkipPersistNoEvents;
4665                 }
4666
4667                 for event in background_events.drain(..) {
4668                         match event {
4669                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4670                                         // The channel has already been closed, so no use bothering to care about the
4671                                         // monitor updating completing.
4672                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4673                                 },
4674                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4675                                         let mut updated_chan = false;
4676                                         {
4677                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4678                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4679                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4680                                                         let peer_state = &mut *peer_state_lock;
4681                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4682                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4683                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4684                                                                                 updated_chan = true;
4685                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4686                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4687                                                                         } else {
4688                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4689                                                                         }
4690                                                                 },
4691                                                                 hash_map::Entry::Vacant(_) => {},
4692                                                         }
4693                                                 }
4694                                         }
4695                                         if !updated_chan {
4696                                                 // TODO: Track this as in-flight even though the channel is closed.
4697                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4698                                         }
4699                                 },
4700                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4701                                         let per_peer_state = self.per_peer_state.read().unwrap();
4702                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4703                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4704                                                 let peer_state = &mut *peer_state_lock;
4705                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4706                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4707                                                 } else {
4708                                                         let update_actions = peer_state.monitor_update_blocked_actions
4709                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4710                                                         mem::drop(peer_state_lock);
4711                                                         mem::drop(per_peer_state);
4712                                                         self.handle_monitor_update_completion_actions(update_actions);
4713                                                 }
4714                                         }
4715                                 },
4716                         }
4717                 }
4718                 NotifyOption::DoPersist
4719         }
4720
4721         #[cfg(any(test, feature = "_test_utils"))]
4722         /// Process background events, for functional testing
4723         pub fn test_process_background_events(&self) {
4724                 let _lck = self.total_consistency_lock.read().unwrap();
4725                 let _ = self.process_background_events();
4726         }
4727
4728         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4729                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4730
4731                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4732
4733                 // If the feerate has decreased by less than half, don't bother
4734                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4735                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4736                                 log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4737                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4738                         }
4739                         return NotifyOption::SkipPersistNoEvents;
4740                 }
4741                 if !chan.context.is_live() {
4742                         log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
4743                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4744                         return NotifyOption::SkipPersistNoEvents;
4745                 }
4746                 log_trace!(logger, "Channel {} qualifies for a feerate change from {} to {}.",
4747                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4748
4749                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &&logger);
4750                 NotifyOption::DoPersist
4751         }
4752
4753         #[cfg(fuzzing)]
4754         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4755         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4756         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4757         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4758         pub fn maybe_update_chan_fees(&self) {
4759                 PersistenceNotifierGuard::optionally_notify(self, || {
4760                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4761
4762                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4763                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4764
4765                         let per_peer_state = self.per_peer_state.read().unwrap();
4766                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4767                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4768                                 let peer_state = &mut *peer_state_lock;
4769                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4770                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4771                                 ) {
4772                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4773                                                 anchor_feerate
4774                                         } else {
4775                                                 non_anchor_feerate
4776                                         };
4777                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4778                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4779                                 }
4780                         }
4781
4782                         should_persist
4783                 });
4784         }
4785
4786         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4787         ///
4788         /// This currently includes:
4789         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4790         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4791         ///    than a minute, informing the network that they should no longer attempt to route over
4792         ///    the channel.
4793         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4794         ///    with the current [`ChannelConfig`].
4795         ///  * Removing peers which have disconnected but and no longer have any channels.
4796         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4797         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4798         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4799         ///    The latter is determined using the system clock in `std` and the highest seen block time
4800         ///    minus two hours in `no-std`.
4801         ///
4802         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4803         /// estimate fetches.
4804         ///
4805         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4806         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4807         pub fn timer_tick_occurred(&self) {
4808                 PersistenceNotifierGuard::optionally_notify(self, || {
4809                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4810
4811                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4812                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4813
4814                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4815                         let mut timed_out_mpp_htlcs = Vec::new();
4816                         let mut pending_peers_awaiting_removal = Vec::new();
4817                         let mut shutdown_channels = Vec::new();
4818
4819                         let mut process_unfunded_channel_tick = |
4820                                 chan_id: &ChannelId,
4821                                 context: &mut ChannelContext<SP>,
4822                                 unfunded_context: &mut UnfundedChannelContext,
4823                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4824                                 counterparty_node_id: PublicKey,
4825                         | {
4826                                 context.maybe_expire_prev_config();
4827                                 if unfunded_context.should_expire_unfunded_channel() {
4828                                         let logger = WithChannelContext::from(&self.logger, context);
4829                                         log_error!(logger,
4830                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4831                                         update_maps_on_chan_removal!(self, &context);
4832                                         self.issue_channel_close_events(&context, ClosureReason::HolderForceClosed);
4833                                         shutdown_channels.push(context.force_shutdown(false));
4834                                         pending_msg_events.push(MessageSendEvent::HandleError {
4835                                                 node_id: counterparty_node_id,
4836                                                 action: msgs::ErrorAction::SendErrorMessage {
4837                                                         msg: msgs::ErrorMessage {
4838                                                                 channel_id: *chan_id,
4839                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4840                                                         },
4841                                                 },
4842                                         });
4843                                         false
4844                                 } else {
4845                                         true
4846                                 }
4847                         };
4848
4849                         {
4850                                 let per_peer_state = self.per_peer_state.read().unwrap();
4851                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4852                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4853                                         let peer_state = &mut *peer_state_lock;
4854                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4855                                         let counterparty_node_id = *counterparty_node_id;
4856                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4857                                                 match phase {
4858                                                         ChannelPhase::Funded(chan) => {
4859                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4860                                                                         anchor_feerate
4861                                                                 } else {
4862                                                                         non_anchor_feerate
4863                                                                 };
4864                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4865                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4866
4867                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4868                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4869                                                                         handle_errors.push((Err(err), counterparty_node_id));
4870                                                                         if needs_close { return false; }
4871                                                                 }
4872
4873                                                                 match chan.channel_update_status() {
4874                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4875                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4876                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4877                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4878                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4879                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4880                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4881                                                                                 n += 1;
4882                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4883                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4884                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4885                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4886                                                                                                         msg: update
4887                                                                                                 });
4888                                                                                         }
4889                                                                                         should_persist = NotifyOption::DoPersist;
4890                                                                                 } else {
4891                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4892                                                                                 }
4893                                                                         },
4894                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4895                                                                                 n += 1;
4896                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4897                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4898                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4899                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4900                                                                                                         msg: update
4901                                                                                                 });
4902                                                                                         }
4903                                                                                         should_persist = NotifyOption::DoPersist;
4904                                                                                 } else {
4905                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4906                                                                                 }
4907                                                                         },
4908                                                                         _ => {},
4909                                                                 }
4910
4911                                                                 chan.context.maybe_expire_prev_config();
4912
4913                                                                 if chan.should_disconnect_peer_awaiting_response() {
4914                                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
4915                                                                         log_debug!(logger, "Disconnecting peer {} due to not making any progress on channel {}",
4916                                                                                         counterparty_node_id, chan_id);
4917                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4918                                                                                 node_id: counterparty_node_id,
4919                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4920                                                                                         msg: msgs::WarningMessage {
4921                                                                                                 channel_id: *chan_id,
4922                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4923                                                                                         },
4924                                                                                 },
4925                                                                         });
4926                                                                 }
4927
4928                                                                 true
4929                                                         },
4930                                                         ChannelPhase::UnfundedInboundV1(chan) => {
4931                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4932                                                                         pending_msg_events, counterparty_node_id)
4933                                                         },
4934                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
4935                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4936                                                                         pending_msg_events, counterparty_node_id)
4937                                                         },
4938                                                 }
4939                                         });
4940
4941                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4942                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4943                                                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(*chan_id));
4944                                                         log_error!(logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
4945                                                         peer_state.pending_msg_events.push(
4946                                                                 events::MessageSendEvent::HandleError {
4947                                                                         node_id: counterparty_node_id,
4948                                                                         action: msgs::ErrorAction::SendErrorMessage {
4949                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4950                                                                         },
4951                                                                 }
4952                                                         );
4953                                                 }
4954                                         }
4955                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4956
4957                                         if peer_state.ok_to_remove(true) {
4958                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4959                                         }
4960                                 }
4961                         }
4962
4963                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4964                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4965                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4966                         // we therefore need to remove the peer from `peer_state` separately.
4967                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4968                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4969                         // negative effects on parallelism as much as possible.
4970                         if pending_peers_awaiting_removal.len() > 0 {
4971                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4972                                 for counterparty_node_id in pending_peers_awaiting_removal {
4973                                         match per_peer_state.entry(counterparty_node_id) {
4974                                                 hash_map::Entry::Occupied(entry) => {
4975                                                         // Remove the entry if the peer is still disconnected and we still
4976                                                         // have no channels to the peer.
4977                                                         let remove_entry = {
4978                                                                 let peer_state = entry.get().lock().unwrap();
4979                                                                 peer_state.ok_to_remove(true)
4980                                                         };
4981                                                         if remove_entry {
4982                                                                 entry.remove_entry();
4983                                                         }
4984                                                 },
4985                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
4986                                         }
4987                                 }
4988                         }
4989
4990                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
4991                                 if payment.htlcs.is_empty() {
4992                                         // This should be unreachable
4993                                         debug_assert!(false);
4994                                         return false;
4995                                 }
4996                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
4997                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
4998                                         // In this case we're not going to handle any timeouts of the parts here.
4999                                         // This condition determining whether the MPP is complete here must match
5000                                         // exactly the condition used in `process_pending_htlc_forwards`.
5001                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5002                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5003                                         {
5004                                                 return true;
5005                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5006                                                 htlc.timer_ticks += 1;
5007                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5008                                         }) {
5009                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5010                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5011                                                 return false;
5012                                         }
5013                                 }
5014                                 true
5015                         });
5016
5017                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5018                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5019                                 let reason = HTLCFailReason::from_failure_code(23);
5020                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5021                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5022                         }
5023
5024                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5025                                 let _ = handle_error!(self, err, counterparty_node_id);
5026                         }
5027
5028                         for shutdown_res in shutdown_channels {
5029                                 self.finish_close_channel(shutdown_res);
5030                         }
5031
5032                         #[cfg(feature = "std")]
5033                         let duration_since_epoch = std::time::SystemTime::now()
5034                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5035                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5036                         #[cfg(not(feature = "std"))]
5037                         let duration_since_epoch = Duration::from_secs(
5038                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5039                         );
5040
5041                         self.pending_outbound_payments.remove_stale_payments(
5042                                 duration_since_epoch, &self.pending_events
5043                         );
5044
5045                         // Technically we don't need to do this here, but if we have holding cell entries in a
5046                         // channel that need freeing, it's better to do that here and block a background task
5047                         // than block the message queueing pipeline.
5048                         if self.check_free_holding_cells() {
5049                                 should_persist = NotifyOption::DoPersist;
5050                         }
5051
5052                         should_persist
5053                 });
5054         }
5055
5056         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5057         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5058         /// along the path (including in our own channel on which we received it).
5059         ///
5060         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5061         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5062         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5063         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5064         ///
5065         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5066         /// [`ChannelManager::claim_funds`]), you should still monitor for
5067         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5068         /// startup during which time claims that were in-progress at shutdown may be replayed.
5069         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5070                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5071         }
5072
5073         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5074         /// reason for the failure.
5075         ///
5076         /// See [`FailureCode`] for valid failure codes.
5077         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5078                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5079
5080                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5081                 if let Some(payment) = removed_source {
5082                         for htlc in payment.htlcs {
5083                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5084                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5085                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5086                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5087                         }
5088                 }
5089         }
5090
5091         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5092         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5093                 match failure_code {
5094                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5095                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5096                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5097                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5098                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5099                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5100                         },
5101                         FailureCode::InvalidOnionPayload(data) => {
5102                                 let fail_data = match data {
5103                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5104                                         None => Vec::new(),
5105                                 };
5106                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5107                         }
5108                 }
5109         }
5110
5111         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5112         /// that we want to return and a channel.
5113         ///
5114         /// This is for failures on the channel on which the HTLC was *received*, not failures
5115         /// forwarding
5116         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5117                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5118                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5119                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5120                 // an inbound SCID alias before the real SCID.
5121                 let scid_pref = if chan.context.should_announce() {
5122                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5123                 } else {
5124                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5125                 };
5126                 if let Some(scid) = scid_pref {
5127                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5128                 } else {
5129                         (0x4000|10, Vec::new())
5130                 }
5131         }
5132
5133
5134         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5135         /// that we want to return and a channel.
5136         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5137                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5138                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5139                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5140                         if desired_err_code == 0x1000 | 20 {
5141                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5142                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5143                                 0u16.write(&mut enc).expect("Writes cannot fail");
5144                         }
5145                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5146                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5147                         upd.write(&mut enc).expect("Writes cannot fail");
5148                         (desired_err_code, enc.0)
5149                 } else {
5150                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5151                         // which means we really shouldn't have gotten a payment to be forwarded over this
5152                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5153                         // PERM|no_such_channel should be fine.
5154                         (0x4000|10, Vec::new())
5155                 }
5156         }
5157
5158         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5159         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5160         // be surfaced to the user.
5161         fn fail_holding_cell_htlcs(
5162                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5163                 counterparty_node_id: &PublicKey
5164         ) {
5165                 let (failure_code, onion_failure_data) = {
5166                         let per_peer_state = self.per_peer_state.read().unwrap();
5167                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5168                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5169                                 let peer_state = &mut *peer_state_lock;
5170                                 match peer_state.channel_by_id.entry(channel_id) {
5171                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5172                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5173                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5174                                                 } else {
5175                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5176                                                         debug_assert!(false);
5177                                                         (0x4000|10, Vec::new())
5178                                                 }
5179                                         },
5180                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5181                                 }
5182                         } else { (0x4000|10, Vec::new()) }
5183                 };
5184
5185                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5186                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5187                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5188                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5189                 }
5190         }
5191
5192         /// Fails an HTLC backwards to the sender of it to us.
5193         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5194         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5195                 // Ensure that no peer state channel storage lock is held when calling this function.
5196                 // This ensures that future code doesn't introduce a lock-order requirement for
5197                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5198                 // this function with any `per_peer_state` peer lock acquired would.
5199                 #[cfg(debug_assertions)]
5200                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5201                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5202                 }
5203
5204                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5205                 //identify whether we sent it or not based on the (I presume) very different runtime
5206                 //between the branches here. We should make this async and move it into the forward HTLCs
5207                 //timer handling.
5208
5209                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5210                 // from block_connected which may run during initialization prior to the chain_monitor
5211                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5212                 match source {
5213                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5214                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5215                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5216                                         &self.pending_events, &self.logger)
5217                                 { self.push_pending_forwards_ev(); }
5218                         },
5219                         HTLCSource::PreviousHopData(HTLCPreviousHopData {
5220                                 ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret,
5221                                 ref phantom_shared_secret, ref outpoint, ref blinded_failure, ..
5222                         }) => {
5223                                 log_trace!(
5224                                         WithContext::from(&self.logger, None, Some(outpoint.to_channel_id())),
5225                                         "Failing {}HTLC with payment_hash {} backwards from us: {:?}",
5226                                         if blinded_failure.is_some() { "blinded " } else { "" }, &payment_hash, onion_error
5227                                 );
5228                                 let err_packet = match blinded_failure {
5229                                         Some(BlindedFailure::FromIntroductionNode) => {
5230                                                 let blinded_onion_error = HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32]);
5231                                                 blinded_onion_error.get_encrypted_failure_packet(
5232                                                         incoming_packet_shared_secret, phantom_shared_secret
5233                                                 )
5234                                         },
5235                                         None => {
5236                                                 onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret)
5237                                         }
5238                                 };
5239
5240                                 let mut push_forward_ev = false;
5241                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5242                                 if forward_htlcs.is_empty() {
5243                                         push_forward_ev = true;
5244                                 }
5245                                 match forward_htlcs.entry(*short_channel_id) {
5246                                         hash_map::Entry::Occupied(mut entry) => {
5247                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
5248                                         },
5249                                         hash_map::Entry::Vacant(entry) => {
5250                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
5251                                         }
5252                                 }
5253                                 mem::drop(forward_htlcs);
5254                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5255                                 let mut pending_events = self.pending_events.lock().unwrap();
5256                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5257                                         prev_channel_id: outpoint.to_channel_id(),
5258                                         failed_next_destination: destination,
5259                                 }, None));
5260                         },
5261                 }
5262         }
5263
5264         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5265         /// [`MessageSendEvent`]s needed to claim the payment.
5266         ///
5267         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5268         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5269         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5270         /// successful. It will generally be available in the next [`process_pending_events`] call.
5271         ///
5272         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5273         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5274         /// event matches your expectation. If you fail to do so and call this method, you may provide
5275         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5276         ///
5277         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5278         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5279         /// [`claim_funds_with_known_custom_tlvs`].
5280         ///
5281         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5282         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5283         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5284         /// [`process_pending_events`]: EventsProvider::process_pending_events
5285         /// [`create_inbound_payment`]: Self::create_inbound_payment
5286         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5287         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5288         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5289                 self.claim_payment_internal(payment_preimage, false);
5290         }
5291
5292         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5293         /// even type numbers.
5294         ///
5295         /// # Note
5296         ///
5297         /// You MUST check you've understood all even TLVs before using this to
5298         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5299         ///
5300         /// [`claim_funds`]: Self::claim_funds
5301         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5302                 self.claim_payment_internal(payment_preimage, true);
5303         }
5304
5305         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5306                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
5307
5308                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5309
5310                 let mut sources = {
5311                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5312                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5313                                 let mut receiver_node_id = self.our_network_pubkey;
5314                                 for htlc in payment.htlcs.iter() {
5315                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5316                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5317                                                         .expect("Failed to get node_id for phantom node recipient");
5318                                                 receiver_node_id = phantom_pubkey;
5319                                                 break;
5320                                         }
5321                                 }
5322
5323                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5324                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5325                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5326                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5327                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5328                                 });
5329                                 if dup_purpose.is_some() {
5330                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5331                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5332                                                 &payment_hash);
5333                                 }
5334
5335                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5336                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5337                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5338                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5339                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5340                                                 mem::drop(claimable_payments);
5341                                                 for htlc in payment.htlcs {
5342                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5343                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5344                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5345                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5346                                                 }
5347                                                 return;
5348                                         }
5349                                 }
5350
5351                                 payment.htlcs
5352                         } else { return; }
5353                 };
5354                 debug_assert!(!sources.is_empty());
5355
5356                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5357                 // and when we got here we need to check that the amount we're about to claim matches the
5358                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5359                 // the MPP parts all have the same `total_msat`.
5360                 let mut claimable_amt_msat = 0;
5361                 let mut prev_total_msat = None;
5362                 let mut expected_amt_msat = None;
5363                 let mut valid_mpp = true;
5364                 let mut errs = Vec::new();
5365                 let per_peer_state = self.per_peer_state.read().unwrap();
5366                 for htlc in sources.iter() {
5367                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5368                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5369                                 debug_assert!(false);
5370                                 valid_mpp = false;
5371                                 break;
5372                         }
5373                         prev_total_msat = Some(htlc.total_msat);
5374
5375                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5376                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5377                                 debug_assert!(false);
5378                                 valid_mpp = false;
5379                                 break;
5380                         }
5381                         expected_amt_msat = htlc.total_value_received;
5382                         claimable_amt_msat += htlc.value;
5383                 }
5384                 mem::drop(per_peer_state);
5385                 if sources.is_empty() || expected_amt_msat.is_none() {
5386                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5387                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5388                         return;
5389                 }
5390                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5391                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5392                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5393                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5394                         return;
5395                 }
5396                 if valid_mpp {
5397                         for htlc in sources.drain(..) {
5398                                 let prev_hop_chan_id = htlc.prev_hop.outpoint.to_channel_id();
5399                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5400                                         htlc.prev_hop, payment_preimage,
5401                                         |_, definitely_duplicate| {
5402                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5403                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5404                                         }
5405                                 ) {
5406                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5407                                                 // We got a temporary failure updating monitor, but will claim the
5408                                                 // HTLC when the monitor updating is restored (or on chain).
5409                                                 let logger = WithContext::from(&self.logger, None, Some(prev_hop_chan_id));
5410                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5411                                         } else { errs.push((pk, err)); }
5412                                 }
5413                         }
5414                 }
5415                 if !valid_mpp {
5416                         for htlc in sources.drain(..) {
5417                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5418                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5419                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5420                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5421                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5422                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5423                         }
5424                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5425                 }
5426
5427                 // Now we can handle any errors which were generated.
5428                 for (counterparty_node_id, err) in errs.drain(..) {
5429                         let res: Result<(), _> = Err(err);
5430                         let _ = handle_error!(self, res, counterparty_node_id);
5431                 }
5432         }
5433
5434         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5435                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5436         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5437                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5438
5439                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5440                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5441                 // `BackgroundEvent`s.
5442                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5443
5444                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5445                 // the required mutexes are not held before we start.
5446                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5447                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5448
5449                 {
5450                         let per_peer_state = self.per_peer_state.read().unwrap();
5451                         let chan_id = prev_hop.outpoint.to_channel_id();
5452                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5453                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5454                                 None => None
5455                         };
5456
5457                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5458                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5459                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5460                         ).unwrap_or(None);
5461
5462                         if peer_state_opt.is_some() {
5463                                 let mut peer_state_lock = peer_state_opt.unwrap();
5464                                 let peer_state = &mut *peer_state_lock;
5465                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5466                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5467                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5468                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
5469                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &&logger);
5470
5471                                                 match fulfill_res {
5472                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5473                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5474                                                                         log_trace!(logger, "Tracking monitor update completion action for channel {}: {:?}",
5475                                                                                 chan_id, action);
5476                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5477                                                                 }
5478                                                                 if !during_init {
5479                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5480                                                                                 peer_state, per_peer_state, chan);
5481                                                                 } else {
5482                                                                         // If we're running during init we cannot update a monitor directly -
5483                                                                         // they probably haven't actually been loaded yet. Instead, push the
5484                                                                         // monitor update as a background event.
5485                                                                         self.pending_background_events.lock().unwrap().push(
5486                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5487                                                                                         counterparty_node_id,
5488                                                                                         funding_txo: prev_hop.outpoint,
5489                                                                                         update: monitor_update.clone(),
5490                                                                                 });
5491                                                                 }
5492                                                         }
5493                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5494                                                                 let action = if let Some(action) = completion_action(None, true) {
5495                                                                         action
5496                                                                 } else {
5497                                                                         return Ok(());
5498                                                                 };
5499                                                                 mem::drop(peer_state_lock);
5500
5501                                                                 log_trace!(logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5502                                                                         chan_id, action);
5503                                                                 let (node_id, funding_outpoint, blocker) =
5504                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5505                                                                         downstream_counterparty_node_id: node_id,
5506                                                                         downstream_funding_outpoint: funding_outpoint,
5507                                                                         blocking_action: blocker,
5508                                                                 } = action {
5509                                                                         (node_id, funding_outpoint, blocker)
5510                                                                 } else {
5511                                                                         debug_assert!(false,
5512                                                                                 "Duplicate claims should always free another channel immediately");
5513                                                                         return Ok(());
5514                                                                 };
5515                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5516                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5517                                                                         if let Some(blockers) = peer_state
5518                                                                                 .actions_blocking_raa_monitor_updates
5519                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5520                                                                         {
5521                                                                                 let mut found_blocker = false;
5522                                                                                 blockers.retain(|iter| {
5523                                                                                         // Note that we could actually be blocked, in
5524                                                                                         // which case we need to only remove the one
5525                                                                                         // blocker which was added duplicatively.
5526                                                                                         let first_blocker = !found_blocker;
5527                                                                                         if *iter == blocker { found_blocker = true; }
5528                                                                                         *iter != blocker || !first_blocker
5529                                                                                 });
5530                                                                                 debug_assert!(found_blocker);
5531                                                                         }
5532                                                                 } else {
5533                                                                         debug_assert!(false);
5534                                                                 }
5535                                                         }
5536                                                 }
5537                                         }
5538                                         return Ok(());
5539                                 }
5540                         }
5541                 }
5542                 let preimage_update = ChannelMonitorUpdate {
5543                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5544                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5545                                 payment_preimage,
5546                         }],
5547                 };
5548
5549                 if !during_init {
5550                         // We update the ChannelMonitor on the backward link, after
5551                         // receiving an `update_fulfill_htlc` from the forward link.
5552                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5553                         if update_res != ChannelMonitorUpdateStatus::Completed {
5554                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5555                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5556                                 // channel, or we must have an ability to receive the same event and try
5557                                 // again on restart.
5558                                 log_error!(WithContext::from(&self.logger, None, Some(prev_hop.outpoint.to_channel_id())), "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5559                                         payment_preimage, update_res);
5560                         }
5561                 } else {
5562                         // If we're running during init we cannot update a monitor directly - they probably
5563                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5564                         // event.
5565                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5566                         // channel is already closed) we need to ultimately handle the monitor update
5567                         // completion action only after we've completed the monitor update. This is the only
5568                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5569                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5570                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5571                         // complete the monitor update completion action from `completion_action`.
5572                         self.pending_background_events.lock().unwrap().push(
5573                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5574                                         prev_hop.outpoint, preimage_update,
5575                                 )));
5576                 }
5577                 // Note that we do process the completion action here. This totally could be a
5578                 // duplicate claim, but we have no way of knowing without interrogating the
5579                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5580                 // generally always allowed to be duplicative (and it's specifically noted in
5581                 // `PaymentForwarded`).
5582                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5583                 Ok(())
5584         }
5585
5586         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5587                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5588         }
5589
5590         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5591                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5592                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5593         ) {
5594                 match source {
5595                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5596                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5597                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5598                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5599                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5600                                 }
5601                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5602                                         channel_funding_outpoint: next_channel_outpoint,
5603                                         counterparty_node_id: path.hops[0].pubkey,
5604                                 };
5605                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5606                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5607                                         &self.logger);
5608                         },
5609                         HTLCSource::PreviousHopData(hop_data) => {
5610                                 let prev_outpoint = hop_data.outpoint;
5611                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5612                                 #[cfg(debug_assertions)]
5613                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5614                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5615                                         |htlc_claim_value_msat, definitely_duplicate| {
5616                                                 let chan_to_release =
5617                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5618                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5619                                                         } else {
5620                                                                 // We can only get `None` here if we are processing a
5621                                                                 // `ChannelMonitor`-originated event, in which case we
5622                                                                 // don't care about ensuring we wake the downstream
5623                                                                 // channel's monitor updating - the channel is already
5624                                                                 // closed.
5625                                                                 None
5626                                                         };
5627
5628                                                 if definitely_duplicate && startup_replay {
5629                                                         // On startup we may get redundant claims which are related to
5630                                                         // monitor updates still in flight. In that case, we shouldn't
5631                                                         // immediately free, but instead let that monitor update complete
5632                                                         // in the background.
5633                                                         #[cfg(debug_assertions)] {
5634                                                                 let background_events = self.pending_background_events.lock().unwrap();
5635                                                                 // There should be a `BackgroundEvent` pending...
5636                                                                 assert!(background_events.iter().any(|ev| {
5637                                                                         match ev {
5638                                                                                 // to apply a monitor update that blocked the claiming channel,
5639                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5640                                                                                         funding_txo, update, ..
5641                                                                                 } => {
5642                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5643                                                                                                 assert!(update.updates.iter().any(|upd|
5644                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5645                                                                                                                 payment_preimage: update_preimage
5646                                                                                                         } = upd {
5647                                                                                                                 payment_preimage == *update_preimage
5648                                                                                                         } else { false }
5649                                                                                                 ), "{:?}", update);
5650                                                                                                 true
5651                                                                                         } else { false }
5652                                                                                 },
5653                                                                                 // or the channel we'd unblock is already closed,
5654                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5655                                                                                         (funding_txo, monitor_update)
5656                                                                                 ) => {
5657                                                                                         if *funding_txo == next_channel_outpoint {
5658                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5659                                                                                                 assert!(matches!(
5660                                                                                                         monitor_update.updates[0],
5661                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5662                                                                                                 ));
5663                                                                                                 true
5664                                                                                         } else { false }
5665                                                                                 },
5666                                                                                 // or the monitor update has completed and will unblock
5667                                                                                 // immediately once we get going.
5668                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5669                                                                                         channel_id, ..
5670                                                                                 } =>
5671                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5672                                                                         }
5673                                                                 }), "{:?}", *background_events);
5674                                                         }
5675                                                         None
5676                                                 } else if definitely_duplicate {
5677                                                         if let Some(other_chan) = chan_to_release {
5678                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5679                                                                         downstream_counterparty_node_id: other_chan.0,
5680                                                                         downstream_funding_outpoint: other_chan.1,
5681                                                                         blocking_action: other_chan.2,
5682                                                                 })
5683                                                         } else { None }
5684                                                 } else {
5685                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5686                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5687                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5688                                                                 } else { None }
5689                                                         } else { None };
5690                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5691                                                                 event: events::Event::PaymentForwarded {
5692                                                                         fee_earned_msat,
5693                                                                         claim_from_onchain_tx: from_onchain,
5694                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5695                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5696                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5697                                                                 },
5698                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5699                                                         })
5700                                                 }
5701                                         });
5702                                 if let Err((pk, err)) = res {
5703                                         let result: Result<(), _> = Err(err);
5704                                         let _ = handle_error!(self, result, pk);
5705                                 }
5706                         },
5707                 }
5708         }
5709
5710         /// Gets the node_id held by this ChannelManager
5711         pub fn get_our_node_id(&self) -> PublicKey {
5712                 self.our_network_pubkey.clone()
5713         }
5714
5715         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5716                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5717                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5718                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5719
5720                 for action in actions.into_iter() {
5721                         match action {
5722                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5723                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5724                                         if let Some(ClaimingPayment {
5725                                                 amount_msat,
5726                                                 payment_purpose: purpose,
5727                                                 receiver_node_id,
5728                                                 htlcs,
5729                                                 sender_intended_value: sender_intended_total_msat,
5730                                         }) = payment {
5731                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5732                                                         payment_hash,
5733                                                         purpose,
5734                                                         amount_msat,
5735                                                         receiver_node_id: Some(receiver_node_id),
5736                                                         htlcs,
5737                                                         sender_intended_total_msat,
5738                                                 }, None));
5739                                         }
5740                                 },
5741                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5742                                         event, downstream_counterparty_and_funding_outpoint
5743                                 } => {
5744                                         self.pending_events.lock().unwrap().push_back((event, None));
5745                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5746                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5747                                         }
5748                                 },
5749                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5750                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5751                                 } => {
5752                                         self.handle_monitor_update_release(
5753                                                 downstream_counterparty_node_id,
5754                                                 downstream_funding_outpoint,
5755                                                 Some(blocking_action),
5756                                         );
5757                                 },
5758                         }
5759                 }
5760         }
5761
5762         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5763         /// update completion.
5764         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5765                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5766                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5767                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5768                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5769         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5770                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5771                 log_trace!(logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5772                         &channel.context.channel_id(),
5773                         if raa.is_some() { "an" } else { "no" },
5774                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5775                         if funding_broadcastable.is_some() { "" } else { "not " },
5776                         if channel_ready.is_some() { "sending" } else { "without" },
5777                         if announcement_sigs.is_some() { "sending" } else { "without" });
5778
5779                 let mut htlc_forwards = None;
5780
5781                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5782                 if !pending_forwards.is_empty() {
5783                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5784                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5785                 }
5786
5787                 if let Some(msg) = channel_ready {
5788                         send_channel_ready!(self, pending_msg_events, channel, msg);
5789                 }
5790                 if let Some(msg) = announcement_sigs {
5791                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5792                                 node_id: counterparty_node_id,
5793                                 msg,
5794                         });
5795                 }
5796
5797                 macro_rules! handle_cs { () => {
5798                         if let Some(update) = commitment_update {
5799                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5800                                         node_id: counterparty_node_id,
5801                                         updates: update,
5802                                 });
5803                         }
5804                 } }
5805                 macro_rules! handle_raa { () => {
5806                         if let Some(revoke_and_ack) = raa {
5807                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5808                                         node_id: counterparty_node_id,
5809                                         msg: revoke_and_ack,
5810                                 });
5811                         }
5812                 } }
5813                 match order {
5814                         RAACommitmentOrder::CommitmentFirst => {
5815                                 handle_cs!();
5816                                 handle_raa!();
5817                         },
5818                         RAACommitmentOrder::RevokeAndACKFirst => {
5819                                 handle_raa!();
5820                                 handle_cs!();
5821                         },
5822                 }
5823
5824                 if let Some(tx) = funding_broadcastable {
5825                         log_info!(logger, "Broadcasting funding transaction with txid {}", tx.txid());
5826                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5827                 }
5828
5829                 {
5830                         let mut pending_events = self.pending_events.lock().unwrap();
5831                         emit_channel_pending_event!(pending_events, channel);
5832                         emit_channel_ready_event!(pending_events, channel);
5833                 }
5834
5835                 htlc_forwards
5836         }
5837
5838         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5839                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5840
5841                 let counterparty_node_id = match counterparty_node_id {
5842                         Some(cp_id) => cp_id.clone(),
5843                         None => {
5844                                 // TODO: Once we can rely on the counterparty_node_id from the
5845                                 // monitor event, this and the id_to_peer map should be removed.
5846                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5847                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5848                                         Some(cp_id) => cp_id.clone(),
5849                                         None => return,
5850                                 }
5851                         }
5852                 };
5853                 let per_peer_state = self.per_peer_state.read().unwrap();
5854                 let mut peer_state_lock;
5855                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5856                 if peer_state_mutex_opt.is_none() { return }
5857                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5858                 let peer_state = &mut *peer_state_lock;
5859                 let channel =
5860                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5861                                 chan
5862                         } else {
5863                                 let update_actions = peer_state.monitor_update_blocked_actions
5864                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5865                                 mem::drop(peer_state_lock);
5866                                 mem::drop(per_peer_state);
5867                                 self.handle_monitor_update_completion_actions(update_actions);
5868                                 return;
5869                         };
5870                 let remaining_in_flight =
5871                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5872                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5873                                 pending.len()
5874                         } else { 0 };
5875                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5876                 log_trace!(logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5877                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5878                         remaining_in_flight);
5879                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5880                         return;
5881                 }
5882                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5883         }
5884
5885         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5886         ///
5887         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5888         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5889         /// the channel.
5890         ///
5891         /// The `user_channel_id` parameter will be provided back in
5892         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5893         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5894         ///
5895         /// Note that this method will return an error and reject the channel, if it requires support
5896         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5897         /// used to accept such channels.
5898         ///
5899         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5900         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5901         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5902                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5903         }
5904
5905         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5906         /// it as confirmed immediately.
5907         ///
5908         /// The `user_channel_id` parameter will be provided back in
5909         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5910         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5911         ///
5912         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5913         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5914         ///
5915         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5916         /// transaction and blindly assumes that it will eventually confirm.
5917         ///
5918         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5919         /// does not pay to the correct script the correct amount, *you will lose funds*.
5920         ///
5921         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5922         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5923         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5924                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5925         }
5926
5927         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5928                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5929
5930                 let peers_without_funded_channels =
5931                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5932                 let per_peer_state = self.per_peer_state.read().unwrap();
5933                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5934                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5935                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5936                 let peer_state = &mut *peer_state_lock;
5937                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5938
5939                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5940                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5941                 // that we can delay allocating the SCID until after we're sure that the checks below will
5942                 // succeed.
5943                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5944                         Some(unaccepted_channel) => {
5945                                 let best_block_height = self.best_block.read().unwrap().height();
5946                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5947                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5948                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5949                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5950                         }
5951                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5952                 }?;
5953
5954                 if accept_0conf {
5955                         // This should have been correctly configured by the call to InboundV1Channel::new.
5956                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5957                 } else if channel.context.get_channel_type().requires_zero_conf() {
5958                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5959                                 node_id: channel.context.get_counterparty_node_id(),
5960                                 action: msgs::ErrorAction::SendErrorMessage{
5961                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5962                                 }
5963                         };
5964                         peer_state.pending_msg_events.push(send_msg_err_event);
5965                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5966                 } else {
5967                         // If this peer already has some channels, a new channel won't increase our number of peers
5968                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5969                         // channels per-peer we can accept channels from a peer with existing ones.
5970                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5971                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5972                                         node_id: channel.context.get_counterparty_node_id(),
5973                                         action: msgs::ErrorAction::SendErrorMessage{
5974                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5975                                         }
5976                                 };
5977                                 peer_state.pending_msg_events.push(send_msg_err_event);
5978                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5979                         }
5980                 }
5981
5982                 // Now that we know we have a channel, assign an outbound SCID alias.
5983                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5984                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5985
5986                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5987                         node_id: channel.context.get_counterparty_node_id(),
5988                         msg: channel.accept_inbound_channel(),
5989                 });
5990
5991                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
5992
5993                 Ok(())
5994         }
5995
5996         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5997         /// or 0-conf channels.
5998         ///
5999         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6000         /// non-0-conf channels we have with the peer.
6001         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6002         where Filter: Fn(&PeerState<SP>) -> bool {
6003                 let mut peers_without_funded_channels = 0;
6004                 let best_block_height = self.best_block.read().unwrap().height();
6005                 {
6006                         let peer_state_lock = self.per_peer_state.read().unwrap();
6007                         for (_, peer_mtx) in peer_state_lock.iter() {
6008                                 let peer = peer_mtx.lock().unwrap();
6009                                 if !maybe_count_peer(&*peer) { continue; }
6010                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6011                                 if num_unfunded_channels == peer.total_channel_count() {
6012                                         peers_without_funded_channels += 1;
6013                                 }
6014                         }
6015                 }
6016                 return peers_without_funded_channels;
6017         }
6018
6019         fn unfunded_channel_count(
6020                 peer: &PeerState<SP>, best_block_height: u32
6021         ) -> usize {
6022                 let mut num_unfunded_channels = 0;
6023                 for (_, phase) in peer.channel_by_id.iter() {
6024                         match phase {
6025                                 ChannelPhase::Funded(chan) => {
6026                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6027                                         // which have not yet had any confirmations on-chain.
6028                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6029                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6030                                         {
6031                                                 num_unfunded_channels += 1;
6032                                         }
6033                                 },
6034                                 ChannelPhase::UnfundedInboundV1(chan) => {
6035                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6036                                                 num_unfunded_channels += 1;
6037                                         }
6038                                 },
6039                                 ChannelPhase::UnfundedOutboundV1(_) => {
6040                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6041                                         continue;
6042                                 }
6043                         }
6044                 }
6045                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6046         }
6047
6048         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6049                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6050                 // likely to be lost on restart!
6051                 if msg.chain_hash != self.chain_hash {
6052                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
6053                 }
6054
6055                 if !self.default_configuration.accept_inbound_channels {
6056                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6057                 }
6058
6059                 // Get the number of peers with channels, but without funded ones. We don't care too much
6060                 // about peers that never open a channel, so we filter by peers that have at least one
6061                 // channel, and then limit the number of those with unfunded channels.
6062                 let channeled_peers_without_funding =
6063                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6064
6065                 let per_peer_state = self.per_peer_state.read().unwrap();
6066                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6067                     .ok_or_else(|| {
6068                                 debug_assert!(false);
6069                                 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())
6070                         })?;
6071                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6072                 let peer_state = &mut *peer_state_lock;
6073
6074                 // If this peer already has some channels, a new channel won't increase our number of peers
6075                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6076                 // channels per-peer we can accept channels from a peer with existing ones.
6077                 if peer_state.total_channel_count() == 0 &&
6078                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6079                         !self.default_configuration.manually_accept_inbound_channels
6080                 {
6081                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6082                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6083                                 msg.temporary_channel_id.clone()));
6084                 }
6085
6086                 let best_block_height = self.best_block.read().unwrap().height();
6087                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6088                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6089                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6090                                 msg.temporary_channel_id.clone()));
6091                 }
6092
6093                 let channel_id = msg.temporary_channel_id;
6094                 let channel_exists = peer_state.has_channel(&channel_id);
6095                 if channel_exists {
6096                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
6097                 }
6098
6099                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6100                 if self.default_configuration.manually_accept_inbound_channels {
6101                         let mut pending_events = self.pending_events.lock().unwrap();
6102                         pending_events.push_back((events::Event::OpenChannelRequest {
6103                                 temporary_channel_id: msg.temporary_channel_id.clone(),
6104                                 counterparty_node_id: counterparty_node_id.clone(),
6105                                 funding_satoshis: msg.funding_satoshis,
6106                                 push_msat: msg.push_msat,
6107                                 channel_type: msg.channel_type.clone().unwrap(),
6108                         }, None));
6109                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6110                                 open_channel_msg: msg.clone(),
6111                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6112                         });
6113                         return Ok(());
6114                 }
6115
6116                 // Otherwise create the channel right now.
6117                 let mut random_bytes = [0u8; 16];
6118                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6119                 let user_channel_id = u128::from_be_bytes(random_bytes);
6120                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6121                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6122                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6123                 {
6124                         Err(e) => {
6125                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
6126                         },
6127                         Ok(res) => res
6128                 };
6129
6130                 let channel_type = channel.context.get_channel_type();
6131                 if channel_type.requires_zero_conf() {
6132                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6133                 }
6134                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6135                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
6136                 }
6137
6138                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6139                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6140
6141                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6142                         node_id: counterparty_node_id.clone(),
6143                         msg: channel.accept_inbound_channel(),
6144                 });
6145                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6146                 Ok(())
6147         }
6148
6149         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6150                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6151                 // likely to be lost on restart!
6152                 let (value, output_script, user_id) = {
6153                         let per_peer_state = self.per_peer_state.read().unwrap();
6154                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6155                                 .ok_or_else(|| {
6156                                         debug_assert!(false);
6157                                         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)
6158                                 })?;
6159                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6160                         let peer_state = &mut *peer_state_lock;
6161                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6162                                 hash_map::Entry::Occupied(mut phase) => {
6163                                         match phase.get_mut() {
6164                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6165                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6166                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6167                                                 },
6168                                                 _ => {
6169                                                         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));
6170                                                 }
6171                                         }
6172                                 },
6173                                 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))
6174                         }
6175                 };
6176                 let mut pending_events = self.pending_events.lock().unwrap();
6177                 pending_events.push_back((events::Event::FundingGenerationReady {
6178                         temporary_channel_id: msg.temporary_channel_id,
6179                         counterparty_node_id: *counterparty_node_id,
6180                         channel_value_satoshis: value,
6181                         output_script,
6182                         user_channel_id: user_id,
6183                 }, None));
6184                 Ok(())
6185         }
6186
6187         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6188                 let best_block = *self.best_block.read().unwrap();
6189
6190                 let per_peer_state = self.per_peer_state.read().unwrap();
6191                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6192                         .ok_or_else(|| {
6193                                 debug_assert!(false);
6194                                 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)
6195                         })?;
6196
6197                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6198                 let peer_state = &mut *peer_state_lock;
6199                 let (chan, funding_msg_opt, monitor) =
6200                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6201                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6202                                         let logger = WithChannelContext::from(&self.logger, &inbound_chan.context);
6203                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &&logger) {
6204                                                 Ok(res) => res,
6205                                                 Err((mut inbound_chan, err)) => {
6206                                                         // We've already removed this inbound channel from the map in `PeerState`
6207                                                         // above so at this point we just need to clean up any lingering entries
6208                                                         // concerning this channel as it is safe to do so.
6209                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
6210                                                         let user_id = inbound_chan.context.get_user_id();
6211                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
6212                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
6213                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
6214                                                 },
6215                                         }
6216                                 },
6217                                 Some(ChannelPhase::Funded(_)) | Some(ChannelPhase::UnfundedOutboundV1(_)) => {
6218                                         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));
6219                                 },
6220                                 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))
6221                         };
6222
6223                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
6224                         hash_map::Entry::Occupied(_) => {
6225                                 Err(MsgHandleErrInternal::send_err_msg_no_close(
6226                                         "Already had channel with the new channel_id".to_owned(),
6227                                         chan.context.channel_id()
6228                                 ))
6229                         },
6230                         hash_map::Entry::Vacant(e) => {
6231                                 let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
6232                                 match id_to_peer_lock.entry(chan.context.channel_id()) {
6233                                         hash_map::Entry::Occupied(_) => {
6234                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
6235                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6236                                                         chan.context.channel_id()))
6237                                         },
6238                                         hash_map::Entry::Vacant(i_e) => {
6239                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6240                                                 if let Ok(persist_state) = monitor_res {
6241                                                         i_e.insert(chan.context.get_counterparty_node_id());
6242                                                         mem::drop(id_to_peer_lock);
6243
6244                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6245                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6246                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6247                                                         // until we have persisted our monitor.
6248                                                         if let Some(msg) = funding_msg_opt {
6249                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6250                                                                         node_id: counterparty_node_id.clone(),
6251                                                                         msg,
6252                                                                 });
6253                                                         }
6254
6255                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6256                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6257                                                                         per_peer_state, chan, INITIAL_MONITOR);
6258                                                         } else {
6259                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6260                                                         }
6261                                                         Ok(())
6262                                                 } else {
6263                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6264                                                         log_error!(logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6265                                                         let channel_id = match funding_msg_opt {
6266                                                                 Some(msg) => msg.channel_id,
6267                                                                 None => chan.context.channel_id(),
6268                                                         };
6269                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6270                                                                 "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6271                                                                 channel_id));
6272                                                 }
6273                                         }
6274                                 }
6275                         }
6276                 }
6277         }
6278
6279         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6280                 let best_block = *self.best_block.read().unwrap();
6281                 let per_peer_state = self.per_peer_state.read().unwrap();
6282                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6283                         .ok_or_else(|| {
6284                                 debug_assert!(false);
6285                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6286                         })?;
6287
6288                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6289                 let peer_state = &mut *peer_state_lock;
6290                 match peer_state.channel_by_id.entry(msg.channel_id) {
6291                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6292                                 match chan_phase_entry.get_mut() {
6293                                         ChannelPhase::Funded(ref mut chan) => {
6294                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
6295                                                 let monitor = try_chan_phase_entry!(self,
6296                                                         chan.funding_signed(&msg, best_block, &self.signer_provider, &&logger), chan_phase_entry);
6297                                                 if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6298                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6299                                                         Ok(())
6300                                                 } else {
6301                                                         try_chan_phase_entry!(self, Err(ChannelError::Close("Channel funding outpoint was a duplicate".to_owned())), chan_phase_entry)
6302                                                 }
6303                                         },
6304                                         _ => {
6305                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6306                                         },
6307                                 }
6308                         },
6309                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6310                 }
6311         }
6312
6313         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6314                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6315                 // closing a channel), so any changes are likely to be lost on restart!
6316                 let per_peer_state = self.per_peer_state.read().unwrap();
6317                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6318                         .ok_or_else(|| {
6319                                 debug_assert!(false);
6320                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6321                         })?;
6322                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6323                 let peer_state = &mut *peer_state_lock;
6324                 match peer_state.channel_by_id.entry(msg.channel_id) {
6325                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6326                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6327                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6328                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6329                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &&logger), chan_phase_entry);
6330                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6331                                                 log_trace!(logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6332                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6333                                                         node_id: counterparty_node_id.clone(),
6334                                                         msg: announcement_sigs,
6335                                                 });
6336                                         } else if chan.context.is_usable() {
6337                                                 // If we're sending an announcement_signatures, we'll send the (public)
6338                                                 // channel_update after sending a channel_announcement when we receive our
6339                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6340                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6341                                                 // announcement_signatures.
6342                                                 log_trace!(logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6343                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6344                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6345                                                                 node_id: counterparty_node_id.clone(),
6346                                                                 msg,
6347                                                         });
6348                                                 }
6349                                         }
6350
6351                                         {
6352                                                 let mut pending_events = self.pending_events.lock().unwrap();
6353                                                 emit_channel_ready_event!(pending_events, chan);
6354                                         }
6355
6356                                         Ok(())
6357                                 } else {
6358                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6359                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6360                                 }
6361                         },
6362                         hash_map::Entry::Vacant(_) => {
6363                                 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))
6364                         }
6365                 }
6366         }
6367
6368         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6369                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6370                 let mut finish_shutdown = None;
6371                 {
6372                         let per_peer_state = self.per_peer_state.read().unwrap();
6373                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6374                                 .ok_or_else(|| {
6375                                         debug_assert!(false);
6376                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6377                                 })?;
6378                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6379                         let peer_state = &mut *peer_state_lock;
6380                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6381                                 let phase = chan_phase_entry.get_mut();
6382                                 match phase {
6383                                         ChannelPhase::Funded(chan) => {
6384                                                 if !chan.received_shutdown() {
6385                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6386                                                         log_info!(logger, "Received a shutdown message from our counterparty for channel {}{}.",
6387                                                                 msg.channel_id,
6388                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6389                                                 }
6390
6391                                                 let funding_txo_opt = chan.context.get_funding_txo();
6392                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6393                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6394                                                 dropped_htlcs = htlcs;
6395
6396                                                 if let Some(msg) = shutdown {
6397                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6398                                                         // here as we don't need the monitor update to complete until we send a
6399                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6400                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6401                                                                 node_id: *counterparty_node_id,
6402                                                                 msg,
6403                                                         });
6404                                                 }
6405                                                 // Update the monitor with the shutdown script if necessary.
6406                                                 if let Some(monitor_update) = monitor_update_opt {
6407                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6408                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6409                                                 }
6410                                         },
6411                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6412                                                 let context = phase.context_mut();
6413                                                 let logger = WithChannelContext::from(&self.logger, context);
6414                                                 log_error!(logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6415                                                 self.issue_channel_close_events(&context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
6416                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6417                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false));
6418                                         },
6419                                 }
6420                         } else {
6421                                 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))
6422                         }
6423                 }
6424                 for htlc_source in dropped_htlcs.drain(..) {
6425                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6426                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6427                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6428                 }
6429                 if let Some(shutdown_res) = finish_shutdown {
6430                         self.finish_close_channel(shutdown_res);
6431                 }
6432
6433                 Ok(())
6434         }
6435
6436         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6437                 let per_peer_state = self.per_peer_state.read().unwrap();
6438                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6439                         .ok_or_else(|| {
6440                                 debug_assert!(false);
6441                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6442                         })?;
6443                 let (tx, chan_option, shutdown_result) = {
6444                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6445                         let peer_state = &mut *peer_state_lock;
6446                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6447                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6448                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6449                                                 let (closing_signed, tx, shutdown_result) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6450                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
6451                                                 if let Some(msg) = closing_signed {
6452                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6453                                                                 node_id: counterparty_node_id.clone(),
6454                                                                 msg,
6455                                                         });
6456                                                 }
6457                                                 if tx.is_some() {
6458                                                         // We're done with this channel, we've got a signed closing transaction and
6459                                                         // will send the closing_signed back to the remote peer upon return. This
6460                                                         // also implies there are no pending HTLCs left on the channel, so we can
6461                                                         // fully delete it from tracking (the channel monitor is still around to
6462                                                         // watch for old state broadcasts)!
6463                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)), shutdown_result)
6464                                                 } else { (tx, None, shutdown_result) }
6465                                         } else {
6466                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6467                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6468                                         }
6469                                 },
6470                                 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))
6471                         }
6472                 };
6473                 if let Some(broadcast_tx) = tx {
6474                         let channel_id = chan_option.as_ref().map(|channel| channel.context().channel_id());
6475                         log_info!(WithContext::from(&self.logger, Some(*counterparty_node_id), channel_id), "Broadcasting {}", log_tx!(broadcast_tx));
6476                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6477                 }
6478                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6479                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6480                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6481                                 let peer_state = &mut *peer_state_lock;
6482                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6483                                         msg: update
6484                                 });
6485                         }
6486                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6487                 }
6488                 mem::drop(per_peer_state);
6489                 if let Some(shutdown_result) = shutdown_result {
6490                         self.finish_close_channel(shutdown_result);
6491                 }
6492                 Ok(())
6493         }
6494
6495         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6496                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6497                 //determine the state of the payment based on our response/if we forward anything/the time
6498                 //we take to respond. We should take care to avoid allowing such an attack.
6499                 //
6500                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6501                 //us repeatedly garbled in different ways, and compare our error messages, which are
6502                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6503                 //but we should prevent it anyway.
6504
6505                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6506                 // closing a channel), so any changes are likely to be lost on restart!
6507
6508                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg, counterparty_node_id);
6509                 let per_peer_state = self.per_peer_state.read().unwrap();
6510                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6511                         .ok_or_else(|| {
6512                                 debug_assert!(false);
6513                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6514                         })?;
6515                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6516                 let peer_state = &mut *peer_state_lock;
6517                 match peer_state.channel_by_id.entry(msg.channel_id) {
6518                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6519                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6520                                         let pending_forward_info = match decoded_hop_res {
6521                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6522                                                         self.construct_pending_htlc_status(
6523                                                                 msg, counterparty_node_id, shared_secret, next_hop,
6524                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt,
6525                                                         ),
6526                                                 Err(e) => PendingHTLCStatus::Fail(e)
6527                                         };
6528                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6529                                                 // If the update_add is completely bogus, the call will Err and we will close,
6530                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6531                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6532                                                 match pending_forward_info {
6533                                                         PendingHTLCStatus::Forward(PendingHTLCInfo {
6534                                                                 ref incoming_shared_secret, ref routing, ..
6535                                                         }) => {
6536                                                                 let reason = if routing.blinded_failure().is_some() {
6537                                                                         HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32])
6538                                                                 } else if (error_code & 0x1000) != 0 {
6539                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6540                                                                         HTLCFailReason::reason(real_code, error_data)
6541                                                                 } else {
6542                                                                         HTLCFailReason::from_failure_code(error_code)
6543                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6544                                                                 let msg = msgs::UpdateFailHTLC {
6545                                                                         channel_id: msg.channel_id,
6546                                                                         htlc_id: msg.htlc_id,
6547                                                                         reason
6548                                                                 };
6549                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6550                                                         },
6551                                                         _ => pending_forward_info
6552                                                 }
6553                                         };
6554                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6555                                         try_chan_phase_entry!(self, chan.update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &&logger), chan_phase_entry);
6556                                 } else {
6557                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6558                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6559                                 }
6560                         },
6561                         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))
6562                 }
6563                 Ok(())
6564         }
6565
6566         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6567                 let funding_txo;
6568                 let (htlc_source, forwarded_htlc_value) = {
6569                         let per_peer_state = self.per_peer_state.read().unwrap();
6570                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6571                                 .ok_or_else(|| {
6572                                         debug_assert!(false);
6573                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6574                                 })?;
6575                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6576                         let peer_state = &mut *peer_state_lock;
6577                         match peer_state.channel_by_id.entry(msg.channel_id) {
6578                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6579                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6580                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6581                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6582                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6583                                                         log_trace!(logger,
6584                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6585                                                                 msg.channel_id);
6586                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6587                                                                 .or_insert_with(Vec::new)
6588                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6589                                                 }
6590                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6591                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6592                                                 // We do this instead in the `claim_funds_internal` by attaching a
6593                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6594                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6595                                                 // process the RAA as messages are processed from single peers serially.
6596                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6597                                                 res
6598                                         } else {
6599                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6600                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6601                                         }
6602                                 },
6603                                 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))
6604                         }
6605                 };
6606                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6607                 Ok(())
6608         }
6609
6610         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6611                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6612                 // closing a channel), so any changes are likely to be lost on restart!
6613                 let per_peer_state = self.per_peer_state.read().unwrap();
6614                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6615                         .ok_or_else(|| {
6616                                 debug_assert!(false);
6617                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6618                         })?;
6619                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6620                 let peer_state = &mut *peer_state_lock;
6621                 match peer_state.channel_by_id.entry(msg.channel_id) {
6622                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6623                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6624                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6625                                 } else {
6626                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6627                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6628                                 }
6629                         },
6630                         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))
6631                 }
6632                 Ok(())
6633         }
6634
6635         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6636                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6637                 // closing a channel), so any changes are likely to be lost on restart!
6638                 let per_peer_state = self.per_peer_state.read().unwrap();
6639                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6640                         .ok_or_else(|| {
6641                                 debug_assert!(false);
6642                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6643                         })?;
6644                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6645                 let peer_state = &mut *peer_state_lock;
6646                 match peer_state.channel_by_id.entry(msg.channel_id) {
6647                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6648                                 if (msg.failure_code & 0x8000) == 0 {
6649                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6650                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6651                                 }
6652                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6653                                         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);
6654                                 } else {
6655                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6656                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6657                                 }
6658                                 Ok(())
6659                         },
6660                         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))
6661                 }
6662         }
6663
6664         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6665                 let per_peer_state = self.per_peer_state.read().unwrap();
6666                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6667                         .ok_or_else(|| {
6668                                 debug_assert!(false);
6669                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6670                         })?;
6671                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6672                 let peer_state = &mut *peer_state_lock;
6673                 match peer_state.channel_by_id.entry(msg.channel_id) {
6674                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6675                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6676                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6677                                         let funding_txo = chan.context.get_funding_txo();
6678                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &&logger), chan_phase_entry);
6679                                         if let Some(monitor_update) = monitor_update_opt {
6680                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6681                                                         peer_state, per_peer_state, chan);
6682                                         }
6683                                         Ok(())
6684                                 } else {
6685                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6686                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6687                                 }
6688                         },
6689                         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))
6690                 }
6691         }
6692
6693         #[inline]
6694         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6695                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6696                         let mut push_forward_event = false;
6697                         let mut new_intercept_events = VecDeque::new();
6698                         let mut failed_intercept_forwards = Vec::new();
6699                         if !pending_forwards.is_empty() {
6700                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6701                                         let scid = match forward_info.routing {
6702                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6703                                                 PendingHTLCRouting::Receive { .. } => 0,
6704                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6705                                         };
6706                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6707                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6708
6709                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6710                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6711                                         match forward_htlcs.entry(scid) {
6712                                                 hash_map::Entry::Occupied(mut entry) => {
6713                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6714                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6715                                                 },
6716                                                 hash_map::Entry::Vacant(entry) => {
6717                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6718                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6719                                                         {
6720                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).to_byte_array());
6721                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6722                                                                 match pending_intercepts.entry(intercept_id) {
6723                                                                         hash_map::Entry::Vacant(entry) => {
6724                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6725                                                                                         requested_next_hop_scid: scid,
6726                                                                                         payment_hash: forward_info.payment_hash,
6727                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6728                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6729                                                                                         intercept_id
6730                                                                                 }, None));
6731                                                                                 entry.insert(PendingAddHTLCInfo {
6732                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6733                                                                         },
6734                                                                         hash_map::Entry::Occupied(_) => {
6735                                                                                 let logger = WithContext::from(&self.logger, None, Some(prev_funding_outpoint.to_channel_id()));
6736                                                                                 log_info!(logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6737                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6738                                                                                         short_channel_id: prev_short_channel_id,
6739                                                                                         user_channel_id: Some(prev_user_channel_id),
6740                                                                                         outpoint: prev_funding_outpoint,
6741                                                                                         htlc_id: prev_htlc_id,
6742                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6743                                                                                         phantom_shared_secret: None,
6744                                                                                         blinded_failure: forward_info.routing.blinded_failure(),
6745                                                                                 });
6746
6747                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6748                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6749                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6750                                                                                 ));
6751                                                                         }
6752                                                                 }
6753                                                         } else {
6754                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6755                                                                 // payments are being processed.
6756                                                                 if forward_htlcs_empty {
6757                                                                         push_forward_event = true;
6758                                                                 }
6759                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6760                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6761                                                         }
6762                                                 }
6763                                         }
6764                                 }
6765                         }
6766
6767                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6768                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6769                         }
6770
6771                         if !new_intercept_events.is_empty() {
6772                                 let mut events = self.pending_events.lock().unwrap();
6773                                 events.append(&mut new_intercept_events);
6774                         }
6775                         if push_forward_event { self.push_pending_forwards_ev() }
6776                 }
6777         }
6778
6779         fn push_pending_forwards_ev(&self) {
6780                 let mut pending_events = self.pending_events.lock().unwrap();
6781                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6782                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6783                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6784                 ).count();
6785                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6786                 // events is done in batches and they are not removed until we're done processing each
6787                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6788                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6789                 // payments will need an additional forwarding event before being claimed to make them look
6790                 // real by taking more time.
6791                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6792                         pending_events.push_back((Event::PendingHTLCsForwardable {
6793                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6794                         }, None));
6795                 }
6796         }
6797
6798         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6799         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6800         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6801         /// the [`ChannelMonitorUpdate`] in question.
6802         fn raa_monitor_updates_held(&self,
6803                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6804                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6805         ) -> bool {
6806                 actions_blocking_raa_monitor_updates
6807                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6808                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6809                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6810                                 channel_funding_outpoint,
6811                                 counterparty_node_id,
6812                         })
6813                 })
6814         }
6815
6816         #[cfg(any(test, feature = "_test_utils"))]
6817         pub(crate) fn test_raa_monitor_updates_held(&self,
6818                 counterparty_node_id: PublicKey, channel_id: ChannelId
6819         ) -> bool {
6820                 let per_peer_state = self.per_peer_state.read().unwrap();
6821                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6822                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6823                         let peer_state = &mut *peer_state_lck;
6824
6825                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6826                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6827                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6828                         }
6829                 }
6830                 false
6831         }
6832
6833         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6834                 let htlcs_to_fail = {
6835                         let per_peer_state = self.per_peer_state.read().unwrap();
6836                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6837                                 .ok_or_else(|| {
6838                                         debug_assert!(false);
6839                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6840                                 }).map(|mtx| mtx.lock().unwrap())?;
6841                         let peer_state = &mut *peer_state_lock;
6842                         match peer_state.channel_by_id.entry(msg.channel_id) {
6843                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6844                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6845                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
6846                                                 let funding_txo_opt = chan.context.get_funding_txo();
6847                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6848                                                         self.raa_monitor_updates_held(
6849                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6850                                                                 *counterparty_node_id)
6851                                                 } else { false };
6852                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
6853                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &&logger, mon_update_blocked), chan_phase_entry);
6854                                                 if let Some(monitor_update) = monitor_update_opt {
6855                                                         let funding_txo = funding_txo_opt
6856                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
6857                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
6858                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6859                                                 }
6860                                                 htlcs_to_fail
6861                                         } else {
6862                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6863                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
6864                                         }
6865                                 },
6866                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6867                         }
6868                 };
6869                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6870                 Ok(())
6871         }
6872
6873         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6874                 let per_peer_state = self.per_peer_state.read().unwrap();
6875                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6876                         .ok_or_else(|| {
6877                                 debug_assert!(false);
6878                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6879                         })?;
6880                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6881                 let peer_state = &mut *peer_state_lock;
6882                 match peer_state.channel_by_id.entry(msg.channel_id) {
6883                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6884                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6885                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6886                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &&logger), chan_phase_entry);
6887                                 } else {
6888                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6889                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
6890                                 }
6891                         },
6892                         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))
6893                 }
6894                 Ok(())
6895         }
6896
6897         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6898                 let per_peer_state = self.per_peer_state.read().unwrap();
6899                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6900                         .ok_or_else(|| {
6901                                 debug_assert!(false);
6902                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6903                         })?;
6904                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6905                 let peer_state = &mut *peer_state_lock;
6906                 match peer_state.channel_by_id.entry(msg.channel_id) {
6907                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6908                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6909                                         if !chan.context.is_usable() {
6910                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6911                                         }
6912
6913                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6914                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6915                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
6916                                                         msg, &self.default_configuration
6917                                                 ), chan_phase_entry),
6918                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6919                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6920                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
6921                                         });
6922                                 } else {
6923                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6924                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
6925                                 }
6926                         },
6927                         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))
6928                 }
6929                 Ok(())
6930         }
6931
6932         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
6933         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6934                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6935                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6936                         None => {
6937                                 // It's not a local channel
6938                                 return Ok(NotifyOption::SkipPersistNoEvents)
6939                         }
6940                 };
6941                 let per_peer_state = self.per_peer_state.read().unwrap();
6942                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6943                 if peer_state_mutex_opt.is_none() {
6944                         return Ok(NotifyOption::SkipPersistNoEvents)
6945                 }
6946                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6947                 let peer_state = &mut *peer_state_lock;
6948                 match peer_state.channel_by_id.entry(chan_id) {
6949                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6950                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6951                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
6952                                                 if chan.context.should_announce() {
6953                                                         // If the announcement is about a channel of ours which is public, some
6954                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
6955                                                         // a scary-looking error message and return Ok instead.
6956                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6957                                                 }
6958                                                 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));
6959                                         }
6960                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
6961                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
6962                                         if were_node_one == msg_from_node_one {
6963                                                 return Ok(NotifyOption::SkipPersistNoEvents);
6964                                         } else {
6965                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
6966                                                 log_debug!(logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
6967                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
6968                                                 // If nothing changed after applying their update, we don't need to bother
6969                                                 // persisting.
6970                                                 if !did_change {
6971                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6972                                                 }
6973                                         }
6974                                 } else {
6975                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6976                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
6977                                 }
6978                         },
6979                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
6980                 }
6981                 Ok(NotifyOption::DoPersist)
6982         }
6983
6984         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
6985                 let htlc_forwards;
6986                 let need_lnd_workaround = {
6987                         let per_peer_state = self.per_peer_state.read().unwrap();
6988
6989                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6990                                 .ok_or_else(|| {
6991                                         debug_assert!(false);
6992                                         MsgHandleErrInternal::send_err_msg_no_close(
6993                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6994                                                 msg.channel_id
6995                                         )
6996                                 })?;
6997                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
6998                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6999                         let peer_state = &mut *peer_state_lock;
7000                         match peer_state.channel_by_id.entry(msg.channel_id) {
7001                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
7002                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7003                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
7004                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
7005                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
7006                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
7007                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
7008                                                         msg, &&logger, &self.node_signer, self.chain_hash,
7009                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
7010                                                 let mut channel_update = None;
7011                                                 if let Some(msg) = responses.shutdown_msg {
7012                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
7013                                                                 node_id: counterparty_node_id.clone(),
7014                                                                 msg,
7015                                                         });
7016                                                 } else if chan.context.is_usable() {
7017                                                         // If the channel is in a usable state (ie the channel is not being shut
7018                                                         // down), send a unicast channel_update to our counterparty to make sure
7019                                                         // they have the latest channel parameters.
7020                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
7021                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
7022                                                                         node_id: chan.context.get_counterparty_node_id(),
7023                                                                         msg,
7024                                                                 });
7025                                                         }
7026                                                 }
7027                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7028                                                 htlc_forwards = self.handle_channel_resumption(
7029                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7030                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7031                                                 if let Some(upd) = channel_update {
7032                                                         peer_state.pending_msg_events.push(upd);
7033                                                 }
7034                                                 need_lnd_workaround
7035                                         } else {
7036                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7037                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7038                                         }
7039                                 },
7040                                 hash_map::Entry::Vacant(_) => {
7041                                         log_debug!(logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7042                                                 log_bytes!(msg.channel_id.0));
7043                                         // Unfortunately, lnd doesn't force close on errors
7044                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7045                                         // One of the few ways to get an lnd counterparty to force close is by
7046                                         // replicating what they do when restoring static channel backups (SCBs). They
7047                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7048                                         // invalid `your_last_per_commitment_secret`.
7049                                         //
7050                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7051                                         // can assume it's likely the channel closed from our point of view, but it
7052                                         // remains open on the counterparty's side. By sending this bogus
7053                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7054                                         // force close broadcasting their latest state. If the closing transaction from
7055                                         // our point of view remains unconfirmed, it'll enter a race with the
7056                                         // counterparty's to-be-broadcast latest commitment transaction.
7057                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7058                                                 node_id: *counterparty_node_id,
7059                                                 msg: msgs::ChannelReestablish {
7060                                                         channel_id: msg.channel_id,
7061                                                         next_local_commitment_number: 0,
7062                                                         next_remote_commitment_number: 0,
7063                                                         your_last_per_commitment_secret: [1u8; 32],
7064                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7065                                                         next_funding_txid: None,
7066                                                 },
7067                                         });
7068                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7069                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7070                                                         counterparty_node_id), msg.channel_id)
7071                                         )
7072                                 }
7073                         }
7074                 };
7075
7076                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7077                 if let Some(forwards) = htlc_forwards {
7078                         self.forward_htlcs(&mut [forwards][..]);
7079                         persist = NotifyOption::DoPersist;
7080                 }
7081
7082                 if let Some(channel_ready_msg) = need_lnd_workaround {
7083                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7084                 }
7085                 Ok(persist)
7086         }
7087
7088         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7089         fn process_pending_monitor_events(&self) -> bool {
7090                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7091
7092                 let mut failed_channels = Vec::new();
7093                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7094                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7095                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7096                         for monitor_event in monitor_events.drain(..) {
7097                                 match monitor_event {
7098                                         MonitorEvent::HTLCEvent(htlc_update) => {
7099                                                 let logger = WithContext::from(&self.logger, counterparty_node_id, Some(funding_outpoint.to_channel_id()));
7100                                                 if let Some(preimage) = htlc_update.payment_preimage {
7101                                                         log_trace!(logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7102                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
7103                                                 } else {
7104                                                         log_trace!(logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7105                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
7106                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7107                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7108                                                 }
7109                                         },
7110                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
7111                                                 let counterparty_node_id_opt = match counterparty_node_id {
7112                                                         Some(cp_id) => Some(cp_id),
7113                                                         None => {
7114                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7115                                                                 // monitor event, this and the id_to_peer map should be removed.
7116                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
7117                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
7118                                                         }
7119                                                 };
7120                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7121                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7122                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7123                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7124                                                                 let peer_state = &mut *peer_state_lock;
7125                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7126                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
7127                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7128                                                                                 failed_channels.push(chan.context.force_shutdown(false));
7129                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7130                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7131                                                                                                 msg: update
7132                                                                                         });
7133                                                                                 }
7134                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
7135                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7136                                                                                         node_id: chan.context.get_counterparty_node_id(),
7137                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7138                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7139                                                                                         },
7140                                                                                 });
7141                                                                         }
7142                                                                 }
7143                                                         }
7144                                                 }
7145                                         },
7146                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
7147                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
7148                                         },
7149                                 }
7150                         }
7151                 }
7152
7153                 for failure in failed_channels.drain(..) {
7154                         self.finish_close_channel(failure);
7155                 }
7156
7157                 has_pending_monitor_events
7158         }
7159
7160         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7161         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7162         /// update events as a separate process method here.
7163         #[cfg(fuzzing)]
7164         pub fn process_monitor_events(&self) {
7165                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7166                 self.process_pending_monitor_events();
7167         }
7168
7169         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7170         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7171         /// update was applied.
7172         fn check_free_holding_cells(&self) -> bool {
7173                 let mut has_monitor_update = false;
7174                 let mut failed_htlcs = Vec::new();
7175
7176                 // Walk our list of channels and find any that need to update. Note that when we do find an
7177                 // update, if it includes actions that must be taken afterwards, we have to drop the
7178                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7179                 // manage to go through all our peers without finding a single channel to update.
7180                 'peer_loop: loop {
7181                         let per_peer_state = self.per_peer_state.read().unwrap();
7182                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7183                                 'chan_loop: loop {
7184                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7185                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7186                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7187                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7188                                         ) {
7189                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7190                                                 let funding_txo = chan.context.get_funding_txo();
7191                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7192                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &&WithChannelContext::from(&self.logger, &chan.context));
7193                                                 if !holding_cell_failed_htlcs.is_empty() {
7194                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7195                                                 }
7196                                                 if let Some(monitor_update) = monitor_opt {
7197                                                         has_monitor_update = true;
7198
7199                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7200                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7201                                                         continue 'peer_loop;
7202                                                 }
7203                                         }
7204                                         break 'chan_loop;
7205                                 }
7206                         }
7207                         break 'peer_loop;
7208                 }
7209
7210                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7211                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7212                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7213                 }
7214
7215                 has_update
7216         }
7217
7218         /// When a call to a [`ChannelSigner`] method returns an error, this indicates that the signer
7219         /// is (temporarily) unavailable, and the operation should be retried later.
7220         ///
7221         /// This method allows for that retry - either checking for any signer-pending messages to be
7222         /// attempted in every channel, or in the specifically provided channel.
7223         ///
7224         /// [`ChannelSigner`]: crate::sign::ChannelSigner
7225         #[cfg(test)] // This is only implemented for one signer method, and should be private until we
7226                      // actually finish implementing it fully.
7227         pub fn signer_unblocked(&self, channel_opt: Option<(PublicKey, ChannelId)>) {
7228                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7229
7230                 let unblock_chan = |phase: &mut ChannelPhase<SP>, pending_msg_events: &mut Vec<MessageSendEvent>| {
7231                         let node_id = phase.context().get_counterparty_node_id();
7232                         if let ChannelPhase::Funded(chan) = phase {
7233                                 let msgs = chan.signer_maybe_unblocked(&self.logger);
7234                                 if let Some(updates) = msgs.commitment_update {
7235                                         pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
7236                                                 node_id,
7237                                                 updates,
7238                                         });
7239                                 }
7240                                 if let Some(msg) = msgs.funding_signed {
7241                                         pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
7242                                                 node_id,
7243                                                 msg,
7244                                         });
7245                                 }
7246                                 if let Some(msg) = msgs.funding_created {
7247                                         pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
7248                                                 node_id,
7249                                                 msg,
7250                                         });
7251                                 }
7252                                 if let Some(msg) = msgs.channel_ready {
7253                                         send_channel_ready!(self, pending_msg_events, chan, msg);
7254                                 }
7255                         }
7256                 };
7257
7258                 let per_peer_state = self.per_peer_state.read().unwrap();
7259                 if let Some((counterparty_node_id, channel_id)) = channel_opt {
7260                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7261                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7262                                 let peer_state = &mut *peer_state_lock;
7263                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&channel_id) {
7264                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7265                                 }
7266                         }
7267                 } else {
7268                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7269                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7270                                 let peer_state = &mut *peer_state_lock;
7271                                 for (_, chan) in peer_state.channel_by_id.iter_mut() {
7272                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7273                                 }
7274                         }
7275                 }
7276         }
7277
7278         /// Check whether any channels have finished removing all pending updates after a shutdown
7279         /// exchange and can now send a closing_signed.
7280         /// Returns whether any closing_signed messages were generated.
7281         fn maybe_generate_initial_closing_signed(&self) -> bool {
7282                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7283                 let mut has_update = false;
7284                 let mut shutdown_results = Vec::new();
7285                 {
7286                         let per_peer_state = self.per_peer_state.read().unwrap();
7287
7288                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7289                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7290                                 let peer_state = &mut *peer_state_lock;
7291                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7292                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7293                                         match phase {
7294                                                 ChannelPhase::Funded(chan) => {
7295                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7296                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &&logger) {
7297                                                                 Ok((msg_opt, tx_opt, shutdown_result_opt)) => {
7298                                                                         if let Some(msg) = msg_opt {
7299                                                                                 has_update = true;
7300                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7301                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7302                                                                                 });
7303                                                                         }
7304                                                                         debug_assert_eq!(shutdown_result_opt.is_some(), chan.is_shutdown());
7305                                                                         if let Some(shutdown_result) = shutdown_result_opt {
7306                                                                                 shutdown_results.push(shutdown_result);
7307                                                                         }
7308                                                                         if let Some(tx) = tx_opt {
7309                                                                                 // We're done with this channel. We got a closing_signed and sent back
7310                                                                                 // a closing_signed with a closing transaction to broadcast.
7311                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7312                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7313                                                                                                 msg: update
7314                                                                                         });
7315                                                                                 }
7316
7317                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
7318
7319                                                                                 log_info!(logger, "Broadcasting {}", log_tx!(tx));
7320                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7321                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7322                                                                                 false
7323                                                                         } else { true }
7324                                                                 },
7325                                                                 Err(e) => {
7326                                                                         has_update = true;
7327                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7328                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7329                                                                         !close_channel
7330                                                                 }
7331                                                         }
7332                                                 },
7333                                                 _ => true, // Retain unfunded channels if present.
7334                                         }
7335                                 });
7336                         }
7337                 }
7338
7339                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7340                         let _ = handle_error!(self, err, counterparty_node_id);
7341                 }
7342
7343                 for shutdown_result in shutdown_results.drain(..) {
7344                         self.finish_close_channel(shutdown_result);
7345                 }
7346
7347                 has_update
7348         }
7349
7350         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7351         /// pushing the channel monitor update (if any) to the background events queue and removing the
7352         /// Channel object.
7353         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7354                 for mut failure in failed_channels.drain(..) {
7355                         // Either a commitment transactions has been confirmed on-chain or
7356                         // Channel::block_disconnected detected that the funding transaction has been
7357                         // reorganized out of the main chain.
7358                         // We cannot broadcast our latest local state via monitor update (as
7359                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7360                         // so we track the update internally and handle it when the user next calls
7361                         // timer_tick_occurred, guaranteeing we're running normally.
7362                         if let Some((counterparty_node_id, funding_txo, update)) = failure.monitor_update.take() {
7363                                 assert_eq!(update.updates.len(), 1);
7364                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7365                                         assert!(should_broadcast);
7366                                 } else { unreachable!(); }
7367                                 self.pending_background_events.lock().unwrap().push(
7368                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7369                                                 counterparty_node_id, funding_txo, update
7370                                         });
7371                         }
7372                         self.finish_close_channel(failure);
7373                 }
7374         }
7375
7376         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7377         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7378         /// not have an expiration unless otherwise set on the builder.
7379         ///
7380         /// # Privacy
7381         ///
7382         /// Uses a one-hop [`BlindedPath`] for the offer with [`ChannelManager::get_our_node_id`] as the
7383         /// introduction node and a derived signing pubkey for recipient privacy. As such, currently,
7384         /// the node must be announced. Otherwise, there is no way to find a path to the introduction
7385         /// node in order to send the [`InvoiceRequest`].
7386         ///
7387         /// # Limitations
7388         ///
7389         /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
7390         /// reply path.
7391         ///
7392         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7393         ///
7394         /// [`Offer`]: crate::offers::offer::Offer
7395         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7396         pub fn create_offer_builder(
7397                 &self, description: String
7398         ) -> OfferBuilder<DerivedMetadata, secp256k1::All> {
7399                 let node_id = self.get_our_node_id();
7400                 let expanded_key = &self.inbound_payment_key;
7401                 let entropy = &*self.entropy_source;
7402                 let secp_ctx = &self.secp_ctx;
7403                 let path = self.create_one_hop_blinded_path();
7404
7405                 OfferBuilder::deriving_signing_pubkey(description, node_id, expanded_key, entropy, secp_ctx)
7406                         .chain_hash(self.chain_hash)
7407                         .path(path)
7408         }
7409
7410         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7411         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7412         ///
7413         /// # Payment
7414         ///
7415         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7416         /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
7417         ///
7418         /// The builder will have the provided expiration set. Any changes to the expiration on the
7419         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7420         /// block time minus two hours is used for the current time when determining if the refund has
7421         /// expired.
7422         ///
7423         /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
7424         /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
7425         /// with an [`Event::InvoiceRequestFailed`].
7426         ///
7427         /// If `max_total_routing_fee_msat` is not specified, The default from
7428         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7429         ///
7430         /// # Privacy
7431         ///
7432         /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
7433         /// the introduction node and a derived payer id for payer privacy. As such, currently, the
7434         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7435         /// in order to send the [`Bolt12Invoice`].
7436         ///
7437         /// # Limitations
7438         ///
7439         /// Requires a direct connection to an introduction node in the responding
7440         /// [`Bolt12Invoice::payment_paths`].
7441         ///
7442         /// # Errors
7443         ///
7444         /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link
7445         /// or if `amount_msats` is invalid.
7446         ///
7447         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7448         ///
7449         /// [`Refund`]: crate::offers::refund::Refund
7450         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7451         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7452         pub fn create_refund_builder(
7453                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7454                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7455         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7456                 let node_id = self.get_our_node_id();
7457                 let expanded_key = &self.inbound_payment_key;
7458                 let entropy = &*self.entropy_source;
7459                 let secp_ctx = &self.secp_ctx;
7460                 let path = self.create_one_hop_blinded_path();
7461
7462                 let builder = RefundBuilder::deriving_payer_id(
7463                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7464                 )?
7465                         .chain_hash(self.chain_hash)
7466                         .absolute_expiry(absolute_expiry)
7467                         .path(path);
7468
7469                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7470                 self.pending_outbound_payments
7471                         .add_new_awaiting_invoice(
7472                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7473                         )
7474                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7475
7476                 Ok(builder)
7477         }
7478
7479         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7480         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7481         /// [`Bolt12Invoice`] once it is received.
7482         ///
7483         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7484         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7485         /// The optional parameters are used in the builder, if `Some`:
7486         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7487         ///   [`Offer::expects_quantity`] is `true`.
7488         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7489         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7490         ///
7491         /// If `max_total_routing_fee_msat` is not specified, The default from
7492         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7493         ///
7494         /// # Payment
7495         ///
7496         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7497         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7498         /// been sent.
7499         ///
7500         /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
7501         /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
7502         /// payment will fail with an [`Event::InvoiceRequestFailed`].
7503         ///
7504         /// # Privacy
7505         ///
7506         /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
7507         /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
7508         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7509         /// in order to send the [`Bolt12Invoice`].
7510         ///
7511         /// # Limitations
7512         ///
7513         /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
7514         /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
7515         /// [`Bolt12Invoice::payment_paths`].
7516         ///
7517         /// # Errors
7518         ///
7519         /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link
7520         /// or if the provided parameters are invalid for the offer.
7521         ///
7522         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7523         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7524         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7525         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7526         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7527         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7528         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7529         pub fn pay_for_offer(
7530                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7531                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7532                 max_total_routing_fee_msat: Option<u64>
7533         ) -> Result<(), Bolt12SemanticError> {
7534                 let expanded_key = &self.inbound_payment_key;
7535                 let entropy = &*self.entropy_source;
7536                 let secp_ctx = &self.secp_ctx;
7537
7538                 let builder = offer
7539                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7540                         .chain_hash(self.chain_hash)?;
7541                 let builder = match quantity {
7542                         None => builder,
7543                         Some(quantity) => builder.quantity(quantity)?,
7544                 };
7545                 let builder = match amount_msats {
7546                         None => builder,
7547                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7548                 };
7549                 let builder = match payer_note {
7550                         None => builder,
7551                         Some(payer_note) => builder.payer_note(payer_note),
7552                 };
7553
7554                 let invoice_request = builder.build_and_sign()?;
7555                 let reply_path = self.create_one_hop_blinded_path();
7556
7557                 let expiration = StaleExpiration::TimerTicks(1);
7558                 self.pending_outbound_payments
7559                         .add_new_awaiting_invoice(
7560                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7561                         )
7562                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7563
7564                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7565                 if offer.paths().is_empty() {
7566                         let message = new_pending_onion_message(
7567                                 OffersMessage::InvoiceRequest(invoice_request),
7568                                 Destination::Node(offer.signing_pubkey()),
7569                                 Some(reply_path),
7570                         );
7571                         pending_offers_messages.push(message);
7572                 } else {
7573                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7574                         // Using only one path could result in a failure if the path no longer exists. But only
7575                         // one invoice for a given payment id will be paid, even if more than one is received.
7576                         const REQUEST_LIMIT: usize = 10;
7577                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7578                                 let message = new_pending_onion_message(
7579                                         OffersMessage::InvoiceRequest(invoice_request.clone()),
7580                                         Destination::BlindedPath(path.clone()),
7581                                         Some(reply_path.clone()),
7582                                 );
7583                                 pending_offers_messages.push(message);
7584                         }
7585                 }
7586
7587                 Ok(())
7588         }
7589
7590         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7591         /// message.
7592         ///
7593         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7594         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7595         /// [`PaymentPreimage`].
7596         ///
7597         /// # Limitations
7598         ///
7599         /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
7600         /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
7601         /// node meeting the aforementioned criteria, but there's no guarantee that they will be
7602         /// received and no retries will be made.
7603         ///
7604         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7605         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7606                 let expanded_key = &self.inbound_payment_key;
7607                 let entropy = &*self.entropy_source;
7608                 let secp_ctx = &self.secp_ctx;
7609
7610                 let amount_msats = refund.amount_msats();
7611                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7612
7613                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7614                         Ok((payment_hash, payment_secret)) => {
7615                                 let payment_paths = vec![
7616                                         self.create_one_hop_blinded_payment_path(payment_secret),
7617                                 ];
7618                                 #[cfg(not(feature = "no-std"))]
7619                                 let builder = refund.respond_using_derived_keys(
7620                                         payment_paths, payment_hash, expanded_key, entropy
7621                                 )?;
7622                                 #[cfg(feature = "no-std")]
7623                                 let created_at = Duration::from_secs(
7624                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7625                                 );
7626                                 #[cfg(feature = "no-std")]
7627                                 let builder = refund.respond_using_derived_keys_no_std(
7628                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7629                                 )?;
7630                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7631                                 let reply_path = self.create_one_hop_blinded_path();
7632
7633                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7634                                 if refund.paths().is_empty() {
7635                                         let message = new_pending_onion_message(
7636                                                 OffersMessage::Invoice(invoice),
7637                                                 Destination::Node(refund.payer_id()),
7638                                                 Some(reply_path),
7639                                         );
7640                                         pending_offers_messages.push(message);
7641                                 } else {
7642                                         for path in refund.paths() {
7643                                                 let message = new_pending_onion_message(
7644                                                         OffersMessage::Invoice(invoice.clone()),
7645                                                         Destination::BlindedPath(path.clone()),
7646                                                         Some(reply_path.clone()),
7647                                                 );
7648                                                 pending_offers_messages.push(message);
7649                                         }
7650                                 }
7651
7652                                 Ok(())
7653                         },
7654                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7655                 }
7656         }
7657
7658         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7659         /// to pay us.
7660         ///
7661         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7662         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7663         ///
7664         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7665         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7666         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7667         /// passed directly to [`claim_funds`].
7668         ///
7669         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7670         ///
7671         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7672         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7673         ///
7674         /// # Note
7675         ///
7676         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7677         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7678         ///
7679         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7680         ///
7681         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7682         /// on versions of LDK prior to 0.0.114.
7683         ///
7684         /// [`claim_funds`]: Self::claim_funds
7685         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7686         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7687         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7688         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7689         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7690         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7691                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7692                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7693                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7694                         min_final_cltv_expiry_delta)
7695         }
7696
7697         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7698         /// stored external to LDK.
7699         ///
7700         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7701         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7702         /// the `min_value_msat` provided here, if one is provided.
7703         ///
7704         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7705         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7706         /// payments.
7707         ///
7708         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7709         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7710         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7711         /// sender "proof-of-payment" unless they have paid the required amount.
7712         ///
7713         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7714         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7715         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7716         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7717         /// invoices when no timeout is set.
7718         ///
7719         /// Note that we use block header time to time-out pending inbound payments (with some margin
7720         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7721         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7722         /// If you need exact expiry semantics, you should enforce them upon receipt of
7723         /// [`PaymentClaimable`].
7724         ///
7725         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7726         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7727         ///
7728         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7729         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7730         ///
7731         /// # Note
7732         ///
7733         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7734         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7735         ///
7736         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7737         ///
7738         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7739         /// on versions of LDK prior to 0.0.114.
7740         ///
7741         /// [`create_inbound_payment`]: Self::create_inbound_payment
7742         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7743         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7744                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7745                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7746                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7747                         min_final_cltv_expiry)
7748         }
7749
7750         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7751         /// previously returned from [`create_inbound_payment`].
7752         ///
7753         /// [`create_inbound_payment`]: Self::create_inbound_payment
7754         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7755                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7756         }
7757
7758         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7759         /// node.
7760         fn create_one_hop_blinded_path(&self) -> BlindedPath {
7761                 let entropy_source = self.entropy_source.deref();
7762                 let secp_ctx = &self.secp_ctx;
7763                 BlindedPath::one_hop_for_message(self.get_our_node_id(), entropy_source, secp_ctx).unwrap()
7764         }
7765
7766         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7767         /// node.
7768         fn create_one_hop_blinded_payment_path(
7769                 &self, payment_secret: PaymentSecret
7770         ) -> (BlindedPayInfo, BlindedPath) {
7771                 let entropy_source = self.entropy_source.deref();
7772                 let secp_ctx = &self.secp_ctx;
7773
7774                 let payee_node_id = self.get_our_node_id();
7775                 let max_cltv_expiry = self.best_block.read().unwrap().height() + LATENCY_GRACE_PERIOD_BLOCKS;
7776                 let payee_tlvs = ReceiveTlvs {
7777                         payment_secret,
7778                         payment_constraints: PaymentConstraints {
7779                                 max_cltv_expiry,
7780                                 htlc_minimum_msat: 1,
7781                         },
7782                 };
7783                 // TODO: Err for overflow?
7784                 BlindedPath::one_hop_for_payment(
7785                         payee_node_id, payee_tlvs, entropy_source, secp_ctx
7786                 ).unwrap()
7787         }
7788
7789         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
7790         /// are used when constructing the phantom invoice's route hints.
7791         ///
7792         /// [phantom node payments]: crate::sign::PhantomKeysManager
7793         pub fn get_phantom_scid(&self) -> u64 {
7794                 let best_block_height = self.best_block.read().unwrap().height();
7795                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7796                 loop {
7797                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7798                         // Ensure the generated scid doesn't conflict with a real channel.
7799                         match short_to_chan_info.get(&scid_candidate) {
7800                                 Some(_) => continue,
7801                                 None => return scid_candidate
7802                         }
7803                 }
7804         }
7805
7806         /// Gets route hints for use in receiving [phantom node payments].
7807         ///
7808         /// [phantom node payments]: crate::sign::PhantomKeysManager
7809         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
7810                 PhantomRouteHints {
7811                         channels: self.list_usable_channels(),
7812                         phantom_scid: self.get_phantom_scid(),
7813                         real_node_pubkey: self.get_our_node_id(),
7814                 }
7815         }
7816
7817         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
7818         /// used when constructing the route hints for HTLCs intended to be intercepted. See
7819         /// [`ChannelManager::forward_intercepted_htlc`].
7820         ///
7821         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
7822         /// times to get a unique scid.
7823         pub fn get_intercept_scid(&self) -> u64 {
7824                 let best_block_height = self.best_block.read().unwrap().height();
7825                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7826                 loop {
7827                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7828                         // Ensure the generated scid doesn't conflict with a real channel.
7829                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
7830                         return scid_candidate
7831                 }
7832         }
7833
7834         /// Gets inflight HTLC information by processing pending outbound payments that are in
7835         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
7836         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
7837                 let mut inflight_htlcs = InFlightHtlcs::new();
7838
7839                 let per_peer_state = self.per_peer_state.read().unwrap();
7840                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7841                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7842                         let peer_state = &mut *peer_state_lock;
7843                         for chan in peer_state.channel_by_id.values().filter_map(
7844                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7845                         ) {
7846                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
7847                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
7848                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
7849                                         }
7850                                 }
7851                         }
7852                 }
7853
7854                 inflight_htlcs
7855         }
7856
7857         #[cfg(any(test, feature = "_test_utils"))]
7858         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
7859                 let events = core::cell::RefCell::new(Vec::new());
7860                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
7861                 self.process_pending_events(&event_handler);
7862                 events.into_inner()
7863         }
7864
7865         #[cfg(feature = "_test_utils")]
7866         pub fn push_pending_event(&self, event: events::Event) {
7867                 let mut events = self.pending_events.lock().unwrap();
7868                 events.push_back((event, None));
7869         }
7870
7871         #[cfg(test)]
7872         pub fn pop_pending_event(&self) -> Option<events::Event> {
7873                 let mut events = self.pending_events.lock().unwrap();
7874                 events.pop_front().map(|(e, _)| e)
7875         }
7876
7877         #[cfg(test)]
7878         pub fn has_pending_payments(&self) -> bool {
7879                 self.pending_outbound_payments.has_pending_payments()
7880         }
7881
7882         #[cfg(test)]
7883         pub fn clear_pending_payments(&self) {
7884                 self.pending_outbound_payments.clear_pending_payments()
7885         }
7886
7887         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
7888         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
7889         /// operation. It will double-check that nothing *else* is also blocking the same channel from
7890         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
7891         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
7892                 let logger = WithContext::from(
7893                         &self.logger, Some(counterparty_node_id), Some(channel_funding_outpoint.to_channel_id())
7894                 );
7895                 loop {
7896                         let per_peer_state = self.per_peer_state.read().unwrap();
7897                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7898                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7899                                 let peer_state = &mut *peer_state_lck;
7900                                 if let Some(blocker) = completed_blocker.take() {
7901                                         // Only do this on the first iteration of the loop.
7902                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
7903                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
7904                                         {
7905                                                 blockers.retain(|iter| iter != &blocker);
7906                                         }
7907                                 }
7908
7909                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7910                                         channel_funding_outpoint, counterparty_node_id) {
7911                                         // Check that, while holding the peer lock, we don't have anything else
7912                                         // blocking monitor updates for this channel. If we do, release the monitor
7913                                         // update(s) when those blockers complete.
7914                                         log_trace!(logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
7915                                                 &channel_funding_outpoint.to_channel_id());
7916                                         break;
7917                                 }
7918
7919                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
7920                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7921                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
7922                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
7923                                                         log_debug!(logger, "Unlocking monitor updating for channel {} and updating monitor",
7924                                                                 channel_funding_outpoint.to_channel_id());
7925                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
7926                                                                 peer_state_lck, peer_state, per_peer_state, chan);
7927                                                         if further_update_exists {
7928                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
7929                                                                 // top of the loop.
7930                                                                 continue;
7931                                                         }
7932                                                 } else {
7933                                                         log_trace!(logger, "Unlocked monitor updating for channel {} without monitors to update",
7934                                                                 channel_funding_outpoint.to_channel_id());
7935                                                 }
7936                                         }
7937                                 }
7938                         } else {
7939                                 log_debug!(logger,
7940                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
7941                                         log_pubkey!(counterparty_node_id));
7942                         }
7943                         break;
7944                 }
7945         }
7946
7947         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
7948                 for action in actions {
7949                         match action {
7950                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7951                                         channel_funding_outpoint, counterparty_node_id
7952                                 } => {
7953                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
7954                                 }
7955                         }
7956                 }
7957         }
7958
7959         /// Processes any events asynchronously in the order they were generated since the last call
7960         /// using the given event handler.
7961         ///
7962         /// See the trait-level documentation of [`EventsProvider`] for requirements.
7963         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
7964                 &self, handler: H
7965         ) {
7966                 let mut ev;
7967                 process_events_body!(self, ev, { handler(ev).await });
7968         }
7969 }
7970
7971 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>
7972 where
7973         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
7974         T::Target: BroadcasterInterface,
7975         ES::Target: EntropySource,
7976         NS::Target: NodeSigner,
7977         SP::Target: SignerProvider,
7978         F::Target: FeeEstimator,
7979         R::Target: Router,
7980         L::Target: Logger,
7981 {
7982         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
7983         /// The returned array will contain `MessageSendEvent`s for different peers if
7984         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
7985         /// is always placed next to each other.
7986         ///
7987         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
7988         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
7989         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
7990         /// will randomly be placed first or last in the returned array.
7991         ///
7992         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
7993         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
7994         /// the `MessageSendEvent`s to the specific peer they were generated under.
7995         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
7996                 let events = RefCell::new(Vec::new());
7997                 PersistenceNotifierGuard::optionally_notify(self, || {
7998                         let mut result = NotifyOption::SkipPersistNoEvents;
7999
8000                         // TODO: This behavior should be documented. It's unintuitive that we query
8001                         // ChannelMonitors when clearing other events.
8002                         if self.process_pending_monitor_events() {
8003                                 result = NotifyOption::DoPersist;
8004                         }
8005
8006                         if self.check_free_holding_cells() {
8007                                 result = NotifyOption::DoPersist;
8008                         }
8009                         if self.maybe_generate_initial_closing_signed() {
8010                                 result = NotifyOption::DoPersist;
8011                         }
8012
8013                         let mut pending_events = Vec::new();
8014                         let per_peer_state = self.per_peer_state.read().unwrap();
8015                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8016                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8017                                 let peer_state = &mut *peer_state_lock;
8018                                 if peer_state.pending_msg_events.len() > 0 {
8019                                         pending_events.append(&mut peer_state.pending_msg_events);
8020                                 }
8021                         }
8022
8023                         if !pending_events.is_empty() {
8024                                 events.replace(pending_events);
8025                         }
8026
8027                         result
8028                 });
8029                 events.into_inner()
8030         }
8031 }
8032
8033 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>
8034 where
8035         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8036         T::Target: BroadcasterInterface,
8037         ES::Target: EntropySource,
8038         NS::Target: NodeSigner,
8039         SP::Target: SignerProvider,
8040         F::Target: FeeEstimator,
8041         R::Target: Router,
8042         L::Target: Logger,
8043 {
8044         /// Processes events that must be periodically handled.
8045         ///
8046         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
8047         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
8048         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
8049                 let mut ev;
8050                 process_events_body!(self, ev, handler.handle_event(ev));
8051         }
8052 }
8053
8054 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>
8055 where
8056         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8057         T::Target: BroadcasterInterface,
8058         ES::Target: EntropySource,
8059         NS::Target: NodeSigner,
8060         SP::Target: SignerProvider,
8061         F::Target: FeeEstimator,
8062         R::Target: Router,
8063         L::Target: Logger,
8064 {
8065         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
8066                 {
8067                         let best_block = self.best_block.read().unwrap();
8068                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
8069                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
8070                         assert_eq!(best_block.height(), height - 1,
8071                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
8072                 }
8073
8074                 self.transactions_confirmed(header, txdata, height);
8075                 self.best_block_updated(header, height);
8076         }
8077
8078         fn block_disconnected(&self, header: &Header, height: u32) {
8079                 let _persistence_guard =
8080                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8081                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8082                 let new_height = height - 1;
8083                 {
8084                         let mut best_block = self.best_block.write().unwrap();
8085                         assert_eq!(best_block.block_hash(), header.block_hash(),
8086                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
8087                         assert_eq!(best_block.height(), height,
8088                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
8089                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
8090                 }
8091
8092                 self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context)));
8093         }
8094 }
8095
8096 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>
8097 where
8098         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8099         T::Target: BroadcasterInterface,
8100         ES::Target: EntropySource,
8101         NS::Target: NodeSigner,
8102         SP::Target: SignerProvider,
8103         F::Target: FeeEstimator,
8104         R::Target: Router,
8105         L::Target: Logger,
8106 {
8107         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
8108                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8109                 // during initialization prior to the chain_monitor being fully configured in some cases.
8110                 // See the docs for `ChannelManagerReadArgs` for more.
8111
8112                 let block_hash = header.block_hash();
8113                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
8114
8115                 let _persistence_guard =
8116                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8117                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8118                 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context))
8119                         .map(|(a, b)| (a, Vec::new(), b)));
8120
8121                 let last_best_block_height = self.best_block.read().unwrap().height();
8122                 if height < last_best_block_height {
8123                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
8124                         self.do_chain_event(Some(last_best_block_height), |channel| channel.best_block_updated(last_best_block_height, timestamp as u32, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context)));
8125                 }
8126         }
8127
8128         fn best_block_updated(&self, header: &Header, height: u32) {
8129                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8130                 // during initialization prior to the chain_monitor being fully configured in some cases.
8131                 // See the docs for `ChannelManagerReadArgs` for more.
8132
8133                 let block_hash = header.block_hash();
8134                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
8135
8136                 let _persistence_guard =
8137                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8138                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8139                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
8140
8141                 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context)));
8142
8143                 macro_rules! max_time {
8144                         ($timestamp: expr) => {
8145                                 loop {
8146                                         // Update $timestamp to be the max of its current value and the block
8147                                         // timestamp. This should keep us close to the current time without relying on
8148                                         // having an explicit local time source.
8149                                         // Just in case we end up in a race, we loop until we either successfully
8150                                         // update $timestamp or decide we don't need to.
8151                                         let old_serial = $timestamp.load(Ordering::Acquire);
8152                                         if old_serial >= header.time as usize { break; }
8153                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8154                                                 break;
8155                                         }
8156                                 }
8157                         }
8158                 }
8159                 max_time!(self.highest_seen_timestamp);
8160                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8161                 payment_secrets.retain(|_, inbound_payment| {
8162                         inbound_payment.expiry_time > header.time as u64
8163                 });
8164         }
8165
8166         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
8167                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8168                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8169                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8170                         let peer_state = &mut *peer_state_lock;
8171                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8172                                 let txid_opt = chan.context.get_funding_txo();
8173                                 let height_opt = chan.context.get_funding_tx_confirmation_height();
8174                                 let hash_opt = chan.context.get_funding_tx_confirmed_in();
8175                                 if let (Some(funding_txo), Some(conf_height), Some(block_hash)) = (txid_opt, height_opt, hash_opt) {
8176                                         res.push((funding_txo.txid, conf_height, Some(block_hash)));
8177                                 }
8178                         }
8179                 }
8180                 res
8181         }
8182
8183         fn transaction_unconfirmed(&self, txid: &Txid) {
8184                 let _persistence_guard =
8185                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8186                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8187                 self.do_chain_event(None, |channel| {
8188                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8189                                 if funding_txo.txid == *txid {
8190                                         channel.funding_transaction_unconfirmed(&&WithChannelContext::from(&self.logger, &channel.context)).map(|()| (None, Vec::new(), None))
8191                                 } else { Ok((None, Vec::new(), None)) }
8192                         } else { Ok((None, Vec::new(), None)) }
8193                 });
8194         }
8195 }
8196
8197 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>
8198 where
8199         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8200         T::Target: BroadcasterInterface,
8201         ES::Target: EntropySource,
8202         NS::Target: NodeSigner,
8203         SP::Target: SignerProvider,
8204         F::Target: FeeEstimator,
8205         R::Target: Router,
8206         L::Target: Logger,
8207 {
8208         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8209         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8210         /// the function.
8211         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8212                         (&self, height_opt: Option<u32>, f: FN) {
8213                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8214                 // during initialization prior to the chain_monitor being fully configured in some cases.
8215                 // See the docs for `ChannelManagerReadArgs` for more.
8216
8217                 let mut failed_channels = Vec::new();
8218                 let mut timed_out_htlcs = Vec::new();
8219                 {
8220                         let per_peer_state = self.per_peer_state.read().unwrap();
8221                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8222                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8223                                 let peer_state = &mut *peer_state_lock;
8224                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8225                                 peer_state.channel_by_id.retain(|_, phase| {
8226                                         match phase {
8227                                                 // Retain unfunded channels.
8228                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8229                                                 ChannelPhase::Funded(channel) => {
8230                                                         let res = f(channel);
8231                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8232                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8233                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8234                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8235                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8236                                                                 }
8237                                                                 let logger = WithChannelContext::from(&self.logger, &channel.context);
8238                                                                 if let Some(channel_ready) = channel_ready_opt {
8239                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8240                                                                         if channel.context.is_usable() {
8241                                                                                 log_trace!(logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8242                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8243                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8244                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8245                                                                                                 msg,
8246                                                                                         });
8247                                                                                 }
8248                                                                         } else {
8249                                                                                 log_trace!(logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8250                                                                         }
8251                                                                 }
8252
8253                                                                 {
8254                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8255                                                                         emit_channel_ready_event!(pending_events, channel);
8256                                                                 }
8257
8258                                                                 if let Some(announcement_sigs) = announcement_sigs {
8259                                                                         log_trace!(logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8260                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8261                                                                                 node_id: channel.context.get_counterparty_node_id(),
8262                                                                                 msg: announcement_sigs,
8263                                                                         });
8264                                                                         if let Some(height) = height_opt {
8265                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8266                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8267                                                                                                 msg: announcement,
8268                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8269                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8270                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8271                                                                                         });
8272                                                                                 }
8273                                                                         }
8274                                                                 }
8275                                                                 if channel.is_our_channel_ready() {
8276                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8277                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8278                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8279                                                                                 // can relay using the real SCID at relay-time (i.e.
8280                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8281                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8282                                                                                 // is always consistent.
8283                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8284                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8285                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8286                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8287                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8288                                                                         }
8289                                                                 }
8290                                                         } else if let Err(reason) = res {
8291                                                                 update_maps_on_chan_removal!(self, &channel.context);
8292                                                                 // It looks like our counterparty went on-chain or funding transaction was
8293                                                                 // reorged out of the main chain. Close the channel.
8294                                                                 failed_channels.push(channel.context.force_shutdown(true));
8295                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8296                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
8297                                                                                 msg: update
8298                                                                         });
8299                                                                 }
8300                                                                 let reason_message = format!("{}", reason);
8301                                                                 self.issue_channel_close_events(&channel.context, reason);
8302                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8303                                                                         node_id: channel.context.get_counterparty_node_id(),
8304                                                                         action: msgs::ErrorAction::DisconnectPeer {
8305                                                                                 msg: Some(msgs::ErrorMessage {
8306                                                                                         channel_id: channel.context.channel_id(),
8307                                                                                         data: reason_message,
8308                                                                                 })
8309                                                                         },
8310                                                                 });
8311                                                                 return false;
8312                                                         }
8313                                                         true
8314                                                 }
8315                                         }
8316                                 });
8317                         }
8318                 }
8319
8320                 if let Some(height) = height_opt {
8321                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8322                                 payment.htlcs.retain(|htlc| {
8323                                         // If height is approaching the number of blocks we think it takes us to get
8324                                         // our commitment transaction confirmed before the HTLC expires, plus the
8325                                         // number of blocks we generally consider it to take to do a commitment update,
8326                                         // just give up on it and fail the HTLC.
8327                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8328                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8329                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8330
8331                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8332                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8333                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8334                                                 false
8335                                         } else { true }
8336                                 });
8337                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8338                         });
8339
8340                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8341                         intercepted_htlcs.retain(|_, htlc| {
8342                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8343                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8344                                                 short_channel_id: htlc.prev_short_channel_id,
8345                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8346                                                 htlc_id: htlc.prev_htlc_id,
8347                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8348                                                 phantom_shared_secret: None,
8349                                                 outpoint: htlc.prev_funding_outpoint,
8350                                                 blinded_failure: htlc.forward_info.routing.blinded_failure(),
8351                                         });
8352
8353                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8354                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8355                                                 _ => unreachable!(),
8356                                         };
8357                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8358                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8359                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8360                                         let logger = WithContext::from(
8361                                                 &self.logger, None, Some(htlc.prev_funding_outpoint.to_channel_id())
8362                                         );
8363                                         log_trace!(logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8364                                         false
8365                                 } else { true }
8366                         });
8367                 }
8368
8369                 self.handle_init_event_channel_failures(failed_channels);
8370
8371                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8372                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8373                 }
8374         }
8375
8376         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8377         /// may have events that need processing.
8378         ///
8379         /// In order to check if this [`ChannelManager`] needs persisting, call
8380         /// [`Self::get_and_clear_needs_persistence`].
8381         ///
8382         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8383         /// [`ChannelManager`] and should instead register actions to be taken later.
8384         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8385                 self.event_persist_notifier.get_future()
8386         }
8387
8388         /// Returns true if this [`ChannelManager`] needs to be persisted.
8389         pub fn get_and_clear_needs_persistence(&self) -> bool {
8390                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8391         }
8392
8393         #[cfg(any(test, feature = "_test_utils"))]
8394         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8395                 self.event_persist_notifier.notify_pending()
8396         }
8397
8398         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8399         /// [`chain::Confirm`] interfaces.
8400         pub fn current_best_block(&self) -> BestBlock {
8401                 self.best_block.read().unwrap().clone()
8402         }
8403
8404         /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
8405         /// [`ChannelManager`].
8406         pub fn node_features(&self) -> NodeFeatures {
8407                 provided_node_features(&self.default_configuration)
8408         }
8409
8410         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
8411         /// [`ChannelManager`].
8412         ///
8413         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8414         /// or not. Thus, this method is not public.
8415         #[cfg(any(feature = "_test_utils", test))]
8416         pub fn bolt11_invoice_features(&self) -> Bolt11InvoiceFeatures {
8417                 provided_bolt11_invoice_features(&self.default_configuration)
8418         }
8419
8420         /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
8421         /// [`ChannelManager`].
8422         fn bolt12_invoice_features(&self) -> Bolt12InvoiceFeatures {
8423                 provided_bolt12_invoice_features(&self.default_configuration)
8424         }
8425
8426         /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
8427         /// [`ChannelManager`].
8428         pub fn channel_features(&self) -> ChannelFeatures {
8429                 provided_channel_features(&self.default_configuration)
8430         }
8431
8432         /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
8433         /// [`ChannelManager`].
8434         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8435                 provided_channel_type_features(&self.default_configuration)
8436         }
8437
8438         /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
8439         /// [`ChannelManager`].
8440         pub fn init_features(&self) -> InitFeatures {
8441                 provided_init_features(&self.default_configuration)
8442         }
8443 }
8444
8445 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8446         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8447 where
8448         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8449         T::Target: BroadcasterInterface,
8450         ES::Target: EntropySource,
8451         NS::Target: NodeSigner,
8452         SP::Target: SignerProvider,
8453         F::Target: FeeEstimator,
8454         R::Target: Router,
8455         L::Target: Logger,
8456 {
8457         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8458                 // Note that we never need to persist the updated ChannelManager for an inbound
8459                 // open_channel message - pre-funded channels are never written so there should be no
8460                 // change to the contents.
8461                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8462                         let res = self.internal_open_channel(counterparty_node_id, msg);
8463                         let persist = match &res {
8464                                 Err(e) if e.closes_channel() => {
8465                                         debug_assert!(false, "We shouldn't close a new channel");
8466                                         NotifyOption::DoPersist
8467                                 },
8468                                 _ => NotifyOption::SkipPersistHandleEvents,
8469                         };
8470                         let _ = handle_error!(self, res, *counterparty_node_id);
8471                         persist
8472                 });
8473         }
8474
8475         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8476                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8477                         "Dual-funded channels not supported".to_owned(),
8478                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8479         }
8480
8481         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8482                 // Note that we never need to persist the updated ChannelManager for an inbound
8483                 // accept_channel message - pre-funded channels are never written so there should be no
8484                 // change to the contents.
8485                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8486                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8487                         NotifyOption::SkipPersistHandleEvents
8488                 });
8489         }
8490
8491         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8492                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8493                         "Dual-funded channels not supported".to_owned(),
8494                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8495         }
8496
8497         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8498                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8499                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8500         }
8501
8502         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8503                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8504                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8505         }
8506
8507         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8508                 // Note that we never need to persist the updated ChannelManager for an inbound
8509                 // channel_ready message - while the channel's state will change, any channel_ready message
8510                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8511                 // will not force-close the channel on startup.
8512                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8513                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8514                         let persist = match &res {
8515                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8516                                 _ => NotifyOption::SkipPersistHandleEvents,
8517                         };
8518                         let _ = handle_error!(self, res, *counterparty_node_id);
8519                         persist
8520                 });
8521         }
8522
8523         fn handle_stfu(&self, counterparty_node_id: &PublicKey, msg: &msgs::Stfu) {
8524                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8525                         "Quiescence not supported".to_owned(),
8526                          msg.channel_id.clone())), *counterparty_node_id);
8527         }
8528
8529         fn handle_splice(&self, counterparty_node_id: &PublicKey, msg: &msgs::Splice) {
8530                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8531                         "Splicing not supported".to_owned(),
8532                          msg.channel_id.clone())), *counterparty_node_id);
8533         }
8534
8535         fn handle_splice_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceAck) {
8536                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8537                         "Splicing not supported (splice_ack)".to_owned(),
8538                          msg.channel_id.clone())), *counterparty_node_id);
8539         }
8540
8541         fn handle_splice_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
8542                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8543                         "Splicing not supported (splice_locked)".to_owned(),
8544                          msg.channel_id.clone())), *counterparty_node_id);
8545         }
8546
8547         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8548                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8549                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8550         }
8551
8552         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8553                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8554                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8555         }
8556
8557         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8558                 // Note that we never need to persist the updated ChannelManager for an inbound
8559                 // update_add_htlc message - the message itself doesn't change our channel state only the
8560                 // `commitment_signed` message afterwards will.
8561                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8562                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8563                         let persist = match &res {
8564                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8565                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8566                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8567                         };
8568                         let _ = handle_error!(self, res, *counterparty_node_id);
8569                         persist
8570                 });
8571         }
8572
8573         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8574                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8575                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8576         }
8577
8578         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8579                 // Note that we never need to persist the updated ChannelManager for an inbound
8580                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8581                 // `commitment_signed` message afterwards will.
8582                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8583                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8584                         let persist = match &res {
8585                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8586                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8587                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8588                         };
8589                         let _ = handle_error!(self, res, *counterparty_node_id);
8590                         persist
8591                 });
8592         }
8593
8594         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8595                 // Note that we never need to persist the updated ChannelManager for an inbound
8596                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8597                 // only the `commitment_signed` message afterwards will.
8598                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8599                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8600                         let persist = match &res {
8601                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8602                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8603                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8604                         };
8605                         let _ = handle_error!(self, res, *counterparty_node_id);
8606                         persist
8607                 });
8608         }
8609
8610         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8611                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8612                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8613         }
8614
8615         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8616                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8617                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8618         }
8619
8620         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8621                 // Note that we never need to persist the updated ChannelManager for an inbound
8622                 // update_fee message - the message itself doesn't change our channel state only the
8623                 // `commitment_signed` message afterwards will.
8624                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8625                         let res = self.internal_update_fee(counterparty_node_id, msg);
8626                         let persist = match &res {
8627                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8628                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8629                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8630                         };
8631                         let _ = handle_error!(self, res, *counterparty_node_id);
8632                         persist
8633                 });
8634         }
8635
8636         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8637                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8638                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8639         }
8640
8641         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8642                 PersistenceNotifierGuard::optionally_notify(self, || {
8643                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8644                                 persist
8645                         } else {
8646                                 NotifyOption::DoPersist
8647                         }
8648                 });
8649         }
8650
8651         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8652                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8653                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8654                         let persist = match &res {
8655                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8656                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8657                                 Ok(persist) => *persist,
8658                         };
8659                         let _ = handle_error!(self, res, *counterparty_node_id);
8660                         persist
8661                 });
8662         }
8663
8664         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8665                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8666                         self, || NotifyOption::SkipPersistHandleEvents);
8667                 let mut failed_channels = Vec::new();
8668                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8669                 let remove_peer = {
8670                         log_debug!(
8671                                 WithContext::from(&self.logger, Some(*counterparty_node_id), None),
8672                                 "Marking channels with {} disconnected and generating channel_updates.",
8673                                 log_pubkey!(counterparty_node_id)
8674                         );
8675                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8676                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8677                                 let peer_state = &mut *peer_state_lock;
8678                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8679                                 peer_state.channel_by_id.retain(|_, phase| {
8680                                         let context = match phase {
8681                                                 ChannelPhase::Funded(chan) => {
8682                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
8683                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&&logger).is_ok() {
8684                                                                 // We only retain funded channels that are not shutdown.
8685                                                                 return true;
8686                                                         }
8687                                                         &mut chan.context
8688                                                 },
8689                                                 // Unfunded channels will always be removed.
8690                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8691                                                         &mut chan.context
8692                                                 },
8693                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8694                                                         &mut chan.context
8695                                                 },
8696                                         };
8697                                         // Clean up for removal.
8698                                         update_maps_on_chan_removal!(self, &context);
8699                                         self.issue_channel_close_events(&context, ClosureReason::DisconnectedPeer);
8700                                         failed_channels.push(context.force_shutdown(false));
8701                                         false
8702                                 });
8703                                 // Note that we don't bother generating any events for pre-accept channels -
8704                                 // they're not considered "channels" yet from the PoV of our events interface.
8705                                 peer_state.inbound_channel_request_by_id.clear();
8706                                 pending_msg_events.retain(|msg| {
8707                                         match msg {
8708                                                 // V1 Channel Establishment
8709                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8710                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8711                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8712                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8713                                                 // V2 Channel Establishment
8714                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8715                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8716                                                 // Common Channel Establishment
8717                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8718                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8719                                                 // Quiescence
8720                                                 &events::MessageSendEvent::SendStfu { .. } => false,
8721                                                 // Splicing
8722                                                 &events::MessageSendEvent::SendSplice { .. } => false,
8723                                                 &events::MessageSendEvent::SendSpliceAck { .. } => false,
8724                                                 &events::MessageSendEvent::SendSpliceLocked { .. } => false,
8725                                                 // Interactive Transaction Construction
8726                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8727                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8728                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8729                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8730                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8731                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8732                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8733                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8734                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8735                                                 // Channel Operations
8736                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8737                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8738                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8739                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8740                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8741                                                 &events::MessageSendEvent::HandleError { .. } => false,
8742                                                 // Gossip
8743                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8744                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8745                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8746                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8747                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8748                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8749                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8750                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8751                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8752                                         }
8753                                 });
8754                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8755                                 peer_state.is_connected = false;
8756                                 peer_state.ok_to_remove(true)
8757                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8758                 };
8759                 if remove_peer {
8760                         per_peer_state.remove(counterparty_node_id);
8761                 }
8762                 mem::drop(per_peer_state);
8763
8764                 for failure in failed_channels.drain(..) {
8765                         self.finish_close_channel(failure);
8766                 }
8767         }
8768
8769         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8770                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), None);
8771                 if !init_msg.features.supports_static_remote_key() {
8772                         log_debug!(logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8773                         return Err(());
8774                 }
8775
8776                 let mut res = Ok(());
8777
8778                 PersistenceNotifierGuard::optionally_notify(self, || {
8779                         // If we have too many peers connected which don't have funded channels, disconnect the
8780                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8781                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8782                         // peers connect, but we'll reject new channels from them.
8783                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8784                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8785
8786                         {
8787                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8788                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8789                                         hash_map::Entry::Vacant(e) => {
8790                                                 if inbound_peer_limited {
8791                                                         res = Err(());
8792                                                         return NotifyOption::SkipPersistNoEvents;
8793                                                 }
8794                                                 e.insert(Mutex::new(PeerState {
8795                                                         channel_by_id: HashMap::new(),
8796                                                         inbound_channel_request_by_id: HashMap::new(),
8797                                                         latest_features: init_msg.features.clone(),
8798                                                         pending_msg_events: Vec::new(),
8799                                                         in_flight_monitor_updates: BTreeMap::new(),
8800                                                         monitor_update_blocked_actions: BTreeMap::new(),
8801                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
8802                                                         is_connected: true,
8803                                                 }));
8804                                         },
8805                                         hash_map::Entry::Occupied(e) => {
8806                                                 let mut peer_state = e.get().lock().unwrap();
8807                                                 peer_state.latest_features = init_msg.features.clone();
8808
8809                                                 let best_block_height = self.best_block.read().unwrap().height();
8810                                                 if inbound_peer_limited &&
8811                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
8812                                                         peer_state.channel_by_id.len()
8813                                                 {
8814                                                         res = Err(());
8815                                                         return NotifyOption::SkipPersistNoEvents;
8816                                                 }
8817
8818                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
8819                                                 peer_state.is_connected = true;
8820                                         },
8821                                 }
8822                         }
8823
8824                         log_debug!(logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
8825
8826                         let per_peer_state = self.per_peer_state.read().unwrap();
8827                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8828                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8829                                 let peer_state = &mut *peer_state_lock;
8830                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8831
8832                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
8833                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else {
8834                                                 // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
8835                                                 // (so won't be recovered after a crash), they shouldn't exist here and we would never need to
8836                                                 // worry about closing and removing them.
8837                                                 debug_assert!(false);
8838                                                 None
8839                                         }
8840                                 ).for_each(|chan| {
8841                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
8842                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
8843                                                 node_id: chan.context.get_counterparty_node_id(),
8844                                                 msg: chan.get_channel_reestablish(&&logger),
8845                                         });
8846                                 });
8847                         }
8848
8849                         return NotifyOption::SkipPersistHandleEvents;
8850                         //TODO: Also re-broadcast announcement_signatures
8851                 });
8852                 res
8853         }
8854
8855         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
8856                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8857
8858                 match &msg.data as &str {
8859                         "cannot co-op close channel w/ active htlcs"|
8860                         "link failed to shutdown" =>
8861                         {
8862                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
8863                                 // send one while HTLCs are still present. The issue is tracked at
8864                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
8865                                 // to fix it but none so far have managed to land upstream. The issue appears to be
8866                                 // very low priority for the LND team despite being marked "P1".
8867                                 // We're not going to bother handling this in a sensible way, instead simply
8868                                 // repeating the Shutdown message on repeat until morale improves.
8869                                 if !msg.channel_id.is_zero() {
8870                                         let per_peer_state = self.per_peer_state.read().unwrap();
8871                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8872                                         if peer_state_mutex_opt.is_none() { return; }
8873                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
8874                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
8875                                                 if let Some(msg) = chan.get_outbound_shutdown() {
8876                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
8877                                                                 node_id: *counterparty_node_id,
8878                                                                 msg,
8879                                                         });
8880                                                 }
8881                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
8882                                                         node_id: *counterparty_node_id,
8883                                                         action: msgs::ErrorAction::SendWarningMessage {
8884                                                                 msg: msgs::WarningMessage {
8885                                                                         channel_id: msg.channel_id,
8886                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
8887                                                                 },
8888                                                                 log_level: Level::Trace,
8889                                                         }
8890                                                 });
8891                                         }
8892                                 }
8893                                 return;
8894                         }
8895                         _ => {}
8896                 }
8897
8898                 if msg.channel_id.is_zero() {
8899                         let channel_ids: Vec<ChannelId> = {
8900                                 let per_peer_state = self.per_peer_state.read().unwrap();
8901                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8902                                 if peer_state_mutex_opt.is_none() { return; }
8903                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8904                                 let peer_state = &mut *peer_state_lock;
8905                                 // Note that we don't bother generating any events for pre-accept channels -
8906                                 // they're not considered "channels" yet from the PoV of our events interface.
8907                                 peer_state.inbound_channel_request_by_id.clear();
8908                                 peer_state.channel_by_id.keys().cloned().collect()
8909                         };
8910                         for channel_id in channel_ids {
8911                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8912                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
8913                         }
8914                 } else {
8915                         {
8916                                 // First check if we can advance the channel type and try again.
8917                                 let per_peer_state = self.per_peer_state.read().unwrap();
8918                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8919                                 if peer_state_mutex_opt.is_none() { return; }
8920                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8921                                 let peer_state = &mut *peer_state_lock;
8922                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8923                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
8924                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
8925                                                         node_id: *counterparty_node_id,
8926                                                         msg,
8927                                                 });
8928                                                 return;
8929                                         }
8930                                 }
8931                         }
8932
8933                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8934                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
8935                 }
8936         }
8937
8938         fn provided_node_features(&self) -> NodeFeatures {
8939                 provided_node_features(&self.default_configuration)
8940         }
8941
8942         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
8943                 provided_init_features(&self.default_configuration)
8944         }
8945
8946         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8947                 Some(vec![self.chain_hash])
8948         }
8949
8950         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
8951                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8952                         "Dual-funded channels not supported".to_owned(),
8953                          msg.channel_id.clone())), *counterparty_node_id);
8954         }
8955
8956         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
8957                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8958                         "Dual-funded channels not supported".to_owned(),
8959                          msg.channel_id.clone())), *counterparty_node_id);
8960         }
8961
8962         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
8963                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8964                         "Dual-funded channels not supported".to_owned(),
8965                          msg.channel_id.clone())), *counterparty_node_id);
8966         }
8967
8968         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
8969                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8970                         "Dual-funded channels not supported".to_owned(),
8971                          msg.channel_id.clone())), *counterparty_node_id);
8972         }
8973
8974         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
8975                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8976                         "Dual-funded channels not supported".to_owned(),
8977                          msg.channel_id.clone())), *counterparty_node_id);
8978         }
8979
8980         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
8981                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8982                         "Dual-funded channels not supported".to_owned(),
8983                          msg.channel_id.clone())), *counterparty_node_id);
8984         }
8985
8986         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
8987                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8988                         "Dual-funded channels not supported".to_owned(),
8989                          msg.channel_id.clone())), *counterparty_node_id);
8990         }
8991
8992         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
8993                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8994                         "Dual-funded channels not supported".to_owned(),
8995                          msg.channel_id.clone())), *counterparty_node_id);
8996         }
8997
8998         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
8999                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9000                         "Dual-funded channels not supported".to_owned(),
9001                          msg.channel_id.clone())), *counterparty_node_id);
9002         }
9003 }
9004
9005 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9006 OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
9007 where
9008         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9009         T::Target: BroadcasterInterface,
9010         ES::Target: EntropySource,
9011         NS::Target: NodeSigner,
9012         SP::Target: SignerProvider,
9013         F::Target: FeeEstimator,
9014         R::Target: Router,
9015         L::Target: Logger,
9016 {
9017         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
9018                 let secp_ctx = &self.secp_ctx;
9019                 let expanded_key = &self.inbound_payment_key;
9020
9021                 match message {
9022                         OffersMessage::InvoiceRequest(invoice_request) => {
9023                                 let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
9024                                         &invoice_request
9025                                 ) {
9026                                         Ok(amount_msats) => Some(amount_msats),
9027                                         Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
9028                                 };
9029                                 let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
9030                                         Ok(invoice_request) => invoice_request,
9031                                         Err(()) => {
9032                                                 let error = Bolt12SemanticError::InvalidMetadata;
9033                                                 return Some(OffersMessage::InvoiceError(error.into()));
9034                                         },
9035                                 };
9036                                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9037
9038                                 match self.create_inbound_payment(amount_msats, relative_expiry, None) {
9039                                         Ok((payment_hash, payment_secret)) if invoice_request.keys.is_some() => {
9040                                                 let payment_paths = vec![
9041                                                         self.create_one_hop_blinded_payment_path(payment_secret),
9042                                                 ];
9043                                                 #[cfg(not(feature = "no-std"))]
9044                                                 let builder = invoice_request.respond_using_derived_keys(
9045                                                         payment_paths, payment_hash
9046                                                 );
9047                                                 #[cfg(feature = "no-std")]
9048                                                 let created_at = Duration::from_secs(
9049                                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9050                                                 );
9051                                                 #[cfg(feature = "no-std")]
9052                                                 let builder = invoice_request.respond_using_derived_keys_no_std(
9053                                                         payment_paths, payment_hash, created_at
9054                                                 );
9055                                                 match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
9056                                                         Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
9057                                                         Err(error) => Some(OffersMessage::InvoiceError(error.into())),
9058                                                 }
9059                                         },
9060                                         Ok((payment_hash, payment_secret)) => {
9061                                                 let payment_paths = vec![
9062                                                         self.create_one_hop_blinded_payment_path(payment_secret),
9063                                                 ];
9064                                                 #[cfg(not(feature = "no-std"))]
9065                                                 let builder = invoice_request.respond_with(payment_paths, payment_hash);
9066                                                 #[cfg(feature = "no-std")]
9067                                                 let created_at = Duration::from_secs(
9068                                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9069                                                 );
9070                                                 #[cfg(feature = "no-std")]
9071                                                 let builder = invoice_request.respond_with_no_std(
9072                                                         payment_paths, payment_hash, created_at
9073                                                 );
9074                                                 let response = builder.and_then(|builder| builder.allow_mpp().build())
9075                                                         .map_err(|e| OffersMessage::InvoiceError(e.into()))
9076                                                         .and_then(|invoice|
9077                                                                 match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
9078                                                                         Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
9079                                                                         Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
9080                                                                                         InvoiceError::from_string("Failed signing invoice".to_string())
9081                                                                         )),
9082                                                                         Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
9083                                                                                         InvoiceError::from_string("Failed invoice signature verification".to_string())
9084                                                                         )),
9085                                                                 });
9086                                                 match response {
9087                                                         Ok(invoice) => Some(invoice),
9088                                                         Err(error) => Some(error),
9089                                                 }
9090                                         },
9091                                         Err(()) => {
9092                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::InvalidAmount.into()))
9093                                         },
9094                                 }
9095                         },
9096                         OffersMessage::Invoice(invoice) => {
9097                                 match invoice.verify(expanded_key, secp_ctx) {
9098                                         Err(()) => {
9099                                                 Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
9100                                         },
9101                                         Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
9102                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
9103                                         },
9104                                         Ok(payment_id) => {
9105                                                 if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
9106                                                         log_trace!(self.logger, "Failed paying invoice: {:?}", e);
9107                                                         Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
9108                                                 } else {
9109                                                         None
9110                                                 }
9111                                         },
9112                                 }
9113                         },
9114                         OffersMessage::InvoiceError(invoice_error) => {
9115                                 log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
9116                                 None
9117                         },
9118                 }
9119         }
9120
9121         fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> {
9122                 core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
9123         }
9124 }
9125
9126 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
9127 /// [`ChannelManager`].
9128 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
9129         let mut node_features = provided_init_features(config).to_context();
9130         node_features.set_keysend_optional();
9131         node_features
9132 }
9133
9134 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
9135 /// [`ChannelManager`].
9136 ///
9137 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
9138 /// or not. Thus, this method is not public.
9139 #[cfg(any(feature = "_test_utils", test))]
9140 pub(crate) fn provided_bolt11_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
9141         provided_init_features(config).to_context()
9142 }
9143
9144 /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
9145 /// [`ChannelManager`].
9146 pub(crate) fn provided_bolt12_invoice_features(config: &UserConfig) -> Bolt12InvoiceFeatures {
9147         provided_init_features(config).to_context()
9148 }
9149
9150 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
9151 /// [`ChannelManager`].
9152 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
9153         provided_init_features(config).to_context()
9154 }
9155
9156 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
9157 /// [`ChannelManager`].
9158 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
9159         ChannelTypeFeatures::from_init(&provided_init_features(config))
9160 }
9161
9162 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
9163 /// [`ChannelManager`].
9164 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
9165         // Note that if new features are added here which other peers may (eventually) require, we
9166         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
9167         // [`ErroringMessageHandler`].
9168         let mut features = InitFeatures::empty();
9169         features.set_data_loss_protect_required();
9170         features.set_upfront_shutdown_script_optional();
9171         features.set_variable_length_onion_required();
9172         features.set_static_remote_key_required();
9173         features.set_payment_secret_required();
9174         features.set_basic_mpp_optional();
9175         features.set_wumbo_optional();
9176         features.set_shutdown_any_segwit_optional();
9177         features.set_channel_type_optional();
9178         features.set_scid_privacy_optional();
9179         features.set_zero_conf_optional();
9180         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
9181                 features.set_anchors_zero_fee_htlc_tx_optional();
9182         }
9183         features
9184 }
9185
9186 const SERIALIZATION_VERSION: u8 = 1;
9187 const MIN_SERIALIZATION_VERSION: u8 = 1;
9188
9189 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
9190         (2, fee_base_msat, required),
9191         (4, fee_proportional_millionths, required),
9192         (6, cltv_expiry_delta, required),
9193 });
9194
9195 impl_writeable_tlv_based!(ChannelCounterparty, {
9196         (2, node_id, required),
9197         (4, features, required),
9198         (6, unspendable_punishment_reserve, required),
9199         (8, forwarding_info, option),
9200         (9, outbound_htlc_minimum_msat, option),
9201         (11, outbound_htlc_maximum_msat, option),
9202 });
9203
9204 impl Writeable for ChannelDetails {
9205         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9206                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9207                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9208                 let user_channel_id_low = self.user_channel_id as u64;
9209                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
9210                 write_tlv_fields!(writer, {
9211                         (1, self.inbound_scid_alias, option),
9212                         (2, self.channel_id, required),
9213                         (3, self.channel_type, option),
9214                         (4, self.counterparty, required),
9215                         (5, self.outbound_scid_alias, option),
9216                         (6, self.funding_txo, option),
9217                         (7, self.config, option),
9218                         (8, self.short_channel_id, option),
9219                         (9, self.confirmations, option),
9220                         (10, self.channel_value_satoshis, required),
9221                         (12, self.unspendable_punishment_reserve, option),
9222                         (14, user_channel_id_low, required),
9223                         (16, self.balance_msat, required),
9224                         (18, self.outbound_capacity_msat, required),
9225                         (19, self.next_outbound_htlc_limit_msat, required),
9226                         (20, self.inbound_capacity_msat, required),
9227                         (21, self.next_outbound_htlc_minimum_msat, required),
9228                         (22, self.confirmations_required, option),
9229                         (24, self.force_close_spend_delay, option),
9230                         (26, self.is_outbound, required),
9231                         (28, self.is_channel_ready, required),
9232                         (30, self.is_usable, required),
9233                         (32, self.is_public, required),
9234                         (33, self.inbound_htlc_minimum_msat, option),
9235                         (35, self.inbound_htlc_maximum_msat, option),
9236                         (37, user_channel_id_high_opt, option),
9237                         (39, self.feerate_sat_per_1000_weight, option),
9238                         (41, self.channel_shutdown_state, option),
9239                 });
9240                 Ok(())
9241         }
9242 }
9243
9244 impl Readable for ChannelDetails {
9245         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9246                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9247                         (1, inbound_scid_alias, option),
9248                         (2, channel_id, required),
9249                         (3, channel_type, option),
9250                         (4, counterparty, required),
9251                         (5, outbound_scid_alias, option),
9252                         (6, funding_txo, option),
9253                         (7, config, option),
9254                         (8, short_channel_id, option),
9255                         (9, confirmations, option),
9256                         (10, channel_value_satoshis, required),
9257                         (12, unspendable_punishment_reserve, option),
9258                         (14, user_channel_id_low, required),
9259                         (16, balance_msat, required),
9260                         (18, outbound_capacity_msat, required),
9261                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
9262                         // filled in, so we can safely unwrap it here.
9263                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
9264                         (20, inbound_capacity_msat, required),
9265                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
9266                         (22, confirmations_required, option),
9267                         (24, force_close_spend_delay, option),
9268                         (26, is_outbound, required),
9269                         (28, is_channel_ready, required),
9270                         (30, is_usable, required),
9271                         (32, is_public, required),
9272                         (33, inbound_htlc_minimum_msat, option),
9273                         (35, inbound_htlc_maximum_msat, option),
9274                         (37, user_channel_id_high_opt, option),
9275                         (39, feerate_sat_per_1000_weight, option),
9276                         (41, channel_shutdown_state, option),
9277                 });
9278
9279                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9280                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9281                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
9282                 let user_channel_id = user_channel_id_low as u128 +
9283                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
9284
9285                 Ok(Self {
9286                         inbound_scid_alias,
9287                         channel_id: channel_id.0.unwrap(),
9288                         channel_type,
9289                         counterparty: counterparty.0.unwrap(),
9290                         outbound_scid_alias,
9291                         funding_txo,
9292                         config,
9293                         short_channel_id,
9294                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
9295                         unspendable_punishment_reserve,
9296                         user_channel_id,
9297                         balance_msat: balance_msat.0.unwrap(),
9298                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
9299                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
9300                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
9301                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
9302                         confirmations_required,
9303                         confirmations,
9304                         force_close_spend_delay,
9305                         is_outbound: is_outbound.0.unwrap(),
9306                         is_channel_ready: is_channel_ready.0.unwrap(),
9307                         is_usable: is_usable.0.unwrap(),
9308                         is_public: is_public.0.unwrap(),
9309                         inbound_htlc_minimum_msat,
9310                         inbound_htlc_maximum_msat,
9311                         feerate_sat_per_1000_weight,
9312                         channel_shutdown_state,
9313                 })
9314         }
9315 }
9316
9317 impl_writeable_tlv_based!(PhantomRouteHints, {
9318         (2, channels, required_vec),
9319         (4, phantom_scid, required),
9320         (6, real_node_pubkey, required),
9321 });
9322
9323 impl_writeable_tlv_based!(BlindedForward, {
9324         (0, inbound_blinding_point, required),
9325 });
9326
9327 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
9328         (0, Forward) => {
9329                 (0, onion_packet, required),
9330                 (1, blinded, option),
9331                 (2, short_channel_id, required),
9332         },
9333         (1, Receive) => {
9334                 (0, payment_data, required),
9335                 (1, phantom_shared_secret, option),
9336                 (2, incoming_cltv_expiry, required),
9337                 (3, payment_metadata, option),
9338                 (5, custom_tlvs, optional_vec),
9339         },
9340         (2, ReceiveKeysend) => {
9341                 (0, payment_preimage, required),
9342                 (2, incoming_cltv_expiry, required),
9343                 (3, payment_metadata, option),
9344                 (4, payment_data, option), // Added in 0.0.116
9345                 (5, custom_tlvs, optional_vec),
9346         },
9347 ;);
9348
9349 impl_writeable_tlv_based!(PendingHTLCInfo, {
9350         (0, routing, required),
9351         (2, incoming_shared_secret, required),
9352         (4, payment_hash, required),
9353         (6, outgoing_amt_msat, required),
9354         (8, outgoing_cltv_value, required),
9355         (9, incoming_amt_msat, option),
9356         (10, skimmed_fee_msat, option),
9357 });
9358
9359
9360 impl Writeable for HTLCFailureMsg {
9361         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9362                 match self {
9363                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9364                                 0u8.write(writer)?;
9365                                 channel_id.write(writer)?;
9366                                 htlc_id.write(writer)?;
9367                                 reason.write(writer)?;
9368                         },
9369                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9370                                 channel_id, htlc_id, sha256_of_onion, failure_code
9371                         }) => {
9372                                 1u8.write(writer)?;
9373                                 channel_id.write(writer)?;
9374                                 htlc_id.write(writer)?;
9375                                 sha256_of_onion.write(writer)?;
9376                                 failure_code.write(writer)?;
9377                         },
9378                 }
9379                 Ok(())
9380         }
9381 }
9382
9383 impl Readable for HTLCFailureMsg {
9384         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9385                 let id: u8 = Readable::read(reader)?;
9386                 match id {
9387                         0 => {
9388                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9389                                         channel_id: Readable::read(reader)?,
9390                                         htlc_id: Readable::read(reader)?,
9391                                         reason: Readable::read(reader)?,
9392                                 }))
9393                         },
9394                         1 => {
9395                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9396                                         channel_id: Readable::read(reader)?,
9397                                         htlc_id: Readable::read(reader)?,
9398                                         sha256_of_onion: Readable::read(reader)?,
9399                                         failure_code: Readable::read(reader)?,
9400                                 }))
9401                         },
9402                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9403                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9404                         // messages contained in the variants.
9405                         // In version 0.0.101, support for reading the variants with these types was added, and
9406                         // we should migrate to writing these variants when UpdateFailHTLC or
9407                         // UpdateFailMalformedHTLC get TLV fields.
9408                         2 => {
9409                                 let length: BigSize = Readable::read(reader)?;
9410                                 let mut s = FixedLengthReader::new(reader, length.0);
9411                                 let res = Readable::read(&mut s)?;
9412                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9413                                 Ok(HTLCFailureMsg::Relay(res))
9414                         },
9415                         3 => {
9416                                 let length: BigSize = Readable::read(reader)?;
9417                                 let mut s = FixedLengthReader::new(reader, length.0);
9418                                 let res = Readable::read(&mut s)?;
9419                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9420                                 Ok(HTLCFailureMsg::Malformed(res))
9421                         },
9422                         _ => Err(DecodeError::UnknownRequiredFeature),
9423                 }
9424         }
9425 }
9426
9427 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9428         (0, Forward),
9429         (1, Fail),
9430 );
9431
9432 impl_writeable_tlv_based_enum!(BlindedFailure,
9433         (0, FromIntroductionNode) => {}, ;
9434 );
9435
9436 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9437         (0, short_channel_id, required),
9438         (1, phantom_shared_secret, option),
9439         (2, outpoint, required),
9440         (3, blinded_failure, option),
9441         (4, htlc_id, required),
9442         (6, incoming_packet_shared_secret, required),
9443         (7, user_channel_id, option),
9444 });
9445
9446 impl Writeable for ClaimableHTLC {
9447         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9448                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9449                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9450                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9451                 };
9452                 write_tlv_fields!(writer, {
9453                         (0, self.prev_hop, required),
9454                         (1, self.total_msat, required),
9455                         (2, self.value, required),
9456                         (3, self.sender_intended_value, required),
9457                         (4, payment_data, option),
9458                         (5, self.total_value_received, option),
9459                         (6, self.cltv_expiry, required),
9460                         (8, keysend_preimage, option),
9461                         (10, self.counterparty_skimmed_fee_msat, option),
9462                 });
9463                 Ok(())
9464         }
9465 }
9466
9467 impl Readable for ClaimableHTLC {
9468         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9469                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9470                         (0, prev_hop, required),
9471                         (1, total_msat, option),
9472                         (2, value_ser, required),
9473                         (3, sender_intended_value, option),
9474                         (4, payment_data_opt, option),
9475                         (5, total_value_received, option),
9476                         (6, cltv_expiry, required),
9477                         (8, keysend_preimage, option),
9478                         (10, counterparty_skimmed_fee_msat, option),
9479                 });
9480                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9481                 let value = value_ser.0.unwrap();
9482                 let onion_payload = match keysend_preimage {
9483                         Some(p) => {
9484                                 if payment_data.is_some() {
9485                                         return Err(DecodeError::InvalidValue)
9486                                 }
9487                                 if total_msat.is_none() {
9488                                         total_msat = Some(value);
9489                                 }
9490                                 OnionPayload::Spontaneous(p)
9491                         },
9492                         None => {
9493                                 if total_msat.is_none() {
9494                                         if payment_data.is_none() {
9495                                                 return Err(DecodeError::InvalidValue)
9496                                         }
9497                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9498                                 }
9499                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9500                         },
9501                 };
9502                 Ok(Self {
9503                         prev_hop: prev_hop.0.unwrap(),
9504                         timer_ticks: 0,
9505                         value,
9506                         sender_intended_value: sender_intended_value.unwrap_or(value),
9507                         total_value_received,
9508                         total_msat: total_msat.unwrap(),
9509                         onion_payload,
9510                         cltv_expiry: cltv_expiry.0.unwrap(),
9511                         counterparty_skimmed_fee_msat,
9512                 })
9513         }
9514 }
9515
9516 impl Readable for HTLCSource {
9517         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9518                 let id: u8 = Readable::read(reader)?;
9519                 match id {
9520                         0 => {
9521                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9522                                 let mut first_hop_htlc_msat: u64 = 0;
9523                                 let mut path_hops = Vec::new();
9524                                 let mut payment_id = None;
9525                                 let mut payment_params: Option<PaymentParameters> = None;
9526                                 let mut blinded_tail: Option<BlindedTail> = None;
9527                                 read_tlv_fields!(reader, {
9528                                         (0, session_priv, required),
9529                                         (1, payment_id, option),
9530                                         (2, first_hop_htlc_msat, required),
9531                                         (4, path_hops, required_vec),
9532                                         (5, payment_params, (option: ReadableArgs, 0)),
9533                                         (6, blinded_tail, option),
9534                                 });
9535                                 if payment_id.is_none() {
9536                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9537                                         // instead.
9538                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9539                                 }
9540                                 let path = Path { hops: path_hops, blinded_tail };
9541                                 if path.hops.len() == 0 {
9542                                         return Err(DecodeError::InvalidValue);
9543                                 }
9544                                 if let Some(params) = payment_params.as_mut() {
9545                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9546                                                 if final_cltv_expiry_delta == &0 {
9547                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9548                                                 }
9549                                         }
9550                                 }
9551                                 Ok(HTLCSource::OutboundRoute {
9552                                         session_priv: session_priv.0.unwrap(),
9553                                         first_hop_htlc_msat,
9554                                         path,
9555                                         payment_id: payment_id.unwrap(),
9556                                 })
9557                         }
9558                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9559                         _ => Err(DecodeError::UnknownRequiredFeature),
9560                 }
9561         }
9562 }
9563
9564 impl Writeable for HTLCSource {
9565         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9566                 match self {
9567                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9568                                 0u8.write(writer)?;
9569                                 let payment_id_opt = Some(payment_id);
9570                                 write_tlv_fields!(writer, {
9571                                         (0, session_priv, required),
9572                                         (1, payment_id_opt, option),
9573                                         (2, first_hop_htlc_msat, required),
9574                                         // 3 was previously used to write a PaymentSecret for the payment.
9575                                         (4, path.hops, required_vec),
9576                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9577                                         (6, path.blinded_tail, option),
9578                                  });
9579                         }
9580                         HTLCSource::PreviousHopData(ref field) => {
9581                                 1u8.write(writer)?;
9582                                 field.write(writer)?;
9583                         }
9584                 }
9585                 Ok(())
9586         }
9587 }
9588
9589 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9590         (0, forward_info, required),
9591         (1, prev_user_channel_id, (default_value, 0)),
9592         (2, prev_short_channel_id, required),
9593         (4, prev_htlc_id, required),
9594         (6, prev_funding_outpoint, required),
9595 });
9596
9597 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
9598         (1, FailHTLC) => {
9599                 (0, htlc_id, required),
9600                 (2, err_packet, required),
9601         };
9602         (0, AddHTLC)
9603 );
9604
9605 impl_writeable_tlv_based!(PendingInboundPayment, {
9606         (0, payment_secret, required),
9607         (2, expiry_time, required),
9608         (4, user_payment_id, required),
9609         (6, payment_preimage, required),
9610         (8, min_value_msat, required),
9611 });
9612
9613 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>
9614 where
9615         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9616         T::Target: BroadcasterInterface,
9617         ES::Target: EntropySource,
9618         NS::Target: NodeSigner,
9619         SP::Target: SignerProvider,
9620         F::Target: FeeEstimator,
9621         R::Target: Router,
9622         L::Target: Logger,
9623 {
9624         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9625                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9626
9627                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9628
9629                 self.chain_hash.write(writer)?;
9630                 {
9631                         let best_block = self.best_block.read().unwrap();
9632                         best_block.height().write(writer)?;
9633                         best_block.block_hash().write(writer)?;
9634                 }
9635
9636                 let mut serializable_peer_count: u64 = 0;
9637                 {
9638                         let per_peer_state = self.per_peer_state.read().unwrap();
9639                         let mut number_of_funded_channels = 0;
9640                         for (_, peer_state_mutex) in per_peer_state.iter() {
9641                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9642                                 let peer_state = &mut *peer_state_lock;
9643                                 if !peer_state.ok_to_remove(false) {
9644                                         serializable_peer_count += 1;
9645                                 }
9646
9647                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9648                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9649                                 ).count();
9650                         }
9651
9652                         (number_of_funded_channels as u64).write(writer)?;
9653
9654                         for (_, peer_state_mutex) in per_peer_state.iter() {
9655                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9656                                 let peer_state = &mut *peer_state_lock;
9657                                 for channel in peer_state.channel_by_id.iter().filter_map(
9658                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9659                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9660                                         } else { None }
9661                                 ) {
9662                                         channel.write(writer)?;
9663                                 }
9664                         }
9665                 }
9666
9667                 {
9668                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9669                         (forward_htlcs.len() as u64).write(writer)?;
9670                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9671                                 short_channel_id.write(writer)?;
9672                                 (pending_forwards.len() as u64).write(writer)?;
9673                                 for forward in pending_forwards {
9674                                         forward.write(writer)?;
9675                                 }
9676                         }
9677                 }
9678
9679                 let per_peer_state = self.per_peer_state.write().unwrap();
9680
9681                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9682                 let claimable_payments = self.claimable_payments.lock().unwrap();
9683                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9684
9685                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9686                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9687                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9688                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9689                         payment_hash.write(writer)?;
9690                         (payment.htlcs.len() as u64).write(writer)?;
9691                         for htlc in payment.htlcs.iter() {
9692                                 htlc.write(writer)?;
9693                         }
9694                         htlc_purposes.push(&payment.purpose);
9695                         htlc_onion_fields.push(&payment.onion_fields);
9696                 }
9697
9698                 let mut monitor_update_blocked_actions_per_peer = None;
9699                 let mut peer_states = Vec::new();
9700                 for (_, peer_state_mutex) in per_peer_state.iter() {
9701                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9702                         // of a lockorder violation deadlock - no other thread can be holding any
9703                         // per_peer_state lock at all.
9704                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9705                 }
9706
9707                 (serializable_peer_count).write(writer)?;
9708                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9709                         // Peers which we have no channels to should be dropped once disconnected. As we
9710                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9711                         // consider all peers as disconnected here. There's therefore no need write peers with
9712                         // no channels.
9713                         if !peer_state.ok_to_remove(false) {
9714                                 peer_pubkey.write(writer)?;
9715                                 peer_state.latest_features.write(writer)?;
9716                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9717                                         monitor_update_blocked_actions_per_peer
9718                                                 .get_or_insert_with(Vec::new)
9719                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9720                                 }
9721                         }
9722                 }
9723
9724                 let events = self.pending_events.lock().unwrap();
9725                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9726                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9727                 // refuse to read the new ChannelManager.
9728                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9729                 if events_not_backwards_compatible {
9730                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9731                         // well save the space and not write any events here.
9732                         0u64.write(writer)?;
9733                 } else {
9734                         (events.len() as u64).write(writer)?;
9735                         for (event, _) in events.iter() {
9736                                 event.write(writer)?;
9737                         }
9738                 }
9739
9740                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
9741                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
9742                 // the closing monitor updates were always effectively replayed on startup (either directly
9743                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
9744                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
9745                 0u64.write(writer)?;
9746
9747                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
9748                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
9749                 // likely to be identical.
9750                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9751                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9752
9753                 (pending_inbound_payments.len() as u64).write(writer)?;
9754                 for (hash, pending_payment) in pending_inbound_payments.iter() {
9755                         hash.write(writer)?;
9756                         pending_payment.write(writer)?;
9757                 }
9758
9759                 // For backwards compat, write the session privs and their total length.
9760                 let mut num_pending_outbounds_compat: u64 = 0;
9761                 for (_, outbound) in pending_outbound_payments.iter() {
9762                         if !outbound.is_fulfilled() && !outbound.abandoned() {
9763                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
9764                         }
9765                 }
9766                 num_pending_outbounds_compat.write(writer)?;
9767                 for (_, outbound) in pending_outbound_payments.iter() {
9768                         match outbound {
9769                                 PendingOutboundPayment::Legacy { session_privs } |
9770                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9771                                         for session_priv in session_privs.iter() {
9772                                                 session_priv.write(writer)?;
9773                                         }
9774                                 }
9775                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
9776                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
9777                                 PendingOutboundPayment::Fulfilled { .. } => {},
9778                                 PendingOutboundPayment::Abandoned { .. } => {},
9779                         }
9780                 }
9781
9782                 // Encode without retry info for 0.0.101 compatibility.
9783                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
9784                 for (id, outbound) in pending_outbound_payments.iter() {
9785                         match outbound {
9786                                 PendingOutboundPayment::Legacy { session_privs } |
9787                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9788                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
9789                                 },
9790                                 _ => {},
9791                         }
9792                 }
9793
9794                 let mut pending_intercepted_htlcs = None;
9795                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
9796                 if our_pending_intercepts.len() != 0 {
9797                         pending_intercepted_htlcs = Some(our_pending_intercepts);
9798                 }
9799
9800                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
9801                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
9802                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
9803                         // map. Thus, if there are no entries we skip writing a TLV for it.
9804                         pending_claiming_payments = None;
9805                 }
9806
9807                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
9808                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9809                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
9810                                 if !updates.is_empty() {
9811                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
9812                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
9813                                 }
9814                         }
9815                 }
9816
9817                 write_tlv_fields!(writer, {
9818                         (1, pending_outbound_payments_no_retry, required),
9819                         (2, pending_intercepted_htlcs, option),
9820                         (3, pending_outbound_payments, required),
9821                         (4, pending_claiming_payments, option),
9822                         (5, self.our_network_pubkey, required),
9823                         (6, monitor_update_blocked_actions_per_peer, option),
9824                         (7, self.fake_scid_rand_bytes, required),
9825                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
9826                         (9, htlc_purposes, required_vec),
9827                         (10, in_flight_monitor_updates, option),
9828                         (11, self.probing_cookie_secret, required),
9829                         (13, htlc_onion_fields, optional_vec),
9830                 });
9831
9832                 Ok(())
9833         }
9834 }
9835
9836 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
9837         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9838                 (self.len() as u64).write(w)?;
9839                 for (event, action) in self.iter() {
9840                         event.write(w)?;
9841                         action.write(w)?;
9842                         #[cfg(debug_assertions)] {
9843                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
9844                                 // be persisted and are regenerated on restart. However, if such an event has a
9845                                 // post-event-handling action we'll write nothing for the event and would have to
9846                                 // either forget the action or fail on deserialization (which we do below). Thus,
9847                                 // check that the event is sane here.
9848                                 let event_encoded = event.encode();
9849                                 let event_read: Option<Event> =
9850                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
9851                                 if action.is_some() { assert!(event_read.is_some()); }
9852                         }
9853                 }
9854                 Ok(())
9855         }
9856 }
9857 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
9858         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9859                 let len: u64 = Readable::read(reader)?;
9860                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
9861                 let mut events: Self = VecDeque::with_capacity(cmp::min(
9862                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
9863                         len) as usize);
9864                 for _ in 0..len {
9865                         let ev_opt = MaybeReadable::read(reader)?;
9866                         let action = Readable::read(reader)?;
9867                         if let Some(ev) = ev_opt {
9868                                 events.push_back((ev, action));
9869                         } else if action.is_some() {
9870                                 return Err(DecodeError::InvalidValue);
9871                         }
9872                 }
9873                 Ok(events)
9874         }
9875 }
9876
9877 impl_writeable_tlv_based_enum!(ChannelShutdownState,
9878         (0, NotShuttingDown) => {},
9879         (2, ShutdownInitiated) => {},
9880         (4, ResolvingHTLCs) => {},
9881         (6, NegotiatingClosingFee) => {},
9882         (8, ShutdownComplete) => {}, ;
9883 );
9884
9885 /// Arguments for the creation of a ChannelManager that are not deserialized.
9886 ///
9887 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
9888 /// is:
9889 /// 1) Deserialize all stored [`ChannelMonitor`]s.
9890 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
9891 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
9892 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
9893 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
9894 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
9895 ///    same way you would handle a [`chain::Filter`] call using
9896 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
9897 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
9898 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
9899 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
9900 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
9901 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
9902 ///    the next step.
9903 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
9904 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
9905 ///
9906 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
9907 /// call any other methods on the newly-deserialized [`ChannelManager`].
9908 ///
9909 /// Note that because some channels may be closed during deserialization, it is critical that you
9910 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
9911 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
9912 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
9913 /// not force-close the same channels but consider them live), you may end up revoking a state for
9914 /// which you've already broadcasted the transaction.
9915 ///
9916 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
9917 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9918 where
9919         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9920         T::Target: BroadcasterInterface,
9921         ES::Target: EntropySource,
9922         NS::Target: NodeSigner,
9923         SP::Target: SignerProvider,
9924         F::Target: FeeEstimator,
9925         R::Target: Router,
9926         L::Target: Logger,
9927 {
9928         /// A cryptographically secure source of entropy.
9929         pub entropy_source: ES,
9930
9931         /// A signer that is able to perform node-scoped cryptographic operations.
9932         pub node_signer: NS,
9933
9934         /// The keys provider which will give us relevant keys. Some keys will be loaded during
9935         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
9936         /// signing data.
9937         pub signer_provider: SP,
9938
9939         /// The fee_estimator for use in the ChannelManager in the future.
9940         ///
9941         /// No calls to the FeeEstimator will be made during deserialization.
9942         pub fee_estimator: F,
9943         /// The chain::Watch for use in the ChannelManager in the future.
9944         ///
9945         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
9946         /// you have deserialized ChannelMonitors separately and will add them to your
9947         /// chain::Watch after deserializing this ChannelManager.
9948         pub chain_monitor: M,
9949
9950         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
9951         /// used to broadcast the latest local commitment transactions of channels which must be
9952         /// force-closed during deserialization.
9953         pub tx_broadcaster: T,
9954         /// The router which will be used in the ChannelManager in the future for finding routes
9955         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
9956         ///
9957         /// No calls to the router will be made during deserialization.
9958         pub router: R,
9959         /// The Logger for use in the ChannelManager and which may be used to log information during
9960         /// deserialization.
9961         pub logger: L,
9962         /// Default settings used for new channels. Any existing channels will continue to use the
9963         /// runtime settings which were stored when the ChannelManager was serialized.
9964         pub default_config: UserConfig,
9965
9966         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
9967         /// value.context.get_funding_txo() should be the key).
9968         ///
9969         /// If a monitor is inconsistent with the channel state during deserialization the channel will
9970         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
9971         /// is true for missing channels as well. If there is a monitor missing for which we find
9972         /// channel data Err(DecodeError::InvalidValue) will be returned.
9973         ///
9974         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
9975         /// this struct.
9976         ///
9977         /// This is not exported to bindings users because we have no HashMap bindings
9978         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>,
9979 }
9980
9981 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9982                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
9983 where
9984         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9985         T::Target: BroadcasterInterface,
9986         ES::Target: EntropySource,
9987         NS::Target: NodeSigner,
9988         SP::Target: SignerProvider,
9989         F::Target: FeeEstimator,
9990         R::Target: Router,
9991         L::Target: Logger,
9992 {
9993         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
9994         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
9995         /// populate a HashMap directly from C.
9996         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,
9997                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>) -> Self {
9998                 Self {
9999                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
10000                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
10001                 }
10002         }
10003 }
10004
10005 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
10006 // SipmleArcChannelManager type:
10007 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10008         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
10009 where
10010         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10011         T::Target: BroadcasterInterface,
10012         ES::Target: EntropySource,
10013         NS::Target: NodeSigner,
10014         SP::Target: SignerProvider,
10015         F::Target: FeeEstimator,
10016         R::Target: Router,
10017         L::Target: Logger,
10018 {
10019         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10020                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
10021                 Ok((blockhash, Arc::new(chan_manager)))
10022         }
10023 }
10024
10025 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10026         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
10027 where
10028         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10029         T::Target: BroadcasterInterface,
10030         ES::Target: EntropySource,
10031         NS::Target: NodeSigner,
10032         SP::Target: SignerProvider,
10033         F::Target: FeeEstimator,
10034         R::Target: Router,
10035         L::Target: Logger,
10036 {
10037         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10038                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
10039
10040                 let chain_hash: ChainHash = Readable::read(reader)?;
10041                 let best_block_height: u32 = Readable::read(reader)?;
10042                 let best_block_hash: BlockHash = Readable::read(reader)?;
10043
10044                 let mut failed_htlcs = Vec::new();
10045
10046                 let channel_count: u64 = Readable::read(reader)?;
10047                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
10048                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10049                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10050                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10051                 let mut channel_closures = VecDeque::new();
10052                 let mut close_background_events = Vec::new();
10053                 for _ in 0..channel_count {
10054                         let mut channel: Channel<SP> = Channel::read(reader, (
10055                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
10056                         ))?;
10057                         let logger = WithChannelContext::from(&args.logger, &channel.context);
10058                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10059                         funding_txo_set.insert(funding_txo.clone());
10060                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10061                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
10062                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
10063                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
10064                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10065                                         // But if the channel is behind of the monitor, close the channel:
10066                                         log_error!(logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
10067                                         log_error!(logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
10068                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10069                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
10070                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
10071                                         }
10072                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
10073                                                 log_error!(logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
10074                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
10075                                         }
10076                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
10077                                                 log_error!(logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
10078                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
10079                                         }
10080                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
10081                                                 log_error!(logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
10082                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
10083                                         }
10084                                         let mut shutdown_result = channel.context.force_shutdown(true);
10085                                         if shutdown_result.unbroadcasted_batch_funding_txid.is_some() {
10086                                                 return Err(DecodeError::InvalidValue);
10087                                         }
10088                                         if let Some((counterparty_node_id, funding_txo, update)) = shutdown_result.monitor_update {
10089                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10090                                                         counterparty_node_id, funding_txo, update
10091                                                 });
10092                                         }
10093                                         failed_htlcs.append(&mut shutdown_result.dropped_outbound_htlcs);
10094                                         channel_closures.push_back((events::Event::ChannelClosed {
10095                                                 channel_id: channel.context.channel_id(),
10096                                                 user_channel_id: channel.context.get_user_id(),
10097                                                 reason: ClosureReason::OutdatedChannelManager,
10098                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10099                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10100                                         }, None));
10101                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
10102                                                 let mut found_htlc = false;
10103                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
10104                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
10105                                                 }
10106                                                 if !found_htlc {
10107                                                         // If we have some HTLCs in the channel which are not present in the newer
10108                                                         // ChannelMonitor, they have been removed and should be failed back to
10109                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
10110                                                         // were actually claimed we'd have generated and ensured the previous-hop
10111                                                         // claim update ChannelMonitor updates were persisted prior to persising
10112                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
10113                                                         // backwards leg of the HTLC will simply be rejected.
10114                                                         log_info!(logger,
10115                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
10116                                                                 &channel.context.channel_id(), &payment_hash);
10117                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10118                                                 }
10119                                         }
10120                                 } else {
10121                                         log_info!(logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
10122                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
10123                                                 monitor.get_latest_update_id());
10124                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
10125                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10126                                         }
10127                                         if channel.context.is_funding_broadcast() {
10128                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
10129                                         }
10130                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
10131                                                 hash_map::Entry::Occupied(mut entry) => {
10132                                                         let by_id_map = entry.get_mut();
10133                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10134                                                 },
10135                                                 hash_map::Entry::Vacant(entry) => {
10136                                                         let mut by_id_map = HashMap::new();
10137                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10138                                                         entry.insert(by_id_map);
10139                                                 }
10140                                         }
10141                                 }
10142                         } else if channel.is_awaiting_initial_mon_persist() {
10143                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
10144                                 // was in-progress, we never broadcasted the funding transaction and can still
10145                                 // safely discard the channel.
10146                                 let _ = channel.context.force_shutdown(false);
10147                                 channel_closures.push_back((events::Event::ChannelClosed {
10148                                         channel_id: channel.context.channel_id(),
10149                                         user_channel_id: channel.context.get_user_id(),
10150                                         reason: ClosureReason::DisconnectedPeer,
10151                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10152                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10153                                 }, None));
10154                         } else {
10155                                 log_error!(logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
10156                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10157                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10158                                 log_error!(logger, " Without the ChannelMonitor we cannot continue without risking funds.");
10159                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10160                                 return Err(DecodeError::InvalidValue);
10161                         }
10162                 }
10163
10164                 for (funding_txo, monitor) in args.channel_monitors.iter() {
10165                         if !funding_txo_set.contains(funding_txo) {
10166                                 let logger = WithChannelMonitor::from(&args.logger, monitor);
10167                                 log_info!(logger, "Queueing monitor update to ensure missing channel {} is force closed",
10168                                         &funding_txo.to_channel_id());
10169                                 let monitor_update = ChannelMonitorUpdate {
10170                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
10171                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
10172                                 };
10173                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
10174                         }
10175                 }
10176
10177                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
10178                 let forward_htlcs_count: u64 = Readable::read(reader)?;
10179                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
10180                 for _ in 0..forward_htlcs_count {
10181                         let short_channel_id = Readable::read(reader)?;
10182                         let pending_forwards_count: u64 = Readable::read(reader)?;
10183                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
10184                         for _ in 0..pending_forwards_count {
10185                                 pending_forwards.push(Readable::read(reader)?);
10186                         }
10187                         forward_htlcs.insert(short_channel_id, pending_forwards);
10188                 }
10189
10190                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
10191                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
10192                 for _ in 0..claimable_htlcs_count {
10193                         let payment_hash = Readable::read(reader)?;
10194                         let previous_hops_len: u64 = Readable::read(reader)?;
10195                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
10196                         for _ in 0..previous_hops_len {
10197                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
10198                         }
10199                         claimable_htlcs_list.push((payment_hash, previous_hops));
10200                 }
10201
10202                 let peer_state_from_chans = |channel_by_id| {
10203                         PeerState {
10204                                 channel_by_id,
10205                                 inbound_channel_request_by_id: HashMap::new(),
10206                                 latest_features: InitFeatures::empty(),
10207                                 pending_msg_events: Vec::new(),
10208                                 in_flight_monitor_updates: BTreeMap::new(),
10209                                 monitor_update_blocked_actions: BTreeMap::new(),
10210                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
10211                                 is_connected: false,
10212                         }
10213                 };
10214
10215                 let peer_count: u64 = Readable::read(reader)?;
10216                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
10217                 for _ in 0..peer_count {
10218                         let peer_pubkey = Readable::read(reader)?;
10219                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
10220                         let mut peer_state = peer_state_from_chans(peer_chans);
10221                         peer_state.latest_features = Readable::read(reader)?;
10222                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
10223                 }
10224
10225                 let event_count: u64 = Readable::read(reader)?;
10226                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
10227                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
10228                 for _ in 0..event_count {
10229                         match MaybeReadable::read(reader)? {
10230                                 Some(event) => pending_events_read.push_back((event, None)),
10231                                 None => continue,
10232                         }
10233                 }
10234
10235                 let background_event_count: u64 = Readable::read(reader)?;
10236                 for _ in 0..background_event_count {
10237                         match <u8 as Readable>::read(reader)? {
10238                                 0 => {
10239                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
10240                                         // however we really don't (and never did) need them - we regenerate all
10241                                         // on-startup monitor updates.
10242                                         let _: OutPoint = Readable::read(reader)?;
10243                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
10244                                 }
10245                                 _ => return Err(DecodeError::InvalidValue),
10246                         }
10247                 }
10248
10249                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
10250                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
10251
10252                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
10253                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
10254                 for _ in 0..pending_inbound_payment_count {
10255                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
10256                                 return Err(DecodeError::InvalidValue);
10257                         }
10258                 }
10259
10260                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
10261                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
10262                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
10263                 for _ in 0..pending_outbound_payments_count_compat {
10264                         let session_priv = Readable::read(reader)?;
10265                         let payment = PendingOutboundPayment::Legacy {
10266                                 session_privs: [session_priv].iter().cloned().collect()
10267                         };
10268                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
10269                                 return Err(DecodeError::InvalidValue)
10270                         };
10271                 }
10272
10273                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
10274                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
10275                 let mut pending_outbound_payments = None;
10276                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
10277                 let mut received_network_pubkey: Option<PublicKey> = None;
10278                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
10279                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
10280                 let mut claimable_htlc_purposes = None;
10281                 let mut claimable_htlc_onion_fields = None;
10282                 let mut pending_claiming_payments = Some(HashMap::new());
10283                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
10284                 let mut events_override = None;
10285                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
10286                 read_tlv_fields!(reader, {
10287                         (1, pending_outbound_payments_no_retry, option),
10288                         (2, pending_intercepted_htlcs, option),
10289                         (3, pending_outbound_payments, option),
10290                         (4, pending_claiming_payments, option),
10291                         (5, received_network_pubkey, option),
10292                         (6, monitor_update_blocked_actions_per_peer, option),
10293                         (7, fake_scid_rand_bytes, option),
10294                         (8, events_override, option),
10295                         (9, claimable_htlc_purposes, optional_vec),
10296                         (10, in_flight_monitor_updates, option),
10297                         (11, probing_cookie_secret, option),
10298                         (13, claimable_htlc_onion_fields, optional_vec),
10299                 });
10300                 if fake_scid_rand_bytes.is_none() {
10301                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
10302                 }
10303
10304                 if probing_cookie_secret.is_none() {
10305                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
10306                 }
10307
10308                 if let Some(events) = events_override {
10309                         pending_events_read = events;
10310                 }
10311
10312                 if !channel_closures.is_empty() {
10313                         pending_events_read.append(&mut channel_closures);
10314                 }
10315
10316                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
10317                         pending_outbound_payments = Some(pending_outbound_payments_compat);
10318                 } else if pending_outbound_payments.is_none() {
10319                         let mut outbounds = HashMap::new();
10320                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
10321                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
10322                         }
10323                         pending_outbound_payments = Some(outbounds);
10324                 }
10325                 let pending_outbounds = OutboundPayments {
10326                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
10327                         retry_lock: Mutex::new(())
10328                 };
10329
10330                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
10331                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
10332                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
10333                 // replayed, and for each monitor update we have to replay we have to ensure there's a
10334                 // `ChannelMonitor` for it.
10335                 //
10336                 // In order to do so we first walk all of our live channels (so that we can check their
10337                 // state immediately after doing the update replays, when we have the `update_id`s
10338                 // available) and then walk any remaining in-flight updates.
10339                 //
10340                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10341                 let mut pending_background_events = Vec::new();
10342                 macro_rules! handle_in_flight_updates {
10343                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10344                          $monitor: expr, $peer_state: expr, $logger: expr, $channel_info_log: expr
10345                         ) => { {
10346                                 let mut max_in_flight_update_id = 0;
10347                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10348                                 for update in $chan_in_flight_upds.iter() {
10349                                         log_trace!($logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10350                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
10351                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10352                                         pending_background_events.push(
10353                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10354                                                         counterparty_node_id: $counterparty_node_id,
10355                                                         funding_txo: $funding_txo,
10356                                                         update: update.clone(),
10357                                                 });
10358                                 }
10359                                 if $chan_in_flight_upds.is_empty() {
10360                                         // We had some updates to apply, but it turns out they had completed before we
10361                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10362                                         // the completion actions for any monitor updates, but otherwise are done.
10363                                         pending_background_events.push(
10364                                                 BackgroundEvent::MonitorUpdatesComplete {
10365                                                         counterparty_node_id: $counterparty_node_id,
10366                                                         channel_id: $funding_txo.to_channel_id(),
10367                                                 });
10368                                 }
10369                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10370                                         log_error!($logger, "Duplicate in-flight monitor update set for the same channel!");
10371                                         return Err(DecodeError::InvalidValue);
10372                                 }
10373                                 max_in_flight_update_id
10374                         } }
10375                 }
10376
10377                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10378                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10379                         let peer_state = &mut *peer_state_lock;
10380                         for phase in peer_state.channel_by_id.values() {
10381                                 if let ChannelPhase::Funded(chan) = phase {
10382                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10383
10384                                         // Channels that were persisted have to be funded, otherwise they should have been
10385                                         // discarded.
10386                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10387                                         let monitor = args.channel_monitors.get(&funding_txo)
10388                                                 .expect("We already checked for monitor presence when loading channels");
10389                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10390                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10391                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10392                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10393                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10394                                                                         funding_txo, monitor, peer_state, logger, ""));
10395                                                 }
10396                                         }
10397                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10398                                                 // If the channel is ahead of the monitor, return InvalidValue:
10399                                                 log_error!(logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10400                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10401                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10402                                                 log_error!(logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10403                                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10404                                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10405                                                 log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10406                                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10407                                                 return Err(DecodeError::InvalidValue);
10408                                         }
10409                                 } else {
10410                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10411                                         // created in this `channel_by_id` map.
10412                                         debug_assert!(false);
10413                                         return Err(DecodeError::InvalidValue);
10414                                 }
10415                         }
10416                 }
10417
10418                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10419                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10420                                 let logger = WithContext::from(&args.logger, Some(counterparty_id), Some(funding_txo.to_channel_id()));
10421                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10422                                         // Now that we've removed all the in-flight monitor updates for channels that are
10423                                         // still open, we need to replay any monitor updates that are for closed channels,
10424                                         // creating the neccessary peer_state entries as we go.
10425                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10426                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
10427                                         });
10428                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10429                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10430                                                 funding_txo, monitor, peer_state, logger, "closed ");
10431                                 } else {
10432                                         log_error!(logger, "A ChannelMonitor is missing even though we have in-flight updates for it! This indicates a potentially-critical violation of the chain::Watch API!");
10433                                         log_error!(logger, " The ChannelMonitor for channel {} is missing.",
10434                                                 &funding_txo.to_channel_id());
10435                                         log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10436                                         log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10437                                         log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10438                                         log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10439                                         return Err(DecodeError::InvalidValue);
10440                                 }
10441                         }
10442                 }
10443
10444                 // Note that we have to do the above replays before we push new monitor updates.
10445                 pending_background_events.append(&mut close_background_events);
10446
10447                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10448                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10449                 // have a fully-constructed `ChannelManager` at the end.
10450                 let mut pending_claims_to_replay = Vec::new();
10451
10452                 {
10453                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10454                         // ChannelMonitor data for any channels for which we do not have authorative state
10455                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10456                         // corresponding `Channel` at all).
10457                         // This avoids several edge-cases where we would otherwise "forget" about pending
10458                         // payments which are still in-flight via their on-chain state.
10459                         // We only rebuild the pending payments map if we were most recently serialized by
10460                         // 0.0.102+
10461                         for (_, monitor) in args.channel_monitors.iter() {
10462                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
10463                                 let chan_id = monitor.get_funding_txo().0.to_channel_id();
10464                                 if counterparty_opt.is_none() {
10465                                         let logger = WithChannelMonitor::from(&args.logger, monitor);
10466                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10467                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10468                                                         if path.hops.is_empty() {
10469                                                                 log_error!(logger, "Got an empty path for a pending payment");
10470                                                                 return Err(DecodeError::InvalidValue);
10471                                                         }
10472
10473                                                         let path_amt = path.final_value_msat();
10474                                                         let mut session_priv_bytes = [0; 32];
10475                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10476                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10477                                                                 hash_map::Entry::Occupied(mut entry) => {
10478                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10479                                                                         log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10480                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), log_bytes!(htlc.payment_hash.0));
10481                                                                 },
10482                                                                 hash_map::Entry::Vacant(entry) => {
10483                                                                         let path_fee = path.fee_msat();
10484                                                                         entry.insert(PendingOutboundPayment::Retryable {
10485                                                                                 retry_strategy: None,
10486                                                                                 attempts: PaymentAttempts::new(),
10487                                                                                 payment_params: None,
10488                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
10489                                                                                 payment_hash: htlc.payment_hash,
10490                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10491                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10492                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10493                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10494                                                                                 pending_amt_msat: path_amt,
10495                                                                                 pending_fee_msat: Some(path_fee),
10496                                                                                 total_msat: path_amt,
10497                                                                                 starting_block_height: best_block_height,
10498                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10499                                                                         });
10500                                                                         log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10501                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10502                                                                 }
10503                                                         }
10504                                                 }
10505                                         }
10506                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10507                                                 match htlc_source {
10508                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10509                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10510                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10511                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10512                                                                 };
10513                                                                 // The ChannelMonitor is now responsible for this HTLC's
10514                                                                 // failure/success and will let us know what its outcome is. If we
10515                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10516                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10517                                                                 // the monitor was when forwarding the payment.
10518                                                                 forward_htlcs.retain(|_, forwards| {
10519                                                                         forwards.retain(|forward| {
10520                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10521                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10522                                                                                                 log_info!(logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10523                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10524                                                                                                 false
10525                                                                                         } else { true }
10526                                                                                 } else { true }
10527                                                                         });
10528                                                                         !forwards.is_empty()
10529                                                                 });
10530                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10531                                                                         if pending_forward_matches_htlc(&htlc_info) {
10532                                                                                 log_info!(logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10533                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10534                                                                                 pending_events_read.retain(|(event, _)| {
10535                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10536                                                                                                 intercepted_id != ev_id
10537                                                                                         } else { true }
10538                                                                                 });
10539                                                                                 false
10540                                                                         } else { true }
10541                                                                 });
10542                                                         },
10543                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10544                                                                 if let Some(preimage) = preimage_opt {
10545                                                                         let pending_events = Mutex::new(pending_events_read);
10546                                                                         // Note that we set `from_onchain` to "false" here,
10547                                                                         // deliberately keeping the pending payment around forever.
10548                                                                         // Given it should only occur when we have a channel we're
10549                                                                         // force-closing for being stale that's okay.
10550                                                                         // The alternative would be to wipe the state when claiming,
10551                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10552                                                                         // it and the `PaymentSent` on every restart until the
10553                                                                         // `ChannelMonitor` is removed.
10554                                                                         let compl_action =
10555                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10556                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10557                                                                                         counterparty_node_id: path.hops[0].pubkey,
10558                                                                                 };
10559                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10560                                                                                 path, false, compl_action, &pending_events, &&logger);
10561                                                                         pending_events_read = pending_events.into_inner().unwrap();
10562                                                                 }
10563                                                         },
10564                                                 }
10565                                         }
10566                                 }
10567
10568                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10569                                 // preimages from it which may be needed in upstream channels for forwarded
10570                                 // payments.
10571                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10572                                         .into_iter()
10573                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10574                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10575                                                         if let Some(payment_preimage) = preimage_opt {
10576                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10577                                                                         // Check if `counterparty_opt.is_none()` to see if the
10578                                                                         // downstream chan is closed (because we don't have a
10579                                                                         // channel_id -> peer map entry).
10580                                                                         counterparty_opt.is_none(),
10581                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10582                                                                         monitor.get_funding_txo().0))
10583                                                         } else { None }
10584                                                 } else {
10585                                                         // If it was an outbound payment, we've handled it above - if a preimage
10586                                                         // came in and we persisted the `ChannelManager` we either handled it and
10587                                                         // are good to go or the channel force-closed - we don't have to handle the
10588                                                         // channel still live case here.
10589                                                         None
10590                                                 }
10591                                         });
10592                                 for tuple in outbound_claimed_htlcs_iter {
10593                                         pending_claims_to_replay.push(tuple);
10594                                 }
10595                         }
10596                 }
10597
10598                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10599                         // If we have pending HTLCs to forward, assume we either dropped a
10600                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10601                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10602                         // constant as enough time has likely passed that we should simply handle the forwards
10603                         // now, or at least after the user gets a chance to reconnect to our peers.
10604                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10605                                 time_forwardable: Duration::from_secs(2),
10606                         }, None));
10607                 }
10608
10609                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10610                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10611
10612                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10613                 if let Some(purposes) = claimable_htlc_purposes {
10614                         if purposes.len() != claimable_htlcs_list.len() {
10615                                 return Err(DecodeError::InvalidValue);
10616                         }
10617                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10618                                 if onion_fields.len() != claimable_htlcs_list.len() {
10619                                         return Err(DecodeError::InvalidValue);
10620                                 }
10621                                 for (purpose, (onion, (payment_hash, htlcs))) in
10622                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10623                                 {
10624                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10625                                                 purpose, htlcs, onion_fields: onion,
10626                                         });
10627                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10628                                 }
10629                         } else {
10630                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10631                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10632                                                 purpose, htlcs, onion_fields: None,
10633                                         });
10634                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10635                                 }
10636                         }
10637                 } else {
10638                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10639                         // include a `_legacy_hop_data` in the `OnionPayload`.
10640                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10641                                 if htlcs.is_empty() {
10642                                         return Err(DecodeError::InvalidValue);
10643                                 }
10644                                 let purpose = match &htlcs[0].onion_payload {
10645                                         OnionPayload::Invoice { _legacy_hop_data } => {
10646                                                 if let Some(hop_data) = _legacy_hop_data {
10647                                                         events::PaymentPurpose::InvoicePayment {
10648                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10649                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10650                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10651                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10652                                                                                 Err(()) => {
10653                                                                                         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);
10654                                                                                         return Err(DecodeError::InvalidValue);
10655                                                                                 }
10656                                                                         }
10657                                                                 },
10658                                                                 payment_secret: hop_data.payment_secret,
10659                                                         }
10660                                                 } else { return Err(DecodeError::InvalidValue); }
10661                                         },
10662                                         OnionPayload::Spontaneous(payment_preimage) =>
10663                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10664                                 };
10665                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10666                                         purpose, htlcs, onion_fields: None,
10667                                 });
10668                         }
10669                 }
10670
10671                 let mut secp_ctx = Secp256k1::new();
10672                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10673
10674                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10675                         Ok(key) => key,
10676                         Err(()) => return Err(DecodeError::InvalidValue)
10677                 };
10678                 if let Some(network_pubkey) = received_network_pubkey {
10679                         if network_pubkey != our_network_pubkey {
10680                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10681                                 return Err(DecodeError::InvalidValue);
10682                         }
10683                 }
10684
10685                 let mut outbound_scid_aliases = HashSet::new();
10686                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10687                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10688                         let peer_state = &mut *peer_state_lock;
10689                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10690                                 if let ChannelPhase::Funded(chan) = phase {
10691                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10692                                         if chan.context.outbound_scid_alias() == 0 {
10693                                                 let mut outbound_scid_alias;
10694                                                 loop {
10695                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10696                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10697                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10698                                                 }
10699                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10700                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10701                                                 // Note that in rare cases its possible to hit this while reading an older
10702                                                 // channel if we just happened to pick a colliding outbound alias above.
10703                                                 log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10704                                                 return Err(DecodeError::InvalidValue);
10705                                         }
10706                                         if chan.context.is_usable() {
10707                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10708                                                         // Note that in rare cases its possible to hit this while reading an older
10709                                                         // channel if we just happened to pick a colliding outbound alias above.
10710                                                         log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10711                                                         return Err(DecodeError::InvalidValue);
10712                                                 }
10713                                         }
10714                                 } else {
10715                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10716                                         // created in this `channel_by_id` map.
10717                                         debug_assert!(false);
10718                                         return Err(DecodeError::InvalidValue);
10719                                 }
10720                         }
10721                 }
10722
10723                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10724
10725                 for (_, monitor) in args.channel_monitors.iter() {
10726                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10727                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10728                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10729                                         let mut claimable_amt_msat = 0;
10730                                         let mut receiver_node_id = Some(our_network_pubkey);
10731                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
10732                                         if phantom_shared_secret.is_some() {
10733                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
10734                                                         .expect("Failed to get node_id for phantom node recipient");
10735                                                 receiver_node_id = Some(phantom_pubkey)
10736                                         }
10737                                         for claimable_htlc in &payment.htlcs {
10738                                                 claimable_amt_msat += claimable_htlc.value;
10739
10740                                                 // Add a holding-cell claim of the payment to the Channel, which should be
10741                                                 // applied ~immediately on peer reconnection. Because it won't generate a
10742                                                 // new commitment transaction we can just provide the payment preimage to
10743                                                 // the corresponding ChannelMonitor and nothing else.
10744                                                 //
10745                                                 // We do so directly instead of via the normal ChannelMonitor update
10746                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
10747                                                 // we're not allowed to call it directly yet. Further, we do the update
10748                                                 // without incrementing the ChannelMonitor update ID as there isn't any
10749                                                 // reason to.
10750                                                 // If we were to generate a new ChannelMonitor update ID here and then
10751                                                 // crash before the user finishes block connect we'd end up force-closing
10752                                                 // this channel as well. On the flip side, there's no harm in restarting
10753                                                 // without the new monitor persisted - we'll end up right back here on
10754                                                 // restart.
10755                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
10756                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
10757                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
10758                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10759                                                         let peer_state = &mut *peer_state_lock;
10760                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
10761                                                                 let logger = WithChannelContext::from(&args.logger, &channel.context);
10762                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &&logger);
10763                                                         }
10764                                                 }
10765                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
10766                                                         let logger = WithChannelMonitor::from(&args.logger, previous_hop_monitor);
10767                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &&logger);
10768                                                 }
10769                                         }
10770                                         pending_events_read.push_back((events::Event::PaymentClaimed {
10771                                                 receiver_node_id,
10772                                                 payment_hash,
10773                                                 purpose: payment.purpose,
10774                                                 amount_msat: claimable_amt_msat,
10775                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
10776                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
10777                                         }, None));
10778                                 }
10779                         }
10780                 }
10781
10782                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
10783                         if let Some(peer_state) = per_peer_state.get(&node_id) {
10784                                 for (channel_id, actions) in monitor_update_blocked_actions.iter() {
10785                                         let logger = WithContext::from(&args.logger, Some(node_id), Some(*channel_id));
10786                                         for action in actions.iter() {
10787                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
10788                                                         downstream_counterparty_and_funding_outpoint:
10789                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
10790                                                 } = action {
10791                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
10792                                                                 log_trace!(logger,
10793                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
10794                                                                         blocked_channel_outpoint.to_channel_id());
10795                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
10796                                                                         .entry(blocked_channel_outpoint.to_channel_id())
10797                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
10798                                                         } else {
10799                                                                 // If the channel we were blocking has closed, we don't need to
10800                                                                 // worry about it - the blocked monitor update should never have
10801                                                                 // been released from the `Channel` object so it can't have
10802                                                                 // completed, and if the channel closed there's no reason to bother
10803                                                                 // anymore.
10804                                                         }
10805                                                 }
10806                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
10807                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
10808                                                 }
10809                                         }
10810                                 }
10811                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
10812                         } else {
10813                                 log_error!(WithContext::from(&args.logger, Some(node_id), None), "Got blocked actions without a per-peer-state for {}", node_id);
10814                                 return Err(DecodeError::InvalidValue);
10815                         }
10816                 }
10817
10818                 let channel_manager = ChannelManager {
10819                         chain_hash,
10820                         fee_estimator: bounded_fee_estimator,
10821                         chain_monitor: args.chain_monitor,
10822                         tx_broadcaster: args.tx_broadcaster,
10823                         router: args.router,
10824
10825                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
10826
10827                         inbound_payment_key: expanded_inbound_key,
10828                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
10829                         pending_outbound_payments: pending_outbounds,
10830                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
10831
10832                         forward_htlcs: Mutex::new(forward_htlcs),
10833                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
10834                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
10835                         id_to_peer: Mutex::new(id_to_peer),
10836                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
10837                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
10838
10839                         probing_cookie_secret: probing_cookie_secret.unwrap(),
10840
10841                         our_network_pubkey,
10842                         secp_ctx,
10843
10844                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
10845
10846                         per_peer_state: FairRwLock::new(per_peer_state),
10847
10848                         pending_events: Mutex::new(pending_events_read),
10849                         pending_events_processor: AtomicBool::new(false),
10850                         pending_background_events: Mutex::new(pending_background_events),
10851                         total_consistency_lock: RwLock::new(()),
10852                         background_events_processed_since_startup: AtomicBool::new(false),
10853
10854                         event_persist_notifier: Notifier::new(),
10855                         needs_persist_flag: AtomicBool::new(false),
10856
10857                         funding_batch_states: Mutex::new(BTreeMap::new()),
10858
10859                         pending_offers_messages: Mutex::new(Vec::new()),
10860
10861                         entropy_source: args.entropy_source,
10862                         node_signer: args.node_signer,
10863                         signer_provider: args.signer_provider,
10864
10865                         logger: args.logger,
10866                         default_configuration: args.default_config,
10867                 };
10868
10869                 for htlc_source in failed_htlcs.drain(..) {
10870                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
10871                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
10872                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
10873                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
10874                 }
10875
10876                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
10877                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
10878                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
10879                         // channel is closed we just assume that it probably came from an on-chain claim.
10880                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
10881                                 downstream_closed, true, downstream_node_id, downstream_funding);
10882                 }
10883
10884                 //TODO: Broadcast channel update for closed channels, but only after we've made a
10885                 //connection or two.
10886
10887                 Ok((best_block_hash.clone(), channel_manager))
10888         }
10889 }
10890
10891 #[cfg(test)]
10892 mod tests {
10893         use bitcoin::hashes::Hash;
10894         use bitcoin::hashes::sha256::Hash as Sha256;
10895         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10896         use core::sync::atomic::Ordering;
10897         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
10898         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
10899         use crate::ln::ChannelId;
10900         use crate::ln::channelmanager::{create_recv_pending_htlc_info, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
10901         use crate::ln::functional_test_utils::*;
10902         use crate::ln::msgs::{self, ErrorAction};
10903         use crate::ln::msgs::ChannelMessageHandler;
10904         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
10905         use crate::util::errors::APIError;
10906         use crate::util::test_utils;
10907         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
10908         use crate::sign::EntropySource;
10909
10910         #[test]
10911         fn test_notify_limits() {
10912                 // Check that a few cases which don't require the persistence of a new ChannelManager,
10913                 // indeed, do not cause the persistence of a new ChannelManager.
10914                 let chanmon_cfgs = create_chanmon_cfgs(3);
10915                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10916                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10917                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10918
10919                 // All nodes start with a persistable update pending as `create_network` connects each node
10920                 // with all other nodes to make most tests simpler.
10921                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10922                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10923                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10924
10925                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10926
10927                 // We check that the channel info nodes have doesn't change too early, even though we try
10928                 // to connect messages with new values
10929                 chan.0.contents.fee_base_msat *= 2;
10930                 chan.1.contents.fee_base_msat *= 2;
10931                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
10932                         &nodes[1].node.get_our_node_id()).pop().unwrap();
10933                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
10934                         &nodes[0].node.get_our_node_id()).pop().unwrap();
10935
10936                 // The first two nodes (which opened a channel) should now require fresh persistence
10937                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10938                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10939                 // ... but the last node should not.
10940                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10941                 // After persisting the first two nodes they should no longer need fresh persistence.
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
10945                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
10946                 // about the channel.
10947                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
10948                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
10949                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10950
10951                 // The nodes which are a party to the channel should also ignore messages from unrelated
10952                 // parties.
10953                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10954                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10955                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10956                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10957                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10958                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10959
10960                 // At this point the channel info given by peers should still be the same.
10961                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10962                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10963
10964                 // An earlier version of handle_channel_update didn't check the directionality of the
10965                 // update message and would always update the local fee info, even if our peer was
10966                 // (spuriously) forwarding us our own channel_update.
10967                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
10968                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
10969                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
10970
10971                 // First deliver each peers' own message, checking that the node doesn't need to be
10972                 // persisted and that its channel info remains the same.
10973                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
10974                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
10975                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10976                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10977                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10978                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10979
10980                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
10981                 // the channel info has updated.
10982                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
10983                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
10984                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10985                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10986                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
10987                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
10988         }
10989
10990         #[test]
10991         fn test_keysend_dup_hash_partial_mpp() {
10992                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
10993                 // expected.
10994                 let chanmon_cfgs = create_chanmon_cfgs(2);
10995                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10996                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10997                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10998                 create_announced_chan_between_nodes(&nodes, 0, 1);
10999
11000                 // First, send a partial MPP payment.
11001                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
11002                 let mut mpp_route = route.clone();
11003                 mpp_route.paths.push(mpp_route.paths[0].clone());
11004
11005                 let payment_id = PaymentId([42; 32]);
11006                 // Use the utility function send_payment_along_path to send the payment with MPP data which
11007                 // indicates there are more HTLCs coming.
11008                 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.
11009                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
11010                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
11011                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
11012                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
11013                 check_added_monitors!(nodes[0], 1);
11014                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11015                 assert_eq!(events.len(), 1);
11016                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
11017
11018                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
11019                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11020                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11021                 check_added_monitors!(nodes[0], 1);
11022                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11023                 assert_eq!(events.len(), 1);
11024                 let ev = events.drain(..).next().unwrap();
11025                 let payment_event = SendEvent::from_event(ev);
11026                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11027                 check_added_monitors!(nodes[1], 0);
11028                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11029                 expect_pending_htlcs_forwardable!(nodes[1]);
11030                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
11031                 check_added_monitors!(nodes[1], 1);
11032                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11033                 assert!(updates.update_add_htlcs.is_empty());
11034                 assert!(updates.update_fulfill_htlcs.is_empty());
11035                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11036                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11037                 assert!(updates.update_fee.is_none());
11038                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11039                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11040                 expect_payment_failed!(nodes[0], our_payment_hash, true);
11041
11042                 // Send the second half of the original MPP payment.
11043                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
11044                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
11045                 check_added_monitors!(nodes[0], 1);
11046                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11047                 assert_eq!(events.len(), 1);
11048                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
11049
11050                 // Claim the full MPP payment. Note that we can't use a test utility like
11051                 // claim_funds_along_route because the ordering of the messages causes the second half of the
11052                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
11053                 // lightning messages manually.
11054                 nodes[1].node.claim_funds(payment_preimage);
11055                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
11056                 check_added_monitors!(nodes[1], 2);
11057
11058                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11059                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
11060                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
11061                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
11062                 check_added_monitors!(nodes[0], 1);
11063                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11064                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
11065                 check_added_monitors!(nodes[1], 1);
11066                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11067                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
11068                 check_added_monitors!(nodes[1], 1);
11069                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11070                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
11071                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
11072                 check_added_monitors!(nodes[0], 1);
11073                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
11074                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
11075                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11076                 check_added_monitors!(nodes[0], 1);
11077                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
11078                 check_added_monitors!(nodes[1], 1);
11079                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
11080                 check_added_monitors!(nodes[1], 1);
11081                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11082                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
11083                 check_added_monitors!(nodes[0], 1);
11084
11085                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
11086                 // path's success and a PaymentPathSuccessful event for each path's success.
11087                 let events = nodes[0].node.get_and_clear_pending_events();
11088                 assert_eq!(events.len(), 2);
11089                 match events[0] {
11090                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11091                                 assert_eq!(payment_id, *actual_payment_id);
11092                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11093                                 assert_eq!(route.paths[0], *path);
11094                         },
11095                         _ => panic!("Unexpected event"),
11096                 }
11097                 match events[1] {
11098                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11099                                 assert_eq!(payment_id, *actual_payment_id);
11100                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11101                                 assert_eq!(route.paths[0], *path);
11102                         },
11103                         _ => panic!("Unexpected event"),
11104                 }
11105         }
11106
11107         #[test]
11108         fn test_keysend_dup_payment_hash() {
11109                 do_test_keysend_dup_payment_hash(false);
11110                 do_test_keysend_dup_payment_hash(true);
11111         }
11112
11113         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
11114                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
11115                 //      outbound regular payment fails as expected.
11116                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
11117                 //      fails as expected.
11118                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
11119                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
11120                 //      reject MPP keysend payments, since in this case where the payment has no payment
11121                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
11122                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
11123                 //      payment secrets and reject otherwise.
11124                 let chanmon_cfgs = create_chanmon_cfgs(2);
11125                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11126                 let mut mpp_keysend_cfg = test_default_channel_config();
11127                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
11128                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
11129                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11130                 create_announced_chan_between_nodes(&nodes, 0, 1);
11131                 let scorer = test_utils::TestScorer::new();
11132                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11133
11134                 // To start (1), send a regular payment but don't claim it.
11135                 let expected_route = [&nodes[1]];
11136                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
11137
11138                 // Next, attempt a keysend payment and make sure it fails.
11139                 let route_params = RouteParameters::from_payment_params_and_value(
11140                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
11141                         TEST_FINAL_CLTV, false), 100_000);
11142                 let route = find_route(
11143                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11144                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11145                 ).unwrap();
11146                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11147                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11148                 check_added_monitors!(nodes[0], 1);
11149                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11150                 assert_eq!(events.len(), 1);
11151                 let ev = events.drain(..).next().unwrap();
11152                 let payment_event = SendEvent::from_event(ev);
11153                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11154                 check_added_monitors!(nodes[1], 0);
11155                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11156                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
11157                 // fails), the second will process the resulting failure and fail the HTLC backward
11158                 expect_pending_htlcs_forwardable!(nodes[1]);
11159                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11160                 check_added_monitors!(nodes[1], 1);
11161                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11162                 assert!(updates.update_add_htlcs.is_empty());
11163                 assert!(updates.update_fulfill_htlcs.is_empty());
11164                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11165                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11166                 assert!(updates.update_fee.is_none());
11167                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11168                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11169                 expect_payment_failed!(nodes[0], payment_hash, true);
11170
11171                 // Finally, claim the original payment.
11172                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11173
11174                 // To start (2), send a keysend payment but don't claim it.
11175                 let payment_preimage = PaymentPreimage([42; 32]);
11176                 let route = find_route(
11177                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11178                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11179                 ).unwrap();
11180                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11181                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11182                 check_added_monitors!(nodes[0], 1);
11183                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11184                 assert_eq!(events.len(), 1);
11185                 let event = events.pop().unwrap();
11186                 let path = vec![&nodes[1]];
11187                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11188
11189                 // Next, attempt a regular payment and make sure it fails.
11190                 let payment_secret = PaymentSecret([43; 32]);
11191                 nodes[0].node.send_payment_with_route(&route, payment_hash,
11192                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
11193                 check_added_monitors!(nodes[0], 1);
11194                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11195                 assert_eq!(events.len(), 1);
11196                 let ev = events.drain(..).next().unwrap();
11197                 let payment_event = SendEvent::from_event(ev);
11198                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11199                 check_added_monitors!(nodes[1], 0);
11200                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11201                 expect_pending_htlcs_forwardable!(nodes[1]);
11202                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11203                 check_added_monitors!(nodes[1], 1);
11204                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11205                 assert!(updates.update_add_htlcs.is_empty());
11206                 assert!(updates.update_fulfill_htlcs.is_empty());
11207                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11208                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11209                 assert!(updates.update_fee.is_none());
11210                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11211                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11212                 expect_payment_failed!(nodes[0], payment_hash, true);
11213
11214                 // Finally, succeed the keysend payment.
11215                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11216
11217                 // To start (3), send a keysend payment but don't claim it.
11218                 let payment_id_1 = PaymentId([44; 32]);
11219                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11220                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
11221                 check_added_monitors!(nodes[0], 1);
11222                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11223                 assert_eq!(events.len(), 1);
11224                 let event = events.pop().unwrap();
11225                 let path = vec![&nodes[1]];
11226                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11227
11228                 // Next, attempt a keysend payment and make sure it fails.
11229                 let route_params = RouteParameters::from_payment_params_and_value(
11230                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
11231                         100_000
11232                 );
11233                 let route = find_route(
11234                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11235                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11236                 ).unwrap();
11237                 let payment_id_2 = PaymentId([45; 32]);
11238                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11239                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
11240                 check_added_monitors!(nodes[0], 1);
11241                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11242                 assert_eq!(events.len(), 1);
11243                 let ev = events.drain(..).next().unwrap();
11244                 let payment_event = SendEvent::from_event(ev);
11245                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11246                 check_added_monitors!(nodes[1], 0);
11247                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11248                 expect_pending_htlcs_forwardable!(nodes[1]);
11249                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11250                 check_added_monitors!(nodes[1], 1);
11251                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11252                 assert!(updates.update_add_htlcs.is_empty());
11253                 assert!(updates.update_fulfill_htlcs.is_empty());
11254                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11255                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11256                 assert!(updates.update_fee.is_none());
11257                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11258                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11259                 expect_payment_failed!(nodes[0], payment_hash, true);
11260
11261                 // Finally, claim the original payment.
11262                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11263         }
11264
11265         #[test]
11266         fn test_keysend_hash_mismatch() {
11267                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
11268                 // preimage doesn't match the msg's payment hash.
11269                 let chanmon_cfgs = create_chanmon_cfgs(2);
11270                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11271                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11272                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11273
11274                 let payer_pubkey = nodes[0].node.get_our_node_id();
11275                 let payee_pubkey = nodes[1].node.get_our_node_id();
11276
11277                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11278                 let route_params = RouteParameters::from_payment_params_and_value(
11279                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11280                 let network_graph = nodes[0].network_graph;
11281                 let first_hops = nodes[0].node.list_usable_channels();
11282                 let scorer = test_utils::TestScorer::new();
11283                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11284                 let route = find_route(
11285                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11286                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11287                 ).unwrap();
11288
11289                 let test_preimage = PaymentPreimage([42; 32]);
11290                 let mismatch_payment_hash = PaymentHash([43; 32]);
11291                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
11292                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
11293                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
11294                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
11295                 check_added_monitors!(nodes[0], 1);
11296
11297                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11298                 assert_eq!(updates.update_add_htlcs.len(), 1);
11299                 assert!(updates.update_fulfill_htlcs.is_empty());
11300                 assert!(updates.update_fail_htlcs.is_empty());
11301                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11302                 assert!(updates.update_fee.is_none());
11303                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11304
11305                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
11306         }
11307
11308         #[test]
11309         fn test_keysend_msg_with_secret_err() {
11310                 // Test that we error as expected if we receive a keysend payment that includes a payment
11311                 // secret when we don't support MPP keysend.
11312                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
11313                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
11314                 let chanmon_cfgs = create_chanmon_cfgs(2);
11315                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11316                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
11317                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11318
11319                 let payer_pubkey = nodes[0].node.get_our_node_id();
11320                 let payee_pubkey = nodes[1].node.get_our_node_id();
11321
11322                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11323                 let route_params = RouteParameters::from_payment_params_and_value(
11324                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11325                 let network_graph = nodes[0].network_graph;
11326                 let first_hops = nodes[0].node.list_usable_channels();
11327                 let scorer = test_utils::TestScorer::new();
11328                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11329                 let route = find_route(
11330                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11331                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11332                 ).unwrap();
11333
11334                 let test_preimage = PaymentPreimage([42; 32]);
11335                 let test_secret = PaymentSecret([43; 32]);
11336                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).to_byte_array());
11337                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
11338                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
11339                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
11340                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
11341                         PaymentId(payment_hash.0), None, session_privs).unwrap();
11342                 check_added_monitors!(nodes[0], 1);
11343
11344                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11345                 assert_eq!(updates.update_add_htlcs.len(), 1);
11346                 assert!(updates.update_fulfill_htlcs.is_empty());
11347                 assert!(updates.update_fail_htlcs.is_empty());
11348                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11349                 assert!(updates.update_fee.is_none());
11350                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11351
11352                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11353         }
11354
11355         #[test]
11356         fn test_multi_hop_missing_secret() {
11357                 let chanmon_cfgs = create_chanmon_cfgs(4);
11358                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11359                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11360                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11361
11362                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11363                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11364                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11365                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11366
11367                 // Marshall an MPP route.
11368                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11369                 let path = route.paths[0].clone();
11370                 route.paths.push(path);
11371                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11372                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11373                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11374                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11375                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11376                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11377
11378                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11379                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11380                 .unwrap_err() {
11381                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11382                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11383                         },
11384                         _ => panic!("unexpected error")
11385                 }
11386         }
11387
11388         #[test]
11389         fn test_drop_disconnected_peers_when_removing_channels() {
11390                 let chanmon_cfgs = create_chanmon_cfgs(2);
11391                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11392                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11393                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11394
11395                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11396
11397                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11398                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11399
11400                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11401                 check_closed_broadcast!(nodes[0], true);
11402                 check_added_monitors!(nodes[0], 1);
11403                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11404
11405                 {
11406                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11407                         // disconnected and the channel between has been force closed.
11408                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11409                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11410                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11411                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11412                 }
11413
11414                 nodes[0].node.timer_tick_occurred();
11415
11416                 {
11417                         // Assert that nodes[1] has now been removed.
11418                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11419                 }
11420         }
11421
11422         #[test]
11423         fn bad_inbound_payment_hash() {
11424                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11425                 let chanmon_cfgs = create_chanmon_cfgs(2);
11426                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11427                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11428                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11429
11430                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11431                 let payment_data = msgs::FinalOnionHopData {
11432                         payment_secret,
11433                         total_msat: 100_000,
11434                 };
11435
11436                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11437                 // payment verification fails as expected.
11438                 let mut bad_payment_hash = payment_hash.clone();
11439                 bad_payment_hash.0[0] += 1;
11440                 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) {
11441                         Ok(_) => panic!("Unexpected ok"),
11442                         Err(()) => {
11443                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11444                         }
11445                 }
11446
11447                 // Check that using the original payment hash succeeds.
11448                 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());
11449         }
11450
11451         #[test]
11452         fn test_id_to_peer_coverage() {
11453                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
11454                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11455                 // the channel is successfully closed.
11456                 let chanmon_cfgs = create_chanmon_cfgs(2);
11457                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11458                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11459                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11460
11461                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
11462                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11463                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11464                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11465                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11466
11467                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11468                 let channel_id = ChannelId::from_bytes(tx.txid().to_byte_array());
11469                 {
11470                         // Ensure that the `id_to_peer` map is empty until either party has received the
11471                         // funding transaction, and have the real `channel_id`.
11472                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11473                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11474                 }
11475
11476                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11477                 {
11478                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
11479                         // as it has the funding transaction.
11480                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11481                         assert_eq!(nodes_0_lock.len(), 1);
11482                         assert!(nodes_0_lock.contains_key(&channel_id));
11483                 }
11484
11485                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11486
11487                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11488
11489                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11490                 {
11491                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11492                         assert_eq!(nodes_0_lock.len(), 1);
11493                         assert!(nodes_0_lock.contains_key(&channel_id));
11494                 }
11495                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11496
11497                 {
11498                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
11499                         // as it has the funding transaction.
11500                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11501                         assert_eq!(nodes_1_lock.len(), 1);
11502                         assert!(nodes_1_lock.contains_key(&channel_id));
11503                 }
11504                 check_added_monitors!(nodes[1], 1);
11505                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11506                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11507                 check_added_monitors!(nodes[0], 1);
11508                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11509                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11510                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11511                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11512
11513                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11514                 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()));
11515                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11516                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11517
11518                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11519                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11520                 {
11521                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
11522                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11523                         // fee for the closing transaction has been negotiated and the parties has the other
11524                         // party's signature for the fee negotiated closing transaction.)
11525                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11526                         assert_eq!(nodes_0_lock.len(), 1);
11527                         assert!(nodes_0_lock.contains_key(&channel_id));
11528                 }
11529
11530                 {
11531                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11532                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11533                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11534                         // kept in the `nodes[1]`'s `id_to_peer` map.
11535                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11536                         assert_eq!(nodes_1_lock.len(), 1);
11537                         assert!(nodes_1_lock.contains_key(&channel_id));
11538                 }
11539
11540                 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()));
11541                 {
11542                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11543                         // therefore has all it needs to fully close the channel (both signatures for the
11544                         // closing transaction).
11545                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
11546                         // fully closed by `nodes[0]`.
11547                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11548
11549                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
11550                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11551                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11552                         assert_eq!(nodes_1_lock.len(), 1);
11553                         assert!(nodes_1_lock.contains_key(&channel_id));
11554                 }
11555
11556                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11557
11558                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11559                 {
11560                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
11561                         // they both have everything required to fully close the channel.
11562                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11563                 }
11564                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11565
11566                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11567                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11568         }
11569
11570         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11571                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11572                 check_api_error_message(expected_message, res_err)
11573         }
11574
11575         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11576                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11577                 check_api_error_message(expected_message, res_err)
11578         }
11579
11580         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11581                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11582                 check_api_error_message(expected_message, res_err)
11583         }
11584
11585         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11586                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11587                 check_api_error_message(expected_message, res_err)
11588         }
11589
11590         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11591                 match res_err {
11592                         Err(APIError::APIMisuseError { err }) => {
11593                                 assert_eq!(err, expected_err_message);
11594                         },
11595                         Err(APIError::ChannelUnavailable { err }) => {
11596                                 assert_eq!(err, expected_err_message);
11597                         },
11598                         Ok(_) => panic!("Unexpected Ok"),
11599                         Err(_) => panic!("Unexpected Error"),
11600                 }
11601         }
11602
11603         #[test]
11604         fn test_api_calls_with_unkown_counterparty_node() {
11605                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11606                 // expected if the `counterparty_node_id` is an unkown peer in the
11607                 // `ChannelManager::per_peer_state` map.
11608                 let chanmon_cfg = create_chanmon_cfgs(2);
11609                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11610                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11611                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11612
11613                 // Dummy values
11614                 let channel_id = ChannelId::from_bytes([4; 32]);
11615                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11616                 let intercept_id = InterceptId([0; 32]);
11617
11618                 // Test the API functions.
11619                 check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None, None), unkown_public_key);
11620
11621                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11622
11623                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11624
11625                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11626
11627                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11628
11629                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11630
11631                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11632         }
11633
11634         #[test]
11635         fn test_api_calls_with_unavailable_channel() {
11636                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11637                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11638                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11639                 // the given `channel_id`.
11640                 let chanmon_cfg = create_chanmon_cfgs(2);
11641                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11642                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11643                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11644
11645                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11646
11647                 // Dummy values
11648                 let channel_id = ChannelId::from_bytes([4; 32]);
11649
11650                 // Test the API functions.
11651                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11652
11653                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11654
11655                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11656
11657                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11658
11659                 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);
11660
11661                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11662         }
11663
11664         #[test]
11665         fn test_connection_limiting() {
11666                 // Test that we limit un-channel'd peers and un-funded channels properly.
11667                 let chanmon_cfgs = create_chanmon_cfgs(2);
11668                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11669                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11670                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11671
11672                 // Note that create_network connects the nodes together for us
11673
11674                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11675                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11676
11677                 let mut funding_tx = None;
11678                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11679                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11680                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11681
11682                         if idx == 0 {
11683                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11684                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11685                                 funding_tx = Some(tx.clone());
11686                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11687                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11688
11689                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11690                                 check_added_monitors!(nodes[1], 1);
11691                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11692
11693                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11694
11695                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11696                                 check_added_monitors!(nodes[0], 1);
11697                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11698                         }
11699                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11700                 }
11701
11702                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11703                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11704                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11705                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11706                         open_channel_msg.temporary_channel_id);
11707
11708                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11709                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11710                 // limit.
11711                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11712                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11713                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11714                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11715                         peer_pks.push(random_pk);
11716                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11717                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11718                         }, true).unwrap();
11719                 }
11720                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11721                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11722                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11723                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11724                 }, true).unwrap_err();
11725
11726                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11727                 // them if we have too many un-channel'd peers.
11728                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11729                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11730                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
11731                 for ev in chan_closed_events {
11732                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
11733                 }
11734                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11735                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11736                 }, true).unwrap();
11737                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11738                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11739                 }, true).unwrap_err();
11740
11741                 // but of course if the connection is outbound its allowed...
11742                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11743                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11744                 }, false).unwrap();
11745                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11746
11747                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
11748                 // Even though we accept one more connection from new peers, we won't actually let them
11749                 // open channels.
11750                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
11751                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11752                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
11753                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
11754                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11755                 }
11756                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11757                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11758                         open_channel_msg.temporary_channel_id);
11759
11760                 // Of course, however, outbound channels are always allowed
11761                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap();
11762                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
11763
11764                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
11765                 // "protected" and can connect again.
11766                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
11767                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11768                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11769                 }, true).unwrap();
11770                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
11771
11772                 // Further, because the first channel was funded, we can open another channel with
11773                 // last_random_pk.
11774                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11775                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11776         }
11777
11778         #[test]
11779         fn test_outbound_chans_unlimited() {
11780                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
11781                 let chanmon_cfgs = create_chanmon_cfgs(2);
11782                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11783                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11784                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11785
11786                 // Note that create_network connects the nodes together for us
11787
11788                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11789                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11790
11791                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11792                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11793                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11794                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11795                 }
11796
11797                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
11798                 // rejected.
11799                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11800                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11801                         open_channel_msg.temporary_channel_id);
11802
11803                 // but we can still open an outbound channel.
11804                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11805                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
11806
11807                 // but even with such an outbound channel, additional inbound channels will still fail.
11808                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11809                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11810                         open_channel_msg.temporary_channel_id);
11811         }
11812
11813         #[test]
11814         fn test_0conf_limiting() {
11815                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11816                 // flag set and (sometimes) accept channels as 0conf.
11817                 let chanmon_cfgs = create_chanmon_cfgs(2);
11818                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11819                 let mut settings = test_default_channel_config();
11820                 settings.manually_accept_inbound_channels = true;
11821                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
11822                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11823
11824                 // Note that create_network connects the nodes together for us
11825
11826                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11827                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11828
11829                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
11830                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11831                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11832                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11833                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11834                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11835                         }, true).unwrap();
11836
11837                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
11838                         let events = nodes[1].node.get_and_clear_pending_events();
11839                         match events[0] {
11840                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11841                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
11842                                 }
11843                                 _ => panic!("Unexpected event"),
11844                         }
11845                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
11846                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11847                 }
11848
11849                 // If we try to accept a channel from another peer non-0conf it will fail.
11850                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11851                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11852                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11853                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11854                 }, true).unwrap();
11855                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11856                 let events = nodes[1].node.get_and_clear_pending_events();
11857                 match events[0] {
11858                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11859                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
11860                                         Err(APIError::APIMisuseError { err }) =>
11861                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
11862                                         _ => panic!(),
11863                                 }
11864                         }
11865                         _ => panic!("Unexpected event"),
11866                 }
11867                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11868                         open_channel_msg.temporary_channel_id);
11869
11870                 // ...however if we accept the same channel 0conf it should work just fine.
11871                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11872                 let events = nodes[1].node.get_and_clear_pending_events();
11873                 match events[0] {
11874                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11875                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
11876                         }
11877                         _ => panic!("Unexpected event"),
11878                 }
11879                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11880         }
11881
11882         #[test]
11883         fn reject_excessively_underpaying_htlcs() {
11884                 let chanmon_cfg = create_chanmon_cfgs(1);
11885                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11886                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11887                 let node = create_network(1, &node_cfg, &node_chanmgr);
11888                 let sender_intended_amt_msat = 100;
11889                 let extra_fee_msat = 10;
11890                 let hop_data = msgs::InboundOnionPayload::Receive {
11891                         amt_msat: 100,
11892                         outgoing_cltv_value: 42,
11893                         payment_metadata: None,
11894                         keysend_preimage: None,
11895                         payment_data: Some(msgs::FinalOnionHopData {
11896                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11897                         }),
11898                         custom_tlvs: Vec::new(),
11899                 };
11900                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
11901                 // intended amount, we fail the payment.
11902                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11903                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
11904                         create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11905                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
11906                                 current_height, node[0].node.default_configuration.accept_mpp_keysend)
11907                 {
11908                         assert_eq!(err_code, 19);
11909                 } else { panic!(); }
11910
11911                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
11912                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
11913                         amt_msat: 100,
11914                         outgoing_cltv_value: 42,
11915                         payment_metadata: None,
11916                         keysend_preimage: None,
11917                         payment_data: Some(msgs::FinalOnionHopData {
11918                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11919                         }),
11920                         custom_tlvs: Vec::new(),
11921                 };
11922                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11923                 assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11924                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
11925                         current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
11926         }
11927
11928         #[test]
11929         fn test_final_incorrect_cltv(){
11930                 let chanmon_cfg = create_chanmon_cfgs(1);
11931                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11932                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11933                 let node = create_network(1, &node_cfg, &node_chanmgr);
11934
11935                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
11936                 let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
11937                         amt_msat: 100,
11938                         outgoing_cltv_value: 22,
11939                         payment_metadata: None,
11940                         keysend_preimage: None,
11941                         payment_data: Some(msgs::FinalOnionHopData {
11942                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
11943                         }),
11944                         custom_tlvs: Vec::new(),
11945                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
11946                         node[0].node.default_configuration.accept_mpp_keysend);
11947
11948                 // Should not return an error as this condition:
11949                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
11950                 // is not satisfied.
11951                 assert!(result.is_ok());
11952         }
11953
11954         #[test]
11955         fn test_inbound_anchors_manual_acceptance() {
11956                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11957                 // flag set and (sometimes) accept channels as 0conf.
11958                 let mut anchors_cfg = test_default_channel_config();
11959                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11960
11961                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
11962                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
11963
11964                 let chanmon_cfgs = create_chanmon_cfgs(3);
11965                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11966                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
11967                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
11968                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11969
11970                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11971                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11972
11973                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11974                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11975                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
11976                 match &msg_events[0] {
11977                         MessageSendEvent::HandleError { node_id, action } => {
11978                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
11979                                 match action {
11980                                         ErrorAction::SendErrorMessage { msg } =>
11981                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
11982                                         _ => panic!("Unexpected error action"),
11983                                 }
11984                         }
11985                         _ => panic!("Unexpected event"),
11986                 }
11987
11988                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11989                 let events = nodes[2].node.get_and_clear_pending_events();
11990                 match events[0] {
11991                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
11992                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
11993                         _ => panic!("Unexpected event"),
11994                 }
11995                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11996         }
11997
11998         #[test]
11999         fn test_anchors_zero_fee_htlc_tx_fallback() {
12000                 // Tests that if both nodes support anchors, but the remote node does not want to accept
12001                 // anchor channels at the moment, an error it sent to the local node such that it can retry
12002                 // the channel without the anchors feature.
12003                 let chanmon_cfgs = create_chanmon_cfgs(2);
12004                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12005                 let mut anchors_config = test_default_channel_config();
12006                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12007                 anchors_config.manually_accept_inbound_channels = true;
12008                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
12009                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12010
12011                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None).unwrap();
12012                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12013                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
12014
12015                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12016                 let events = nodes[1].node.get_and_clear_pending_events();
12017                 match events[0] {
12018                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12019                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
12020                         }
12021                         _ => panic!("Unexpected event"),
12022                 }
12023
12024                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
12025                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
12026
12027                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12028                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
12029
12030                 // Since nodes[1] should not have accepted the channel, it should
12031                 // not have generated any events.
12032                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12033         }
12034
12035         #[test]
12036         fn test_update_channel_config() {
12037                 let chanmon_cfg = create_chanmon_cfgs(2);
12038                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12039                 let mut user_config = test_default_channel_config();
12040                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12041                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12042                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
12043                 let channel = &nodes[0].node.list_channels()[0];
12044
12045                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12046                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12047                 assert_eq!(events.len(), 0);
12048
12049                 user_config.channel_config.forwarding_fee_base_msat += 10;
12050                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12051                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
12052                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12053                 assert_eq!(events.len(), 1);
12054                 match &events[0] {
12055                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12056                         _ => panic!("expected BroadcastChannelUpdate event"),
12057                 }
12058
12059                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
12060                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12061                 assert_eq!(events.len(), 0);
12062
12063                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
12064                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12065                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
12066                         ..Default::default()
12067                 }).unwrap();
12068                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12069                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12070                 assert_eq!(events.len(), 1);
12071                 match &events[0] {
12072                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12073                         _ => panic!("expected BroadcastChannelUpdate event"),
12074                 }
12075
12076                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
12077                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12078                         forwarding_fee_proportional_millionths: Some(new_fee),
12079                         ..Default::default()
12080                 }).unwrap();
12081                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12082                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
12083                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12084                 assert_eq!(events.len(), 1);
12085                 match &events[0] {
12086                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12087                         _ => panic!("expected BroadcastChannelUpdate event"),
12088                 }
12089
12090                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
12091                 // should be applied to ensure update atomicity as specified in the API docs.
12092                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
12093                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
12094                 let new_fee = current_fee + 100;
12095                 assert!(
12096                         matches!(
12097                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
12098                                         forwarding_fee_proportional_millionths: Some(new_fee),
12099                                         ..Default::default()
12100                                 }),
12101                                 Err(APIError::ChannelUnavailable { err: _ }),
12102                         )
12103                 );
12104                 // Check that the fee hasn't changed for the channel that exists.
12105                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
12106                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12107                 assert_eq!(events.len(), 0);
12108         }
12109
12110         #[test]
12111         fn test_payment_display() {
12112                 let payment_id = PaymentId([42; 32]);
12113                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12114                 let payment_hash = PaymentHash([42; 32]);
12115                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12116                 let payment_preimage = PaymentPreimage([42; 32]);
12117                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12118         }
12119
12120         #[test]
12121         fn test_trigger_lnd_force_close() {
12122                 let chanmon_cfg = create_chanmon_cfgs(2);
12123                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12124                 let user_config = test_default_channel_config();
12125                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12126                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12127
12128                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
12129                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
12130                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
12131                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12132                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
12133                 check_closed_broadcast(&nodes[0], 1, true);
12134                 check_added_monitors(&nodes[0], 1);
12135                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
12136                 {
12137                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
12138                         assert_eq!(txn.len(), 1);
12139                         check_spends!(txn[0], funding_tx);
12140                 }
12141
12142                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
12143                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
12144                 // their side.
12145                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
12146                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
12147                 }, true).unwrap();
12148                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12149                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12150                 }, false).unwrap();
12151                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
12152                 let channel_reestablish = get_event_msg!(
12153                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
12154                 );
12155                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
12156
12157                 // Alice should respond with an error since the channel isn't known, but a bogus
12158                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
12159                 // close even if it was an lnd node.
12160                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
12161                 assert_eq!(msg_events.len(), 2);
12162                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
12163                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
12164                         assert_eq!(msg.next_local_commitment_number, 0);
12165                         assert_eq!(msg.next_remote_commitment_number, 0);
12166                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
12167                 } else { panic!() };
12168                 check_closed_broadcast(&nodes[1], 1, true);
12169                 check_added_monitors(&nodes[1], 1);
12170                 let expected_close_reason = ClosureReason::ProcessingError {
12171                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
12172                 };
12173                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
12174                 {
12175                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
12176                         assert_eq!(txn.len(), 1);
12177                         check_spends!(txn[0], funding_tx);
12178                 }
12179         }
12180 }
12181
12182 #[cfg(ldk_bench)]
12183 pub mod bench {
12184         use crate::chain::Listen;
12185         use crate::chain::chainmonitor::{ChainMonitor, Persist};
12186         use crate::sign::{KeysManager, InMemorySigner};
12187         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
12188         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
12189         use crate::ln::functional_test_utils::*;
12190         use crate::ln::msgs::{ChannelMessageHandler, Init};
12191         use crate::routing::gossip::NetworkGraph;
12192         use crate::routing::router::{PaymentParameters, RouteParameters};
12193         use crate::util::test_utils;
12194         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
12195
12196         use bitcoin::blockdata::locktime::absolute::LockTime;
12197         use bitcoin::hashes::Hash;
12198         use bitcoin::hashes::sha256::Hash as Sha256;
12199         use bitcoin::{Block, Transaction, TxOut};
12200
12201         use crate::sync::{Arc, Mutex, RwLock};
12202
12203         use criterion::Criterion;
12204
12205         type Manager<'a, P> = ChannelManager<
12206                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
12207                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
12208                         &'a test_utils::TestLogger, &'a P>,
12209                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
12210                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
12211                 &'a test_utils::TestLogger>;
12212
12213         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
12214                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
12215         }
12216         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
12217                 type CM = Manager<'chan_mon_cfg, P>;
12218                 #[inline]
12219                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
12220                 #[inline]
12221                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
12222         }
12223
12224         pub fn bench_sends(bench: &mut Criterion) {
12225                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
12226         }
12227
12228         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
12229                 // Do a simple benchmark of sending a payment back and forth between two nodes.
12230                 // Note that this is unrealistic as each payment send will require at least two fsync
12231                 // calls per node.
12232                 let network = bitcoin::Network::Testnet;
12233                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
12234
12235                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
12236                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
12237                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
12238                 let scorer = RwLock::new(test_utils::TestScorer::new());
12239                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
12240
12241                 let mut config: UserConfig = Default::default();
12242                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
12243                 config.channel_handshake_config.minimum_depth = 1;
12244
12245                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
12246                 let seed_a = [1u8; 32];
12247                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
12248                 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 {
12249                         network,
12250                         best_block: BestBlock::from_network(network),
12251                 }, genesis_block.header.time);
12252                 let node_a_holder = ANodeHolder { node: &node_a };
12253
12254                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
12255                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
12256                 let seed_b = [2u8; 32];
12257                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
12258                 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 {
12259                         network,
12260                         best_block: BestBlock::from_network(network),
12261                 }, genesis_block.header.time);
12262                 let node_b_holder = ANodeHolder { node: &node_b };
12263
12264                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
12265                         features: node_b.init_features(), networks: None, remote_network_address: None
12266                 }, true).unwrap();
12267                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
12268                         features: node_a.init_features(), networks: None, remote_network_address: None
12269                 }, false).unwrap();
12270                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None, None).unwrap();
12271                 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()));
12272                 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()));
12273
12274                 let tx;
12275                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
12276                         tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12277                                 value: 8_000_000, script_pubkey: output_script,
12278                         }]};
12279                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
12280                 } else { panic!(); }
12281
12282                 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()));
12283                 let events_b = node_b.get_and_clear_pending_events();
12284                 assert_eq!(events_b.len(), 1);
12285                 match events_b[0] {
12286                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12287                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12288                         },
12289                         _ => panic!("Unexpected event"),
12290                 }
12291
12292                 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()));
12293                 let events_a = node_a.get_and_clear_pending_events();
12294                 assert_eq!(events_a.len(), 1);
12295                 match events_a[0] {
12296                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12297                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12298                         },
12299                         _ => panic!("Unexpected event"),
12300                 }
12301
12302                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
12303
12304                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
12305                 Listen::block_connected(&node_a, &block, 1);
12306                 Listen::block_connected(&node_b, &block, 1);
12307
12308                 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()));
12309                 let msg_events = node_a.get_and_clear_pending_msg_events();
12310                 assert_eq!(msg_events.len(), 2);
12311                 match msg_events[0] {
12312                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
12313                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
12314                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
12315                         },
12316                         _ => panic!(),
12317                 }
12318                 match msg_events[1] {
12319                         MessageSendEvent::SendChannelUpdate { .. } => {},
12320                         _ => panic!(),
12321                 }
12322
12323                 let events_a = node_a.get_and_clear_pending_events();
12324                 assert_eq!(events_a.len(), 1);
12325                 match events_a[0] {
12326                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12327                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12328                         },
12329                         _ => panic!("Unexpected event"),
12330                 }
12331
12332                 let events_b = node_b.get_and_clear_pending_events();
12333                 assert_eq!(events_b.len(), 1);
12334                 match events_b[0] {
12335                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12336                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12337                         },
12338                         _ => panic!("Unexpected event"),
12339                 }
12340
12341                 let mut payment_count: u64 = 0;
12342                 macro_rules! send_payment {
12343                         ($node_a: expr, $node_b: expr) => {
12344                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
12345                                         .with_bolt11_features($node_b.bolt11_invoice_features()).unwrap();
12346                                 let mut payment_preimage = PaymentPreimage([0; 32]);
12347                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
12348                                 payment_count += 1;
12349                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
12350                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
12351
12352                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
12353                                         PaymentId(payment_hash.0),
12354                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12355                                         Retry::Attempts(0)).unwrap();
12356                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12357                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12358                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12359                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12360                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12361                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12362                                 $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()));
12363
12364                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12365                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12366                                 $node_b.claim_funds(payment_preimage);
12367                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12368
12369                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12370                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12371                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12372                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12373                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12374                                         },
12375                                         _ => panic!("Failed to generate claim event"),
12376                                 }
12377
12378                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12379                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12380                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12381                                 $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()));
12382
12383                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12384                         }
12385                 }
12386
12387                 bench.bench_function(bench_name, |b| b.iter(|| {
12388                         send_payment!(node_a, node_b);
12389                         send_payment!(node_b, node_a);
12390                 }));
12391         }
12392 }