Add c_bindings version of OfferBuilder
[rust-lightning] / lightning / src / ln / channelmanager.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The top-level channel management and payment tracking stuff lives here.
11 //!
12 //! The [`ChannelManager`] is the main chunk of logic implementing the lightning protocol and is
13 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
14 //! upon reconnect to the relevant peer(s).
15 //!
16 //! It does not manage routing logic (see [`Router`] for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
19
20 use bitcoin::blockdata::block::Header;
21 use bitcoin::blockdata::transaction::Transaction;
22 use bitcoin::blockdata::constants::ChainHash;
23 use bitcoin::key::constants::SECRET_KEY_SIZE;
24 use bitcoin::network::constants::Network;
25
26 use bitcoin::hashes::Hash;
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::hash_types::{BlockHash, Txid};
29
30 use bitcoin::secp256k1::{SecretKey,PublicKey};
31 use bitcoin::secp256k1::Secp256k1;
32 use bitcoin::{secp256k1, Sequence};
33
34 use crate::blinded_path::BlindedPath;
35 use crate::blinded_path::payment::{PaymentConstraints, ReceiveTlvs};
36 use crate::chain;
37 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
38 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
39 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, WithChannelMonitor, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
40 use crate::chain::transaction::{OutPoint, TransactionData};
41 use crate::events;
42 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
43 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
44 // construct one themselves.
45 use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
46 use crate::ln::channel::{self, Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext};
47 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
48 #[cfg(any(feature = "_test_utils", test))]
49 use crate::ln::features::Bolt11InvoiceFeatures;
50 use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
51 use crate::ln::onion_payment::{check_incoming_htlc_cltv, create_recv_pending_htlc_info, create_fwd_pending_htlc_info, decode_incoming_update_add_htlc_onion, InboundHTLCErr, NextPacketDetails};
52 use crate::ln::msgs;
53 use crate::ln::onion_utils;
54 use crate::ln::onion_utils::{HTLCFailReason, INVALID_ONION_BLINDING};
55 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
56 #[cfg(test)]
57 use crate::ln::outbound_payment;
58 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs, StaleExpiration};
59 use crate::ln::wire::Encode;
60 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, InvoiceBuilder};
61 use crate::offers::invoice_error::InvoiceError;
62 use crate::offers::merkle::SignError;
63 use crate::offers::offer::{Offer, OfferBuilder};
64 use crate::offers::parse::Bolt12SemanticError;
65 use crate::offers::refund::{Refund, RefundBuilder};
66 use crate::onion_message::messenger::{Destination, MessageRouter, PendingOnionMessage, new_pending_onion_message};
67 use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
68 use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
69 use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
70 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
71 use crate::util::wakers::{Future, Notifier};
72 use crate::util::scid_utils::fake_scid;
73 use crate::util::string::UntrustedString;
74 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
75 use crate::util::logger::{Level, Logger, WithContext};
76 use crate::util::errors::APIError;
77 #[cfg(not(c_bindings))]
78 use {
79         crate::offers::offer::DerivedMetadata,
80         crate::routing::router::DefaultRouter,
81         crate::routing::gossip::NetworkGraph,
82         crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters},
83         crate::sign::KeysManager,
84 };
85 #[cfg(c_bindings)]
86 use {
87         crate::offers::offer::OfferWithDerivedMetadataBuilder,
88 };
89
90 use alloc::collections::{btree_map, BTreeMap};
91
92 use crate::io;
93 use crate::prelude::*;
94 use core::{cmp, mem};
95 use core::cell::RefCell;
96 use crate::io::Read;
97 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
98 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
99 use core::time::Duration;
100 use core::ops::Deref;
101
102 // Re-export this for use in the public API.
103 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
104 use crate::ln::script::ShutdownScript;
105
106 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
107 //
108 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
109 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
110 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
111 //
112 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
113 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
114 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
115 // before we forward it.
116 //
117 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
118 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
119 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
120 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
121 // our payment, which we can use to decode errors or inform the user that the payment was sent.
122
123 /// Information about where a received HTLC('s onion) has indicated the HTLC should go.
124 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125 #[cfg_attr(test, derive(Debug, PartialEq))]
126 pub enum PendingHTLCRouting {
127         /// An HTLC which should be forwarded on to another node.
128         Forward {
129                 /// The onion which should be included in the forwarded HTLC, telling the next hop what to
130                 /// do with the HTLC.
131                 onion_packet: msgs::OnionPacket,
132                 /// The short channel ID of the channel which we were instructed to forward this HTLC to.
133                 ///
134                 /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning
135                 /// to the receiving node, such as one returned from
136                 /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`].
137                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
138                 /// Set if this HTLC is being forwarded within a blinded path.
139                 blinded: Option<BlindedForward>,
140         },
141         /// The onion indicates that this is a payment for an invoice (supposedly) generated by us.
142         ///
143         /// Note that at this point, we have not checked that the invoice being paid was actually
144         /// generated by us, but rather it's claiming to pay an invoice of ours.
145         Receive {
146                 /// Information about the amount the sender intended to pay and (potential) proof that this
147                 /// is a payment for an invoice we generated. This proof of payment is is also used for
148                 /// linking MPP parts of a larger payment.
149                 payment_data: msgs::FinalOnionHopData,
150                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
151                 ///
152                 /// For HTLCs received by LDK, this will ultimately be exposed in
153                 /// [`Event::PaymentClaimable::onion_fields`] as
154                 /// [`RecipientOnionFields::payment_metadata`].
155                 payment_metadata: Option<Vec<u8>>,
156                 /// CLTV expiry of the received HTLC.
157                 ///
158                 /// Used to track when we should expire pending HTLCs that go unclaimed.
159                 incoming_cltv_expiry: u32,
160                 /// If the onion had forwarding instructions to one of our phantom node SCIDs, this will
161                 /// provide the onion shared secret used to decrypt the next level of forwarding
162                 /// instructions.
163                 phantom_shared_secret: Option<[u8; 32]>,
164                 /// Custom TLVs which were set by the sender.
165                 ///
166                 /// For HTLCs received by LDK, this will ultimately be exposed in
167                 /// [`Event::PaymentClaimable::onion_fields`] as
168                 /// [`RecipientOnionFields::custom_tlvs`].
169                 custom_tlvs: Vec<(u64, Vec<u8>)>,
170                 /// Set if this HTLC is the final hop in a multi-hop blinded path.
171                 requires_blinded_error: bool,
172         },
173         /// The onion indicates that this is for payment to us but which contains the preimage for
174         /// claiming included, and is unrelated to any invoice we'd previously generated (aka a
175         /// "keysend" or "spontaneous" payment).
176         ReceiveKeysend {
177                 /// Information about the amount the sender intended to pay and possibly a token to
178                 /// associate MPP parts of a larger payment.
179                 ///
180                 /// This will only be filled in if receiving MPP keysend payments is enabled, and it being
181                 /// present will cause deserialization to fail on versions of LDK prior to 0.0.116.
182                 payment_data: Option<msgs::FinalOnionHopData>,
183                 /// Preimage for this onion payment. This preimage is provided by the sender and will be
184                 /// used to settle the spontaneous payment.
185                 payment_preimage: PaymentPreimage,
186                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
187                 ///
188                 /// For HTLCs received by LDK, this will ultimately bubble back up as
189                 /// [`RecipientOnionFields::payment_metadata`].
190                 payment_metadata: Option<Vec<u8>>,
191                 /// CLTV expiry of the received HTLC.
192                 ///
193                 /// Used to track when we should expire pending HTLCs that go unclaimed.
194                 incoming_cltv_expiry: u32,
195                 /// Custom TLVs which were set by the sender.
196                 ///
197                 /// For HTLCs received by LDK, these will ultimately bubble back up as
198                 /// [`RecipientOnionFields::custom_tlvs`].
199                 custom_tlvs: Vec<(u64, Vec<u8>)>,
200         },
201 }
202
203 /// Information used to forward or fail this HTLC that is being forwarded within a blinded path.
204 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
205 pub struct BlindedForward {
206         /// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound
207         /// onion payload if we're the introduction node. Useful for calculating the next hop's
208         /// [`msgs::UpdateAddHTLC::blinding_point`].
209         pub inbound_blinding_point: PublicKey,
210         /// If needed, this determines how this HTLC should be failed backwards, based on whether we are
211         /// the introduction node.
212         pub failure: BlindedFailure,
213 }
214
215 impl PendingHTLCRouting {
216         // Used to override the onion failure code and data if the HTLC is blinded.
217         fn blinded_failure(&self) -> Option<BlindedFailure> {
218                 match self {
219                         Self::Forward { blinded: Some(BlindedForward { failure, .. }), .. } => Some(*failure),
220                         Self::Receive { requires_blinded_error: true, .. } => Some(BlindedFailure::FromBlindedNode),
221                         _ => None,
222                 }
223         }
224 }
225
226 /// Information about an incoming HTLC, including the [`PendingHTLCRouting`] describing where it
227 /// should go next.
228 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
229 #[cfg_attr(test, derive(Debug, PartialEq))]
230 pub struct PendingHTLCInfo {
231         /// Further routing details based on whether the HTLC is being forwarded or received.
232         pub routing: PendingHTLCRouting,
233         /// The onion shared secret we build with the sender used to decrypt the onion.
234         ///
235         /// This is later used to encrypt failure packets in the event that the HTLC is failed.
236         pub incoming_shared_secret: [u8; 32],
237         /// Hash of the payment preimage, to lock the payment until the receiver releases the preimage.
238         pub payment_hash: PaymentHash,
239         /// Amount received in the incoming HTLC.
240         ///
241         /// This field was added in LDK 0.0.113 and will be `None` for objects written by prior
242         /// versions.
243         pub incoming_amt_msat: Option<u64>,
244         /// The amount the sender indicated should be forwarded on to the next hop or amount the sender
245         /// intended for us to receive for received payments.
246         ///
247         /// If the received amount is less than this for received payments, an intermediary hop has
248         /// attempted to steal some of our funds and we should fail the HTLC (the sender should retry
249         /// it along another path).
250         ///
251         /// Because nodes can take less than their required fees, and because senders may wish to
252         /// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for
253         /// received payments. In such cases, recipients must handle this HTLC as if it had received
254         /// [`Self::outgoing_amt_msat`].
255         pub outgoing_amt_msat: u64,
256         /// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated
257         /// should have been set on the received HTLC for received payments).
258         pub outgoing_cltv_value: u32,
259         /// The fee taken for this HTLC in addition to the standard protocol HTLC fees.
260         ///
261         /// If this is a payment for forwarding, this is the fee we are taking before forwarding the
262         /// HTLC.
263         ///
264         /// If this is a received payment, this is the fee that our counterparty took.
265         ///
266         /// This is used to allow LSPs to take fees as a part of payments, without the sender having to
267         /// shoulder them.
268         pub skimmed_fee_msat: Option<u64>,
269 }
270
271 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
272 pub(super) enum HTLCFailureMsg {
273         Relay(msgs::UpdateFailHTLC),
274         Malformed(msgs::UpdateFailMalformedHTLC),
275 }
276
277 /// Stores whether we can't forward an HTLC or relevant forwarding info
278 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
279 pub(super) enum PendingHTLCStatus {
280         Forward(PendingHTLCInfo),
281         Fail(HTLCFailureMsg),
282 }
283
284 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
285 pub(super) struct PendingAddHTLCInfo {
286         pub(super) forward_info: PendingHTLCInfo,
287
288         // These fields are produced in `forward_htlcs()` and consumed in
289         // `process_pending_htlc_forwards()` for constructing the
290         // `HTLCSource::PreviousHopData` for failed and forwarded
291         // HTLCs.
292         //
293         // Note that this may be an outbound SCID alias for the associated channel.
294         prev_short_channel_id: u64,
295         prev_htlc_id: u64,
296         prev_funding_outpoint: OutPoint,
297         prev_user_channel_id: u128,
298 }
299
300 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
301 pub(super) enum HTLCForwardInfo {
302         AddHTLC(PendingAddHTLCInfo),
303         FailHTLC {
304                 htlc_id: u64,
305                 err_packet: msgs::OnionErrorPacket,
306         },
307         FailMalformedHTLC {
308                 htlc_id: u64,
309                 failure_code: u16,
310                 sha256_of_onion: [u8; 32],
311         },
312 }
313
314 /// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node,
315 /// which determines the failure message that should be used.
316 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
317 pub enum BlindedFailure {
318         /// This HTLC is being failed backwards by the introduction node, and thus should be failed with
319         /// [`msgs::UpdateFailHTLC`] and error code `0x8000|0x4000|24`.
320         FromIntroductionNode,
321         /// This HTLC is being failed backwards by a blinded node within the path, and thus should be
322         /// failed with [`msgs::UpdateFailMalformedHTLC`] and error code `0x8000|0x4000|24`.
323         FromBlindedNode,
324 }
325
326 /// Tracks the inbound corresponding to an outbound HTLC
327 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
328 pub(crate) struct HTLCPreviousHopData {
329         // Note that this may be an outbound SCID alias for the associated channel.
330         short_channel_id: u64,
331         user_channel_id: Option<u128>,
332         htlc_id: u64,
333         incoming_packet_shared_secret: [u8; 32],
334         phantom_shared_secret: Option<[u8; 32]>,
335         blinded_failure: Option<BlindedFailure>,
336
337         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
338         // channel with a preimage provided by the forward channel.
339         outpoint: OutPoint,
340 }
341
342 enum OnionPayload {
343         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
344         Invoice {
345                 /// This is only here for backwards-compatibility in serialization, in the future it can be
346                 /// removed, breaking clients running 0.0.106 and earlier.
347                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
348         },
349         /// Contains the payer-provided preimage.
350         Spontaneous(PaymentPreimage),
351 }
352
353 /// HTLCs that are to us and can be failed/claimed by the user
354 struct ClaimableHTLC {
355         prev_hop: HTLCPreviousHopData,
356         cltv_expiry: u32,
357         /// The amount (in msats) of this MPP part
358         value: u64,
359         /// The amount (in msats) that the sender intended to be sent in this MPP
360         /// part (used for validating total MPP amount)
361         sender_intended_value: u64,
362         onion_payload: OnionPayload,
363         timer_ticks: u8,
364         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
365         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
366         total_value_received: Option<u64>,
367         /// The sender intended sum total of all MPP parts specified in the onion
368         total_msat: u64,
369         /// The extra fee our counterparty skimmed off the top of this HTLC.
370         counterparty_skimmed_fee_msat: Option<u64>,
371 }
372
373 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
374         fn from(val: &ClaimableHTLC) -> Self {
375                 events::ClaimedHTLC {
376                         channel_id: val.prev_hop.outpoint.to_channel_id(),
377                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
378                         cltv_expiry: val.cltv_expiry,
379                         value_msat: val.value,
380                         counterparty_skimmed_fee_msat: val.counterparty_skimmed_fee_msat.unwrap_or(0),
381                 }
382         }
383 }
384
385 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
386 /// a payment and ensure idempotency in LDK.
387 ///
388 /// This is not exported to bindings users as we just use [u8; 32] directly
389 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
390 pub struct PaymentId(pub [u8; Self::LENGTH]);
391
392 impl PaymentId {
393         /// Number of bytes in the id.
394         pub const LENGTH: usize = 32;
395 }
396
397 impl Writeable for PaymentId {
398         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
399                 self.0.write(w)
400         }
401 }
402
403 impl Readable for PaymentId {
404         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
405                 let buf: [u8; 32] = Readable::read(r)?;
406                 Ok(PaymentId(buf))
407         }
408 }
409
410 impl core::fmt::Display for PaymentId {
411         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
412                 crate::util::logger::DebugBytes(&self.0).fmt(f)
413         }
414 }
415
416 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
417 ///
418 /// This is not exported to bindings users as we just use [u8; 32] directly
419 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
420 pub struct InterceptId(pub [u8; 32]);
421
422 impl Writeable for InterceptId {
423         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
424                 self.0.write(w)
425         }
426 }
427
428 impl Readable for InterceptId {
429         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
430                 let buf: [u8; 32] = Readable::read(r)?;
431                 Ok(InterceptId(buf))
432         }
433 }
434
435 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
436 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
437 pub(crate) enum SentHTLCId {
438         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
439         OutboundRoute { session_priv: [u8; SECRET_KEY_SIZE] },
440 }
441 impl SentHTLCId {
442         pub(crate) fn from_source(source: &HTLCSource) -> Self {
443                 match source {
444                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
445                                 short_channel_id: hop_data.short_channel_id,
446                                 htlc_id: hop_data.htlc_id,
447                         },
448                         HTLCSource::OutboundRoute { session_priv, .. } =>
449                                 Self::OutboundRoute { session_priv: session_priv.secret_bytes() },
450                 }
451         }
452 }
453 impl_writeable_tlv_based_enum!(SentHTLCId,
454         (0, PreviousHopData) => {
455                 (0, short_channel_id, required),
456                 (2, htlc_id, required),
457         },
458         (2, OutboundRoute) => {
459                 (0, session_priv, required),
460         };
461 );
462
463
464 /// Tracks the inbound corresponding to an outbound HTLC
465 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
466 #[derive(Clone, Debug, PartialEq, Eq)]
467 pub(crate) enum HTLCSource {
468         PreviousHopData(HTLCPreviousHopData),
469         OutboundRoute {
470                 path: Path,
471                 session_priv: SecretKey,
472                 /// Technically we can recalculate this from the route, but we cache it here to avoid
473                 /// doing a double-pass on route when we get a failure back
474                 first_hop_htlc_msat: u64,
475                 payment_id: PaymentId,
476         },
477 }
478 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
479 impl core::hash::Hash for HTLCSource {
480         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
481                 match self {
482                         HTLCSource::PreviousHopData(prev_hop_data) => {
483                                 0u8.hash(hasher);
484                                 prev_hop_data.hash(hasher);
485                         },
486                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
487                                 1u8.hash(hasher);
488                                 path.hash(hasher);
489                                 session_priv[..].hash(hasher);
490                                 payment_id.hash(hasher);
491                                 first_hop_htlc_msat.hash(hasher);
492                         },
493                 }
494         }
495 }
496 impl HTLCSource {
497         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
498         #[cfg(test)]
499         pub fn dummy() -> Self {
500                 HTLCSource::OutboundRoute {
501                         path: Path { hops: Vec::new(), blinded_tail: None },
502                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
503                         first_hop_htlc_msat: 0,
504                         payment_id: PaymentId([2; 32]),
505                 }
506         }
507
508         #[cfg(debug_assertions)]
509         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
510         /// transaction. Useful to ensure different datastructures match up.
511         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
512                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
513                         *first_hop_htlc_msat == htlc.amount_msat
514                 } else {
515                         // There's nothing we can check for forwarded HTLCs
516                         true
517                 }
518         }
519 }
520
521 /// This enum is used to specify which error data to send to peers when failing back an HTLC
522 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
523 ///
524 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
525 #[derive(Clone, Copy)]
526 pub enum FailureCode {
527         /// We had a temporary error processing the payment. Useful if no other error codes fit
528         /// and you want to indicate that the payer may want to retry.
529         TemporaryNodeFailure,
530         /// We have a required feature which was not in this onion. For example, you may require
531         /// some additional metadata that was not provided with this payment.
532         RequiredNodeFeatureMissing,
533         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
534         /// the HTLC is too close to the current block height for safe handling.
535         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
536         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
537         IncorrectOrUnknownPaymentDetails,
538         /// We failed to process the payload after the onion was decrypted. You may wish to
539         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
540         ///
541         /// If available, the tuple data may include the type number and byte offset in the
542         /// decrypted byte stream where the failure occurred.
543         InvalidOnionPayload(Option<(u64, u16)>),
544 }
545
546 impl Into<u16> for FailureCode {
547     fn into(self) -> u16 {
548                 match self {
549                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
550                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
551                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
552                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
553                 }
554         }
555 }
556
557 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
558 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
559 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
560 /// peer_state lock. We then return the set of things that need to be done outside the lock in
561 /// this struct and call handle_error!() on it.
562
563 struct MsgHandleErrInternal {
564         err: msgs::LightningError,
565         closes_channel: bool,
566         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
567 }
568 impl MsgHandleErrInternal {
569         #[inline]
570         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
571                 Self {
572                         err: LightningError {
573                                 err: err.clone(),
574                                 action: msgs::ErrorAction::SendErrorMessage {
575                                         msg: msgs::ErrorMessage {
576                                                 channel_id,
577                                                 data: err
578                                         },
579                                 },
580                         },
581                         closes_channel: false,
582                         shutdown_finish: None,
583                 }
584         }
585         #[inline]
586         fn from_no_close(err: msgs::LightningError) -> Self {
587                 Self { err, closes_channel: false, shutdown_finish: None }
588         }
589         #[inline]
590         fn from_finish_shutdown(err: String, channel_id: ChannelId, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
591                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
592                 let action = if shutdown_res.monitor_update.is_some() {
593                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
594                         // should disconnect our peer such that we force them to broadcast their latest
595                         // commitment upon reconnecting.
596                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
597                 } else {
598                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
599                 };
600                 Self {
601                         err: LightningError { err, action },
602                         closes_channel: true,
603                         shutdown_finish: Some((shutdown_res, channel_update)),
604                 }
605         }
606         #[inline]
607         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
608                 Self {
609                         err: match err {
610                                 ChannelError::Warn(msg) =>  LightningError {
611                                         err: msg.clone(),
612                                         action: msgs::ErrorAction::SendWarningMessage {
613                                                 msg: msgs::WarningMessage {
614                                                         channel_id,
615                                                         data: msg
616                                                 },
617                                                 log_level: Level::Warn,
618                                         },
619                                 },
620                                 ChannelError::Ignore(msg) => LightningError {
621                                         err: msg,
622                                         action: msgs::ErrorAction::IgnoreError,
623                                 },
624                                 ChannelError::Close(msg) => LightningError {
625                                         err: msg.clone(),
626                                         action: msgs::ErrorAction::SendErrorMessage {
627                                                 msg: msgs::ErrorMessage {
628                                                         channel_id,
629                                                         data: msg
630                                                 },
631                                         },
632                                 },
633                         },
634                         closes_channel: false,
635                         shutdown_finish: None,
636                 }
637         }
638
639         fn closes_channel(&self) -> bool {
640                 self.closes_channel
641         }
642 }
643
644 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
645 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
646 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
647 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
648 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
649
650 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
651 /// be sent in the order they appear in the return value, however sometimes the order needs to be
652 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
653 /// they were originally sent). In those cases, this enum is also returned.
654 #[derive(Clone, PartialEq)]
655 pub(super) enum RAACommitmentOrder {
656         /// Send the CommitmentUpdate messages first
657         CommitmentFirst,
658         /// Send the RevokeAndACK message first
659         RevokeAndACKFirst,
660 }
661
662 /// Information about a payment which is currently being claimed.
663 struct ClaimingPayment {
664         amount_msat: u64,
665         payment_purpose: events::PaymentPurpose,
666         receiver_node_id: PublicKey,
667         htlcs: Vec<events::ClaimedHTLC>,
668         sender_intended_value: Option<u64>,
669 }
670 impl_writeable_tlv_based!(ClaimingPayment, {
671         (0, amount_msat, required),
672         (2, payment_purpose, required),
673         (4, receiver_node_id, required),
674         (5, htlcs, optional_vec),
675         (7, sender_intended_value, option),
676 });
677
678 struct ClaimablePayment {
679         purpose: events::PaymentPurpose,
680         onion_fields: Option<RecipientOnionFields>,
681         htlcs: Vec<ClaimableHTLC>,
682 }
683
684 /// Information about claimable or being-claimed payments
685 struct ClaimablePayments {
686         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
687         /// failed/claimed by the user.
688         ///
689         /// Note that, no consistency guarantees are made about the channels given here actually
690         /// existing anymore by the time you go to read them!
691         ///
692         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
693         /// we don't get a duplicate payment.
694         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
695
696         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
697         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
698         /// as an [`events::Event::PaymentClaimed`].
699         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
700 }
701
702 /// Events which we process internally but cannot be processed immediately at the generation site
703 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
704 /// running normally, and specifically must be processed before any other non-background
705 /// [`ChannelMonitorUpdate`]s are applied.
706 #[derive(Debug)]
707 enum BackgroundEvent {
708         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
709         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
710         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
711         /// channel has been force-closed we do not need the counterparty node_id.
712         ///
713         /// Note that any such events are lost on shutdown, so in general they must be updates which
714         /// are regenerated on startup.
715         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
716         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
717         /// channel to continue normal operation.
718         ///
719         /// In general this should be used rather than
720         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
721         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
722         /// error the other variant is acceptable.
723         ///
724         /// Note that any such events are lost on shutdown, so in general they must be updates which
725         /// are regenerated on startup.
726         MonitorUpdateRegeneratedOnStartup {
727                 counterparty_node_id: PublicKey,
728                 funding_txo: OutPoint,
729                 update: ChannelMonitorUpdate
730         },
731         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
732         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
733         /// on a channel.
734         MonitorUpdatesComplete {
735                 counterparty_node_id: PublicKey,
736                 channel_id: ChannelId,
737         },
738 }
739
740 #[derive(Debug)]
741 pub(crate) enum MonitorUpdateCompletionAction {
742         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
743         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
744         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
745         /// event can be generated.
746         PaymentClaimed { payment_hash: PaymentHash },
747         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
748         /// operation of another channel.
749         ///
750         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
751         /// from completing a monitor update which removes the payment preimage until the inbound edge
752         /// completes a monitor update containing the payment preimage. In that case, after the inbound
753         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
754         /// outbound edge.
755         EmitEventAndFreeOtherChannel {
756                 event: events::Event,
757                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
758         },
759         /// Indicates we should immediately resume the operation of another channel, unless there is
760         /// some other reason why the channel is blocked. In practice this simply means immediately
761         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
762         ///
763         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
764         /// from completing a monitor update which removes the payment preimage until the inbound edge
765         /// completes a monitor update containing the payment preimage. However, we use this variant
766         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
767         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
768         ///
769         /// This variant should thus never be written to disk, as it is processed inline rather than
770         /// stored for later processing.
771         FreeOtherChannelImmediately {
772                 downstream_counterparty_node_id: PublicKey,
773                 downstream_funding_outpoint: OutPoint,
774                 blocking_action: RAAMonitorUpdateBlockingAction,
775         },
776 }
777
778 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
779         (0, PaymentClaimed) => { (0, payment_hash, required) },
780         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
781         // *immediately*. However, for simplicity we implement read/write here.
782         (1, FreeOtherChannelImmediately) => {
783                 (0, downstream_counterparty_node_id, required),
784                 (2, downstream_funding_outpoint, required),
785                 (4, blocking_action, required),
786         },
787         (2, EmitEventAndFreeOtherChannel) => {
788                 (0, event, upgradable_required),
789                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
790                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
791                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
792                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
793                 // downgrades to prior versions.
794                 (1, downstream_counterparty_and_funding_outpoint, option),
795         },
796 );
797
798 #[derive(Clone, Debug, PartialEq, Eq)]
799 pub(crate) enum EventCompletionAction {
800         ReleaseRAAChannelMonitorUpdate {
801                 counterparty_node_id: PublicKey,
802                 channel_funding_outpoint: OutPoint,
803         },
804 }
805 impl_writeable_tlv_based_enum!(EventCompletionAction,
806         (0, ReleaseRAAChannelMonitorUpdate) => {
807                 (0, channel_funding_outpoint, required),
808                 (2, counterparty_node_id, required),
809         };
810 );
811
812 #[derive(Clone, PartialEq, Eq, Debug)]
813 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
814 /// the blocked action here. See enum variants for more info.
815 pub(crate) enum RAAMonitorUpdateBlockingAction {
816         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
817         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
818         /// durably to disk.
819         ForwardedPaymentInboundClaim {
820                 /// The upstream channel ID (i.e. the inbound edge).
821                 channel_id: ChannelId,
822                 /// The HTLC ID on the inbound edge.
823                 htlc_id: u64,
824         },
825 }
826
827 impl RAAMonitorUpdateBlockingAction {
828         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
829                 Self::ForwardedPaymentInboundClaim {
830                         channel_id: prev_hop.outpoint.to_channel_id(),
831                         htlc_id: prev_hop.htlc_id,
832                 }
833         }
834 }
835
836 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
837         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
838 ;);
839
840
841 /// State we hold per-peer.
842 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
843         /// `channel_id` -> `ChannelPhase`
844         ///
845         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
846         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
847         /// `temporary_channel_id` -> `InboundChannelRequest`.
848         ///
849         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
850         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
851         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
852         /// the channel is rejected, then the entry is simply removed.
853         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
854         /// The latest `InitFeatures` we heard from the peer.
855         latest_features: InitFeatures,
856         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
857         /// for broadcast messages, where ordering isn't as strict).
858         pub(super) pending_msg_events: Vec<MessageSendEvent>,
859         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
860         /// user but which have not yet completed.
861         ///
862         /// Note that the channel may no longer exist. For example if the channel was closed but we
863         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
864         /// for a missing channel.
865         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
866         /// Map from a specific channel to some action(s) that should be taken when all pending
867         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
868         ///
869         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
870         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
871         /// channels with a peer this will just be one allocation and will amount to a linear list of
872         /// channels to walk, avoiding the whole hashing rigmarole.
873         ///
874         /// Note that the channel may no longer exist. For example, if a channel was closed but we
875         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
876         /// for a missing channel. While a malicious peer could construct a second channel with the
877         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
878         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
879         /// duplicates do not occur, so such channels should fail without a monitor update completing.
880         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
881         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
882         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
883         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
884         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
885         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
886         /// The peer is currently connected (i.e. we've seen a
887         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
888         /// [`ChannelMessageHandler::peer_disconnected`].
889         is_connected: bool,
890 }
891
892 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
893         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
894         /// If true is passed for `require_disconnected`, the function will return false if we haven't
895         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
896         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
897                 if require_disconnected && self.is_connected {
898                         return false
899                 }
900                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
901                         && self.monitor_update_blocked_actions.is_empty()
902                         && self.in_flight_monitor_updates.is_empty()
903         }
904
905         // Returns a count of all channels we have with this peer, including unfunded channels.
906         fn total_channel_count(&self) -> usize {
907                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
908         }
909
910         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
911         fn has_channel(&self, channel_id: &ChannelId) -> bool {
912                 self.channel_by_id.contains_key(channel_id) ||
913                         self.inbound_channel_request_by_id.contains_key(channel_id)
914         }
915 }
916
917 /// A not-yet-accepted inbound (from counterparty) channel. Once
918 /// accepted, the parameters will be used to construct a channel.
919 pub(super) struct InboundChannelRequest {
920         /// The original OpenChannel message.
921         pub open_channel_msg: msgs::OpenChannel,
922         /// The number of ticks remaining before the request expires.
923         pub ticks_remaining: i32,
924 }
925
926 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
927 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
928 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
929
930 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
931 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
932 ///
933 /// For users who don't want to bother doing their own payment preimage storage, we also store that
934 /// here.
935 ///
936 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
937 /// and instead encoding it in the payment secret.
938 struct PendingInboundPayment {
939         /// The payment secret that the sender must use for us to accept this payment
940         payment_secret: PaymentSecret,
941         /// Time at which this HTLC expires - blocks with a header time above this value will result in
942         /// this payment being removed.
943         expiry_time: u64,
944         /// Arbitrary identifier the user specifies (or not)
945         user_payment_id: u64,
946         // Other required attributes of the payment, optionally enforced:
947         payment_preimage: Option<PaymentPreimage>,
948         min_value_msat: Option<u64>,
949 }
950
951 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
952 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
953 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
954 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
955 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
956 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
957 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
958 /// of [`KeysManager`] and [`DefaultRouter`].
959 ///
960 /// This is not exported to bindings users as type aliases aren't supported in most languages.
961 #[cfg(not(c_bindings))]
962 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
963         Arc<M>,
964         Arc<T>,
965         Arc<KeysManager>,
966         Arc<KeysManager>,
967         Arc<KeysManager>,
968         Arc<F>,
969         Arc<DefaultRouter<
970                 Arc<NetworkGraph<Arc<L>>>,
971                 Arc<L>,
972                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
973                 ProbabilisticScoringFeeParameters,
974                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
975         >>,
976         Arc<L>
977 >;
978
979 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
980 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
981 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
982 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
983 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
984 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
985 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
986 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
987 /// of [`KeysManager`] and [`DefaultRouter`].
988 ///
989 /// This is not exported to bindings users as type aliases aren't supported in most languages.
990 #[cfg(not(c_bindings))]
991 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
992         ChannelManager<
993                 &'a M,
994                 &'b T,
995                 &'c KeysManager,
996                 &'c KeysManager,
997                 &'c KeysManager,
998                 &'d F,
999                 &'e DefaultRouter<
1000                         &'f NetworkGraph<&'g L>,
1001                         &'g L,
1002                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
1003                         ProbabilisticScoringFeeParameters,
1004                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
1005                 >,
1006                 &'g L
1007         >;
1008
1009 /// A trivial trait which describes any [`ChannelManager`].
1010 ///
1011 /// This is not exported to bindings users as general cover traits aren't useful in other
1012 /// languages.
1013 pub trait AChannelManager {
1014         /// A type implementing [`chain::Watch`].
1015         type Watch: chain::Watch<Self::Signer> + ?Sized;
1016         /// A type that may be dereferenced to [`Self::Watch`].
1017         type M: Deref<Target = Self::Watch>;
1018         /// A type implementing [`BroadcasterInterface`].
1019         type Broadcaster: BroadcasterInterface + ?Sized;
1020         /// A type that may be dereferenced to [`Self::Broadcaster`].
1021         type T: Deref<Target = Self::Broadcaster>;
1022         /// A type implementing [`EntropySource`].
1023         type EntropySource: EntropySource + ?Sized;
1024         /// A type that may be dereferenced to [`Self::EntropySource`].
1025         type ES: Deref<Target = Self::EntropySource>;
1026         /// A type implementing [`NodeSigner`].
1027         type NodeSigner: NodeSigner + ?Sized;
1028         /// A type that may be dereferenced to [`Self::NodeSigner`].
1029         type NS: Deref<Target = Self::NodeSigner>;
1030         /// A type implementing [`WriteableEcdsaChannelSigner`].
1031         type Signer: WriteableEcdsaChannelSigner + Sized;
1032         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
1033         type SignerProvider: SignerProvider<EcdsaSigner= Self::Signer> + ?Sized;
1034         /// A type that may be dereferenced to [`Self::SignerProvider`].
1035         type SP: Deref<Target = Self::SignerProvider>;
1036         /// A type implementing [`FeeEstimator`].
1037         type FeeEstimator: FeeEstimator + ?Sized;
1038         /// A type that may be dereferenced to [`Self::FeeEstimator`].
1039         type F: Deref<Target = Self::FeeEstimator>;
1040         /// A type implementing [`Router`].
1041         type Router: Router + ?Sized;
1042         /// A type that may be dereferenced to [`Self::Router`].
1043         type R: Deref<Target = Self::Router>;
1044         /// A type implementing [`Logger`].
1045         type Logger: Logger + ?Sized;
1046         /// A type that may be dereferenced to [`Self::Logger`].
1047         type L: Deref<Target = Self::Logger>;
1048         /// Returns a reference to the actual [`ChannelManager`] object.
1049         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
1050 }
1051
1052 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
1053 for ChannelManager<M, T, ES, NS, SP, F, R, L>
1054 where
1055         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1056         T::Target: BroadcasterInterface,
1057         ES::Target: EntropySource,
1058         NS::Target: NodeSigner,
1059         SP::Target: SignerProvider,
1060         F::Target: FeeEstimator,
1061         R::Target: Router,
1062         L::Target: Logger,
1063 {
1064         type Watch = M::Target;
1065         type M = M;
1066         type Broadcaster = T::Target;
1067         type T = T;
1068         type EntropySource = ES::Target;
1069         type ES = ES;
1070         type NodeSigner = NS::Target;
1071         type NS = NS;
1072         type Signer = <SP::Target as SignerProvider>::EcdsaSigner;
1073         type SignerProvider = SP::Target;
1074         type SP = SP;
1075         type FeeEstimator = F::Target;
1076         type F = F;
1077         type Router = R::Target;
1078         type R = R;
1079         type Logger = L::Target;
1080         type L = L;
1081         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
1082 }
1083
1084 /// Manager which keeps track of a number of channels and sends messages to the appropriate
1085 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
1086 ///
1087 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
1088 /// to individual Channels.
1089 ///
1090 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
1091 /// all peers during write/read (though does not modify this instance, only the instance being
1092 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
1093 /// called [`funding_transaction_generated`] for outbound channels) being closed.
1094 ///
1095 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
1096 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
1097 /// [`ChannelMonitorUpdate`] before returning from
1098 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
1099 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
1100 /// `ChannelManager` operations from occurring during the serialization process). If the
1101 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
1102 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
1103 /// will be lost (modulo on-chain transaction fees).
1104 ///
1105 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
1106 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
1107 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
1108 ///
1109 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
1110 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
1111 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
1112 /// offline for a full minute. In order to track this, you must call
1113 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1114 ///
1115 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1116 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1117 /// not have a channel with being unable to connect to us or open new channels with us if we have
1118 /// many peers with unfunded channels.
1119 ///
1120 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1121 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1122 /// never limited. Please ensure you limit the count of such channels yourself.
1123 ///
1124 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1125 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1126 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1127 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1128 /// you're using lightning-net-tokio.
1129 ///
1130 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1131 /// [`funding_created`]: msgs::FundingCreated
1132 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1133 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1134 /// [`update_channel`]: chain::Watch::update_channel
1135 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1136 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1137 /// [`read`]: ReadableArgs::read
1138 //
1139 // Lock order:
1140 // The tree structure below illustrates the lock order requirements for the different locks of the
1141 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1142 // and should then be taken in the order of the lowest to the highest level in the tree.
1143 // Note that locks on different branches shall not be taken at the same time, as doing so will
1144 // create a new lock order for those specific locks in the order they were taken.
1145 //
1146 // Lock order tree:
1147 //
1148 // `pending_offers_messages`
1149 //
1150 // `total_consistency_lock`
1151 //  |
1152 //  |__`forward_htlcs`
1153 //  |   |
1154 //  |   |__`pending_intercepted_htlcs`
1155 //  |
1156 //  |__`per_peer_state`
1157 //      |
1158 //      |__`pending_inbound_payments`
1159 //          |
1160 //          |__`claimable_payments`
1161 //          |
1162 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1163 //              |
1164 //              |__`peer_state`
1165 //                  |
1166 //                  |__`outpoint_to_peer`
1167 //                  |
1168 //                  |__`short_to_chan_info`
1169 //                  |
1170 //                  |__`outbound_scid_aliases`
1171 //                  |
1172 //                  |__`best_block`
1173 //                  |
1174 //                  |__`pending_events`
1175 //                      |
1176 //                      |__`pending_background_events`
1177 //
1178 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1179 where
1180         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1181         T::Target: BroadcasterInterface,
1182         ES::Target: EntropySource,
1183         NS::Target: NodeSigner,
1184         SP::Target: SignerProvider,
1185         F::Target: FeeEstimator,
1186         R::Target: Router,
1187         L::Target: Logger,
1188 {
1189         default_configuration: UserConfig,
1190         chain_hash: ChainHash,
1191         fee_estimator: LowerBoundedFeeEstimator<F>,
1192         chain_monitor: M,
1193         tx_broadcaster: T,
1194         #[allow(unused)]
1195         router: R,
1196
1197         /// See `ChannelManager` struct-level documentation for lock order requirements.
1198         #[cfg(test)]
1199         pub(super) best_block: RwLock<BestBlock>,
1200         #[cfg(not(test))]
1201         best_block: RwLock<BestBlock>,
1202         secp_ctx: Secp256k1<secp256k1::All>,
1203
1204         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1205         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1206         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1207         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1208         ///
1209         /// See `ChannelManager` struct-level documentation for lock order requirements.
1210         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1211
1212         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1213         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1214         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1215         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1216         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1217         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1218         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1219         /// after reloading from disk while replaying blocks against ChannelMonitors.
1220         ///
1221         /// See `PendingOutboundPayment` documentation for more info.
1222         ///
1223         /// See `ChannelManager` struct-level documentation for lock order requirements.
1224         pending_outbound_payments: OutboundPayments,
1225
1226         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1227         ///
1228         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1229         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1230         /// and via the classic SCID.
1231         ///
1232         /// Note that no consistency guarantees are made about the existence of a channel with the
1233         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1234         ///
1235         /// See `ChannelManager` struct-level documentation for lock order requirements.
1236         #[cfg(test)]
1237         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1238         #[cfg(not(test))]
1239         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1240         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1241         /// until the user tells us what we should do with them.
1242         ///
1243         /// See `ChannelManager` struct-level documentation for lock order requirements.
1244         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1245
1246         /// The sets of payments which are claimable or currently being claimed. See
1247         /// [`ClaimablePayments`]' individual field docs for more info.
1248         ///
1249         /// See `ChannelManager` struct-level documentation for lock order requirements.
1250         claimable_payments: Mutex<ClaimablePayments>,
1251
1252         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1253         /// and some closed channels which reached a usable state prior to being closed. This is used
1254         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1255         /// active channel list on load.
1256         ///
1257         /// See `ChannelManager` struct-level documentation for lock order requirements.
1258         outbound_scid_aliases: Mutex<HashSet<u64>>,
1259
1260         /// Channel funding outpoint -> `counterparty_node_id`.
1261         ///
1262         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1263         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1264         /// the handling of the events.
1265         ///
1266         /// Note that no consistency guarantees are made about the existence of a peer with the
1267         /// `counterparty_node_id` in our other maps.
1268         ///
1269         /// TODO:
1270         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1271         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1272         /// would break backwards compatability.
1273         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1274         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1275         /// required to access the channel with the `counterparty_node_id`.
1276         ///
1277         /// See `ChannelManager` struct-level documentation for lock order requirements.
1278         #[cfg(not(test))]
1279         outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1280         #[cfg(test)]
1281         pub(crate) outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1282
1283         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1284         ///
1285         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1286         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1287         /// confirmation depth.
1288         ///
1289         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1290         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1291         /// channel with the `channel_id` in our other maps.
1292         ///
1293         /// See `ChannelManager` struct-level documentation for lock order requirements.
1294         #[cfg(test)]
1295         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1296         #[cfg(not(test))]
1297         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1298
1299         our_network_pubkey: PublicKey,
1300
1301         inbound_payment_key: inbound_payment::ExpandedKey,
1302
1303         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1304         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1305         /// we encrypt the namespace identifier using these bytes.
1306         ///
1307         /// [fake scids]: crate::util::scid_utils::fake_scid
1308         fake_scid_rand_bytes: [u8; 32],
1309
1310         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1311         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1312         /// keeping additional state.
1313         probing_cookie_secret: [u8; 32],
1314
1315         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1316         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1317         /// very far in the past, and can only ever be up to two hours in the future.
1318         highest_seen_timestamp: AtomicUsize,
1319
1320         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1321         /// basis, as well as the peer's latest features.
1322         ///
1323         /// If we are connected to a peer we always at least have an entry here, even if no channels
1324         /// are currently open with that peer.
1325         ///
1326         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1327         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1328         /// channels.
1329         ///
1330         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1331         ///
1332         /// See `ChannelManager` struct-level documentation for lock order requirements.
1333         #[cfg(not(any(test, feature = "_test_utils")))]
1334         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1335         #[cfg(any(test, feature = "_test_utils"))]
1336         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1337
1338         /// The set of events which we need to give to the user to handle. In some cases an event may
1339         /// require some further action after the user handles it (currently only blocking a monitor
1340         /// update from being handed to the user to ensure the included changes to the channel state
1341         /// are handled by the user before they're persisted durably to disk). In that case, the second
1342         /// element in the tuple is set to `Some` with further details of the action.
1343         ///
1344         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1345         /// could be in the middle of being processed without the direct mutex held.
1346         ///
1347         /// See `ChannelManager` struct-level documentation for lock order requirements.
1348         #[cfg(not(any(test, feature = "_test_utils")))]
1349         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1350         #[cfg(any(test, feature = "_test_utils"))]
1351         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1352
1353         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1354         pending_events_processor: AtomicBool,
1355
1356         /// If we are running during init (either directly during the deserialization method or in
1357         /// block connection methods which run after deserialization but before normal operation) we
1358         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1359         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1360         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1361         ///
1362         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1363         ///
1364         /// See `ChannelManager` struct-level documentation for lock order requirements.
1365         ///
1366         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1367         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1368         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1369         /// Essentially just when we're serializing ourselves out.
1370         /// Taken first everywhere where we are making changes before any other locks.
1371         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1372         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1373         /// Notifier the lock contains sends out a notification when the lock is released.
1374         total_consistency_lock: RwLock<()>,
1375         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1376         /// received and the monitor has been persisted.
1377         ///
1378         /// This information does not need to be persisted as funding nodes can forget
1379         /// unfunded channels upon disconnection.
1380         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1381
1382         background_events_processed_since_startup: AtomicBool,
1383
1384         event_persist_notifier: Notifier,
1385         needs_persist_flag: AtomicBool,
1386
1387         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1388
1389         entropy_source: ES,
1390         node_signer: NS,
1391         signer_provider: SP,
1392
1393         logger: L,
1394 }
1395
1396 /// Chain-related parameters used to construct a new `ChannelManager`.
1397 ///
1398 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1399 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1400 /// are not needed when deserializing a previously constructed `ChannelManager`.
1401 #[derive(Clone, Copy, PartialEq)]
1402 pub struct ChainParameters {
1403         /// The network for determining the `chain_hash` in Lightning messages.
1404         pub network: Network,
1405
1406         /// The hash and height of the latest block successfully connected.
1407         ///
1408         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1409         pub best_block: BestBlock,
1410 }
1411
1412 #[derive(Copy, Clone, PartialEq)]
1413 #[must_use]
1414 enum NotifyOption {
1415         DoPersist,
1416         SkipPersistHandleEvents,
1417         SkipPersistNoEvents,
1418 }
1419
1420 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1421 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1422 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1423 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1424 /// sending the aforementioned notification (since the lock being released indicates that the
1425 /// updates are ready for persistence).
1426 ///
1427 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1428 /// notify or not based on whether relevant changes have been made, providing a closure to
1429 /// `optionally_notify` which returns a `NotifyOption`.
1430 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1431         event_persist_notifier: &'a Notifier,
1432         needs_persist_flag: &'a AtomicBool,
1433         should_persist: F,
1434         // We hold onto this result so the lock doesn't get released immediately.
1435         _read_guard: RwLockReadGuard<'a, ()>,
1436 }
1437
1438 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1439         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1440         /// events to handle.
1441         ///
1442         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1443         /// other cases where losing the changes on restart may result in a force-close or otherwise
1444         /// isn't ideal.
1445         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1446                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1447         }
1448
1449         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1450         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1451                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1452                 let force_notify = cm.get_cm().process_background_events();
1453
1454                 PersistenceNotifierGuard {
1455                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1456                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1457                         should_persist: move || {
1458                                 // Pick the "most" action between `persist_check` and the background events
1459                                 // processing and return that.
1460                                 let notify = persist_check();
1461                                 match (notify, force_notify) {
1462                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1463                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1464                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1465                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1466                                         _ => NotifyOption::SkipPersistNoEvents,
1467                                 }
1468                         },
1469                         _read_guard: read_guard,
1470                 }
1471         }
1472
1473         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1474         /// [`ChannelManager::process_background_events`] MUST be called first (or
1475         /// [`Self::optionally_notify`] used).
1476         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1477         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1478                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1479
1480                 PersistenceNotifierGuard {
1481                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1482                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1483                         should_persist: persist_check,
1484                         _read_guard: read_guard,
1485                 }
1486         }
1487 }
1488
1489 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1490         fn drop(&mut self) {
1491                 match (self.should_persist)() {
1492                         NotifyOption::DoPersist => {
1493                                 self.needs_persist_flag.store(true, Ordering::Release);
1494                                 self.event_persist_notifier.notify()
1495                         },
1496                         NotifyOption::SkipPersistHandleEvents =>
1497                                 self.event_persist_notifier.notify(),
1498                         NotifyOption::SkipPersistNoEvents => {},
1499                 }
1500         }
1501 }
1502
1503 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1504 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1505 ///
1506 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1507 ///
1508 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1509 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1510 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1511 /// the maximum required amount in lnd as of March 2021.
1512 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1513
1514 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1515 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1516 ///
1517 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1518 ///
1519 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1520 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1521 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1522 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1523 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1524 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1525 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1526 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1527 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1528 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1529 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1530 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1531 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1532
1533 /// Minimum CLTV difference between the current block height and received inbound payments.
1534 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1535 /// this value.
1536 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1537 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1538 // a payment was being routed, so we add an extra block to be safe.
1539 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1540
1541 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1542 // ie that if the next-hop peer fails the HTLC within
1543 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1544 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1545 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1546 // LATENCY_GRACE_PERIOD_BLOCKS.
1547 #[allow(dead_code)]
1548 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;
1549
1550 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1551 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1552 #[allow(dead_code)]
1553 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1554
1555 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1556 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1557
1558 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1559 /// until we mark the channel disabled and gossip the update.
1560 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1561
1562 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1563 /// we mark the channel enabled and gossip the update.
1564 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1565
1566 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1567 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1568 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1569 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1570
1571 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1572 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1573 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1574
1575 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1576 /// many peers we reject new (inbound) connections.
1577 const MAX_NO_CHANNEL_PEERS: usize = 250;
1578
1579 /// Information needed for constructing an invoice route hint for this channel.
1580 #[derive(Clone, Debug, PartialEq)]
1581 pub struct CounterpartyForwardingInfo {
1582         /// Base routing fee in millisatoshis.
1583         pub fee_base_msat: u32,
1584         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1585         pub fee_proportional_millionths: u32,
1586         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1587         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1588         /// `cltv_expiry_delta` for more details.
1589         pub cltv_expiry_delta: u16,
1590 }
1591
1592 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1593 /// to better separate parameters.
1594 #[derive(Clone, Debug, PartialEq)]
1595 pub struct ChannelCounterparty {
1596         /// The node_id of our counterparty
1597         pub node_id: PublicKey,
1598         /// The Features the channel counterparty provided upon last connection.
1599         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1600         /// many routing-relevant features are present in the init context.
1601         pub features: InitFeatures,
1602         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1603         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1604         /// claiming at least this value on chain.
1605         ///
1606         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1607         ///
1608         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1609         pub unspendable_punishment_reserve: u64,
1610         /// Information on the fees and requirements that the counterparty requires when forwarding
1611         /// payments to us through this channel.
1612         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1613         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1614         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1615         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1616         pub outbound_htlc_minimum_msat: Option<u64>,
1617         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1618         pub outbound_htlc_maximum_msat: Option<u64>,
1619 }
1620
1621 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1622 #[derive(Clone, Debug, PartialEq)]
1623 pub struct ChannelDetails {
1624         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1625         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1626         /// Note that this means this value is *not* persistent - it can change once during the
1627         /// lifetime of the channel.
1628         pub channel_id: ChannelId,
1629         /// Parameters which apply to our counterparty. See individual fields for more information.
1630         pub counterparty: ChannelCounterparty,
1631         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1632         /// our counterparty already.
1633         ///
1634         /// Note that, if this has been set, `channel_id` will be equivalent to
1635         /// `funding_txo.unwrap().to_channel_id()`.
1636         pub funding_txo: Option<OutPoint>,
1637         /// The features which this channel operates with. See individual features for more info.
1638         ///
1639         /// `None` until negotiation completes and the channel type is finalized.
1640         pub channel_type: Option<ChannelTypeFeatures>,
1641         /// The position of the funding transaction in the chain. None if the funding transaction has
1642         /// not yet been confirmed and the channel fully opened.
1643         ///
1644         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1645         /// payments instead of this. See [`get_inbound_payment_scid`].
1646         ///
1647         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1648         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1649         ///
1650         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1651         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1652         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1653         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1654         /// [`confirmations_required`]: Self::confirmations_required
1655         pub short_channel_id: Option<u64>,
1656         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1657         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1658         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1659         /// `Some(0)`).
1660         ///
1661         /// This will be `None` as long as the channel is not available for routing outbound payments.
1662         ///
1663         /// [`short_channel_id`]: Self::short_channel_id
1664         /// [`confirmations_required`]: Self::confirmations_required
1665         pub outbound_scid_alias: Option<u64>,
1666         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1667         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1668         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1669         /// when they see a payment to be routed to us.
1670         ///
1671         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1672         /// previous values for inbound payment forwarding.
1673         ///
1674         /// [`short_channel_id`]: Self::short_channel_id
1675         pub inbound_scid_alias: Option<u64>,
1676         /// The value, in satoshis, of this channel as appears in the funding output
1677         pub channel_value_satoshis: u64,
1678         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1679         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1680         /// this value on chain.
1681         ///
1682         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1683         ///
1684         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1685         ///
1686         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1687         pub unspendable_punishment_reserve: Option<u64>,
1688         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1689         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1690         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1691         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1692         /// serialized with LDK versions prior to 0.0.113.
1693         ///
1694         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1695         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1696         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1697         pub user_channel_id: u128,
1698         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1699         /// which is applied to commitment and HTLC transactions.
1700         ///
1701         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1702         pub feerate_sat_per_1000_weight: Option<u32>,
1703         /// Our total balance.  This is the amount we would get if we close the channel.
1704         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1705         /// amount is not likely to be recoverable on close.
1706         ///
1707         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1708         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1709         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1710         /// This does not consider any on-chain fees.
1711         ///
1712         /// See also [`ChannelDetails::outbound_capacity_msat`]
1713         pub balance_msat: u64,
1714         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1715         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1716         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1717         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1718         ///
1719         /// See also [`ChannelDetails::balance_msat`]
1720         ///
1721         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1722         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1723         /// should be able to spend nearly this amount.
1724         pub outbound_capacity_msat: u64,
1725         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1726         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1727         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1728         /// to use a limit as close as possible to the HTLC limit we can currently send.
1729         ///
1730         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1731         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1732         pub next_outbound_htlc_limit_msat: u64,
1733         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1734         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1735         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1736         /// route which is valid.
1737         pub next_outbound_htlc_minimum_msat: u64,
1738         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1739         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1740         /// available for inclusion in new inbound HTLCs).
1741         /// Note that there are some corner cases not fully handled here, so the actual available
1742         /// inbound capacity may be slightly higher than this.
1743         ///
1744         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1745         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1746         /// However, our counterparty should be able to spend nearly this amount.
1747         pub inbound_capacity_msat: u64,
1748         /// The number of required confirmations on the funding transaction before the funding will be
1749         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1750         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1751         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1752         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1753         ///
1754         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1755         ///
1756         /// [`is_outbound`]: ChannelDetails::is_outbound
1757         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1758         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1759         pub confirmations_required: Option<u32>,
1760         /// The current number of confirmations on the funding transaction.
1761         ///
1762         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1763         pub confirmations: Option<u32>,
1764         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1765         /// until we can claim our funds after we force-close the channel. During this time our
1766         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1767         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1768         /// time to claim our non-HTLC-encumbered funds.
1769         ///
1770         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1771         pub force_close_spend_delay: Option<u16>,
1772         /// True if the channel was initiated (and thus funded) by us.
1773         pub is_outbound: bool,
1774         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1775         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1776         /// required confirmation count has been reached (and we were connected to the peer at some
1777         /// point after the funding transaction received enough confirmations). The required
1778         /// confirmation count is provided in [`confirmations_required`].
1779         ///
1780         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1781         pub is_channel_ready: bool,
1782         /// The stage of the channel's shutdown.
1783         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1784         pub channel_shutdown_state: Option<ChannelShutdownState>,
1785         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1786         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1787         ///
1788         /// This is a strict superset of `is_channel_ready`.
1789         pub is_usable: bool,
1790         /// True if this channel is (or will be) publicly-announced.
1791         pub is_public: bool,
1792         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1793         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1794         pub inbound_htlc_minimum_msat: Option<u64>,
1795         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1796         pub inbound_htlc_maximum_msat: Option<u64>,
1797         /// Set of configurable parameters that affect channel operation.
1798         ///
1799         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1800         pub config: Option<ChannelConfig>,
1801 }
1802
1803 impl ChannelDetails {
1804         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1805         /// This should be used for providing invoice hints or in any other context where our
1806         /// counterparty will forward a payment to us.
1807         ///
1808         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1809         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1810         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1811                 self.inbound_scid_alias.or(self.short_channel_id)
1812         }
1813
1814         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1815         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1816         /// we're sending or forwarding a payment outbound over this channel.
1817         ///
1818         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1819         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1820         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1821                 self.short_channel_id.or(self.outbound_scid_alias)
1822         }
1823
1824         fn from_channel_context<SP: Deref, F: Deref>(
1825                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1826                 fee_estimator: &LowerBoundedFeeEstimator<F>
1827         ) -> Self
1828         where
1829                 SP::Target: SignerProvider,
1830                 F::Target: FeeEstimator
1831         {
1832                 let balance = context.get_available_balances(fee_estimator);
1833                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1834                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1835                 ChannelDetails {
1836                         channel_id: context.channel_id(),
1837                         counterparty: ChannelCounterparty {
1838                                 node_id: context.get_counterparty_node_id(),
1839                                 features: latest_features,
1840                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1841                                 forwarding_info: context.counterparty_forwarding_info(),
1842                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1843                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1844                                 // message (as they are always the first message from the counterparty).
1845                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1846                                 // default `0` value set by `Channel::new_outbound`.
1847                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1848                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1849                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1850                         },
1851                         funding_txo: context.get_funding_txo(),
1852                         // Note that accept_channel (or open_channel) is always the first message, so
1853                         // `have_received_message` indicates that type negotiation has completed.
1854                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1855                         short_channel_id: context.get_short_channel_id(),
1856                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1857                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1858                         channel_value_satoshis: context.get_value_satoshis(),
1859                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1860                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1861                         balance_msat: balance.balance_msat,
1862                         inbound_capacity_msat: balance.inbound_capacity_msat,
1863                         outbound_capacity_msat: balance.outbound_capacity_msat,
1864                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1865                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1866                         user_channel_id: context.get_user_id(),
1867                         confirmations_required: context.minimum_depth(),
1868                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1869                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1870                         is_outbound: context.is_outbound(),
1871                         is_channel_ready: context.is_usable(),
1872                         is_usable: context.is_live(),
1873                         is_public: context.should_announce(),
1874                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1875                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1876                         config: Some(context.config()),
1877                         channel_shutdown_state: Some(context.shutdown_state()),
1878                 }
1879         }
1880 }
1881
1882 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1883 /// Further information on the details of the channel shutdown.
1884 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1885 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1886 /// the channel will be removed shortly.
1887 /// Also note, that in normal operation, peers could disconnect at any of these states
1888 /// and require peer re-connection before making progress onto other states
1889 pub enum ChannelShutdownState {
1890         /// Channel has not sent or received a shutdown message.
1891         NotShuttingDown,
1892         /// Local node has sent a shutdown message for this channel.
1893         ShutdownInitiated,
1894         /// Shutdown message exchanges have concluded and the channels are in the midst of
1895         /// resolving all existing open HTLCs before closing can continue.
1896         ResolvingHTLCs,
1897         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1898         NegotiatingClosingFee,
1899         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1900         /// to drop the channel.
1901         ShutdownComplete,
1902 }
1903
1904 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1905 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1906 #[derive(Debug, PartialEq)]
1907 pub enum RecentPaymentDetails {
1908         /// When an invoice was requested and thus a payment has not yet been sent.
1909         AwaitingInvoice {
1910                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1911                 /// a payment and ensure idempotency in LDK.
1912                 payment_id: PaymentId,
1913         },
1914         /// When a payment is still being sent and awaiting successful delivery.
1915         Pending {
1916                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1917                 /// a payment and ensure idempotency in LDK.
1918                 payment_id: PaymentId,
1919                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1920                 /// abandoned.
1921                 payment_hash: PaymentHash,
1922                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1923                 /// not just the amount currently inflight.
1924                 total_msat: u64,
1925         },
1926         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1927         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1928         /// payment is removed from tracking.
1929         Fulfilled {
1930                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1931                 /// a payment and ensure idempotency in LDK.
1932                 payment_id: PaymentId,
1933                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1934                 /// made before LDK version 0.0.104.
1935                 payment_hash: Option<PaymentHash>,
1936         },
1937         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1938         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1939         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1940         Abandoned {
1941                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1942                 /// a payment and ensure idempotency in LDK.
1943                 payment_id: PaymentId,
1944                 /// Hash of the payment that we have given up trying to send.
1945                 payment_hash: PaymentHash,
1946         },
1947 }
1948
1949 /// Route hints used in constructing invoices for [phantom node payents].
1950 ///
1951 /// [phantom node payments]: crate::sign::PhantomKeysManager
1952 #[derive(Clone)]
1953 pub struct PhantomRouteHints {
1954         /// The list of channels to be included in the invoice route hints.
1955         pub channels: Vec<ChannelDetails>,
1956         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1957         /// route hints.
1958         pub phantom_scid: u64,
1959         /// The pubkey of the real backing node that would ultimately receive the payment.
1960         pub real_node_pubkey: PublicKey,
1961 }
1962
1963 macro_rules! handle_error {
1964         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1965                 // In testing, ensure there are no deadlocks where the lock is already held upon
1966                 // entering the macro.
1967                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1968                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1969
1970                 match $internal {
1971                         Ok(msg) => Ok(msg),
1972                         Err(MsgHandleErrInternal { err, shutdown_finish, .. }) => {
1973                                 let mut msg_events = Vec::with_capacity(2);
1974
1975                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1976                                         let counterparty_node_id = shutdown_res.counterparty_node_id;
1977                                         let channel_id = shutdown_res.channel_id;
1978                                         let logger = WithContext::from(
1979                                                 &$self.logger, Some(counterparty_node_id), Some(channel_id),
1980                                         );
1981                                         log_error!(logger, "Force-closing channel: {}", err.err);
1982
1983                                         $self.finish_close_channel(shutdown_res);
1984                                         if let Some(update) = update_option {
1985                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1986                                                         msg: update
1987                                                 });
1988                                         }
1989                                 } else {
1990                                         log_error!($self.logger, "Got non-closing error: {}", err.err);
1991                                 }
1992
1993                                 if let msgs::ErrorAction::IgnoreError = err.action {
1994                                 } else {
1995                                         msg_events.push(events::MessageSendEvent::HandleError {
1996                                                 node_id: $counterparty_node_id,
1997                                                 action: err.action.clone()
1998                                         });
1999                                 }
2000
2001                                 if !msg_events.is_empty() {
2002                                         let per_peer_state = $self.per_peer_state.read().unwrap();
2003                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
2004                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2005                                                 peer_state.pending_msg_events.append(&mut msg_events);
2006                                         }
2007                                 }
2008
2009                                 // Return error in case higher-API need one
2010                                 Err(err)
2011                         },
2012                 }
2013         } };
2014 }
2015
2016 macro_rules! update_maps_on_chan_removal {
2017         ($self: expr, $channel_context: expr) => {{
2018                 if let Some(outpoint) = $channel_context.get_funding_txo() {
2019                         $self.outpoint_to_peer.lock().unwrap().remove(&outpoint);
2020                 }
2021                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2022                 if let Some(short_id) = $channel_context.get_short_channel_id() {
2023                         short_to_chan_info.remove(&short_id);
2024                 } else {
2025                         // If the channel was never confirmed on-chain prior to its closure, remove the
2026                         // outbound SCID alias we used for it from the collision-prevention set. While we
2027                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
2028                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
2029                         // opening a million channels with us which are closed before we ever reach the funding
2030                         // stage.
2031                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
2032                         debug_assert!(alias_removed);
2033                 }
2034                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
2035         }}
2036 }
2037
2038 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
2039 macro_rules! convert_chan_phase_err {
2040         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
2041                 match $err {
2042                         ChannelError::Warn(msg) => {
2043                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
2044                         },
2045                         ChannelError::Ignore(msg) => {
2046                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
2047                         },
2048                         ChannelError::Close(msg) => {
2049                                 let logger = WithChannelContext::from(&$self.logger, &$channel.context);
2050                                 log_error!(logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
2051                                 update_maps_on_chan_removal!($self, $channel.context);
2052                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
2053                                 let shutdown_res = $channel.context.force_shutdown(true, reason);
2054                                 let err =
2055                                         MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $channel_update);
2056                                 (true, err)
2057                         },
2058                 }
2059         };
2060         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
2061                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
2062         };
2063         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
2064                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
2065         };
2066         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
2067                 match $channel_phase {
2068                         ChannelPhase::Funded(channel) => {
2069                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
2070                         },
2071                         ChannelPhase::UnfundedOutboundV1(channel) => {
2072                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2073                         },
2074                         ChannelPhase::UnfundedInboundV1(channel) => {
2075                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2076                         },
2077                 }
2078         };
2079 }
2080
2081 macro_rules! break_chan_phase_entry {
2082         ($self: ident, $res: expr, $entry: expr) => {
2083                 match $res {
2084                         Ok(res) => res,
2085                         Err(e) => {
2086                                 let key = *$entry.key();
2087                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2088                                 if drop {
2089                                         $entry.remove_entry();
2090                                 }
2091                                 break Err(res);
2092                         }
2093                 }
2094         }
2095 }
2096
2097 macro_rules! try_chan_phase_entry {
2098         ($self: ident, $res: expr, $entry: expr) => {
2099                 match $res {
2100                         Ok(res) => res,
2101                         Err(e) => {
2102                                 let key = *$entry.key();
2103                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2104                                 if drop {
2105                                         $entry.remove_entry();
2106                                 }
2107                                 return Err(res);
2108                         }
2109                 }
2110         }
2111 }
2112
2113 macro_rules! remove_channel_phase {
2114         ($self: expr, $entry: expr) => {
2115                 {
2116                         let channel = $entry.remove_entry().1;
2117                         update_maps_on_chan_removal!($self, &channel.context());
2118                         channel
2119                 }
2120         }
2121 }
2122
2123 macro_rules! send_channel_ready {
2124         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2125                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2126                         node_id: $channel.context.get_counterparty_node_id(),
2127                         msg: $channel_ready_msg,
2128                 });
2129                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2130                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2131                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2132                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2133                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2134                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2135                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2136                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2137                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2138                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2139                 }
2140         }}
2141 }
2142
2143 macro_rules! emit_channel_pending_event {
2144         ($locked_events: expr, $channel: expr) => {
2145                 if $channel.context.should_emit_channel_pending_event() {
2146                         $locked_events.push_back((events::Event::ChannelPending {
2147                                 channel_id: $channel.context.channel_id(),
2148                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2149                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2150                                 user_channel_id: $channel.context.get_user_id(),
2151                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2152                         }, None));
2153                         $channel.context.set_channel_pending_event_emitted();
2154                 }
2155         }
2156 }
2157
2158 macro_rules! emit_channel_ready_event {
2159         ($locked_events: expr, $channel: expr) => {
2160                 if $channel.context.should_emit_channel_ready_event() {
2161                         debug_assert!($channel.context.channel_pending_event_emitted());
2162                         $locked_events.push_back((events::Event::ChannelReady {
2163                                 channel_id: $channel.context.channel_id(),
2164                                 user_channel_id: $channel.context.get_user_id(),
2165                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2166                                 channel_type: $channel.context.get_channel_type().clone(),
2167                         }, None));
2168                         $channel.context.set_channel_ready_event_emitted();
2169                 }
2170         }
2171 }
2172
2173 macro_rules! handle_monitor_update_completion {
2174         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2175                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2176                 let mut updates = $chan.monitor_updating_restored(&&logger,
2177                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2178                         $self.best_block.read().unwrap().height());
2179                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2180                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2181                         // We only send a channel_update in the case where we are just now sending a
2182                         // channel_ready and the channel is in a usable state. We may re-send a
2183                         // channel_update later through the announcement_signatures process for public
2184                         // channels, but there's no reason not to just inform our counterparty of our fees
2185                         // now.
2186                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2187                                 Some(events::MessageSendEvent::SendChannelUpdate {
2188                                         node_id: counterparty_node_id,
2189                                         msg,
2190                                 })
2191                         } else { None }
2192                 } else { None };
2193
2194                 let update_actions = $peer_state.monitor_update_blocked_actions
2195                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2196
2197                 let htlc_forwards = $self.handle_channel_resumption(
2198                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2199                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2200                         updates.funding_broadcastable, updates.channel_ready,
2201                         updates.announcement_sigs);
2202                 if let Some(upd) = channel_update {
2203                         $peer_state.pending_msg_events.push(upd);
2204                 }
2205
2206                 let channel_id = $chan.context.channel_id();
2207                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2208                 core::mem::drop($peer_state_lock);
2209                 core::mem::drop($per_peer_state_lock);
2210
2211                 // If the channel belongs to a batch funding transaction, the progress of the batch
2212                 // should be updated as we have received funding_signed and persisted the monitor.
2213                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2214                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2215                         let mut batch_completed = false;
2216                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2217                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2218                                         *chan_id == channel_id &&
2219                                         *pubkey == counterparty_node_id
2220                                 ));
2221                                 if let Some(channel_state) = channel_state {
2222                                         channel_state.2 = true;
2223                                 } else {
2224                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2225                                 }
2226                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2227                         } else {
2228                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2229                         }
2230
2231                         // When all channels in a batched funding transaction have become ready, it is not necessary
2232                         // to track the progress of the batch anymore and the state of the channels can be updated.
2233                         if batch_completed {
2234                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2235                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2236                                 let mut batch_funding_tx = None;
2237                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2238                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2239                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2240                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2241                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2242                                                         chan.set_batch_ready();
2243                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2244                                                         emit_channel_pending_event!(pending_events, chan);
2245                                                 }
2246                                         }
2247                                 }
2248                                 if let Some(tx) = batch_funding_tx {
2249                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2250                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2251                                 }
2252                         }
2253                 }
2254
2255                 $self.handle_monitor_update_completion_actions(update_actions);
2256
2257                 if let Some(forwards) = htlc_forwards {
2258                         $self.forward_htlcs(&mut [forwards][..]);
2259                 }
2260                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2261                 for failure in updates.failed_htlcs.drain(..) {
2262                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2263                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2264                 }
2265         } }
2266 }
2267
2268 macro_rules! handle_new_monitor_update {
2269         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2270                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2271                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2272                 match $update_res {
2273                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2274                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2275                                 log_error!(logger, "{}", err_str);
2276                                 panic!("{}", err_str);
2277                         },
2278                         ChannelMonitorUpdateStatus::InProgress => {
2279                                 log_debug!(logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2280                                         &$chan.context.channel_id());
2281                                 false
2282                         },
2283                         ChannelMonitorUpdateStatus::Completed => {
2284                                 $completed;
2285                                 true
2286                         },
2287                 }
2288         } };
2289         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2290                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2291                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2292         };
2293         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2294                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2295                         .or_insert_with(Vec::new);
2296                 // During startup, we push monitor updates as background events through to here in
2297                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2298                 // filter for uniqueness here.
2299                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2300                         .unwrap_or_else(|| {
2301                                 in_flight_updates.push($update);
2302                                 in_flight_updates.len() - 1
2303                         });
2304                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2305                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2306                         {
2307                                 let _ = in_flight_updates.remove(idx);
2308                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2309                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2310                                 }
2311                         })
2312         } };
2313 }
2314
2315 macro_rules! process_events_body {
2316         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2317                 let mut processed_all_events = false;
2318                 while !processed_all_events {
2319                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2320                                 return;
2321                         }
2322
2323                         let mut result;
2324
2325                         {
2326                                 // We'll acquire our total consistency lock so that we can be sure no other
2327                                 // persists happen while processing monitor events.
2328                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2329
2330                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2331                                 // ensure any startup-generated background events are handled first.
2332                                 result = $self.process_background_events();
2333
2334                                 // TODO: This behavior should be documented. It's unintuitive that we query
2335                                 // ChannelMonitors when clearing other events.
2336                                 if $self.process_pending_monitor_events() {
2337                                         result = NotifyOption::DoPersist;
2338                                 }
2339                         }
2340
2341                         let pending_events = $self.pending_events.lock().unwrap().clone();
2342                         let num_events = pending_events.len();
2343                         if !pending_events.is_empty() {
2344                                 result = NotifyOption::DoPersist;
2345                         }
2346
2347                         let mut post_event_actions = Vec::new();
2348
2349                         for (event, action_opt) in pending_events {
2350                                 $event_to_handle = event;
2351                                 $handle_event;
2352                                 if let Some(action) = action_opt {
2353                                         post_event_actions.push(action);
2354                                 }
2355                         }
2356
2357                         {
2358                                 let mut pending_events = $self.pending_events.lock().unwrap();
2359                                 pending_events.drain(..num_events);
2360                                 processed_all_events = pending_events.is_empty();
2361                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2362                                 // updated here with the `pending_events` lock acquired.
2363                                 $self.pending_events_processor.store(false, Ordering::Release);
2364                         }
2365
2366                         if !post_event_actions.is_empty() {
2367                                 $self.handle_post_event_actions(post_event_actions);
2368                                 // If we had some actions, go around again as we may have more events now
2369                                 processed_all_events = false;
2370                         }
2371
2372                         match result {
2373                                 NotifyOption::DoPersist => {
2374                                         $self.needs_persist_flag.store(true, Ordering::Release);
2375                                         $self.event_persist_notifier.notify();
2376                                 },
2377                                 NotifyOption::SkipPersistHandleEvents =>
2378                                         $self.event_persist_notifier.notify(),
2379                                 NotifyOption::SkipPersistNoEvents => {},
2380                         }
2381                 }
2382         }
2383 }
2384
2385 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>
2386 where
2387         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
2388         T::Target: BroadcasterInterface,
2389         ES::Target: EntropySource,
2390         NS::Target: NodeSigner,
2391         SP::Target: SignerProvider,
2392         F::Target: FeeEstimator,
2393         R::Target: Router,
2394         L::Target: Logger,
2395 {
2396         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2397         ///
2398         /// The current time or latest block header time can be provided as the `current_timestamp`.
2399         ///
2400         /// This is the main "logic hub" for all channel-related actions, and implements
2401         /// [`ChannelMessageHandler`].
2402         ///
2403         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2404         ///
2405         /// Users need to notify the new `ChannelManager` when a new block is connected or
2406         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2407         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2408         /// more details.
2409         ///
2410         /// [`block_connected`]: chain::Listen::block_connected
2411         /// [`block_disconnected`]: chain::Listen::block_disconnected
2412         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2413         pub fn new(
2414                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2415                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2416                 current_timestamp: u32,
2417         ) -> Self {
2418                 let mut secp_ctx = Secp256k1::new();
2419                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2420                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2421                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2422                 ChannelManager {
2423                         default_configuration: config.clone(),
2424                         chain_hash: ChainHash::using_genesis_block(params.network),
2425                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2426                         chain_monitor,
2427                         tx_broadcaster,
2428                         router,
2429
2430                         best_block: RwLock::new(params.best_block),
2431
2432                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2433                         pending_inbound_payments: Mutex::new(HashMap::new()),
2434                         pending_outbound_payments: OutboundPayments::new(),
2435                         forward_htlcs: Mutex::new(HashMap::new()),
2436                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2437                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2438                         outpoint_to_peer: Mutex::new(HashMap::new()),
2439                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2440
2441                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2442                         secp_ctx,
2443
2444                         inbound_payment_key: expanded_inbound_key,
2445                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2446
2447                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2448
2449                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2450
2451                         per_peer_state: FairRwLock::new(HashMap::new()),
2452
2453                         pending_events: Mutex::new(VecDeque::new()),
2454                         pending_events_processor: AtomicBool::new(false),
2455                         pending_background_events: Mutex::new(Vec::new()),
2456                         total_consistency_lock: RwLock::new(()),
2457                         background_events_processed_since_startup: AtomicBool::new(false),
2458                         event_persist_notifier: Notifier::new(),
2459                         needs_persist_flag: AtomicBool::new(false),
2460                         funding_batch_states: Mutex::new(BTreeMap::new()),
2461
2462                         pending_offers_messages: Mutex::new(Vec::new()),
2463
2464                         entropy_source,
2465                         node_signer,
2466                         signer_provider,
2467
2468                         logger,
2469                 }
2470         }
2471
2472         /// Gets the current configuration applied to all new channels.
2473         pub fn get_current_default_configuration(&self) -> &UserConfig {
2474                 &self.default_configuration
2475         }
2476
2477         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2478                 let height = self.best_block.read().unwrap().height();
2479                 let mut outbound_scid_alias = 0;
2480                 let mut i = 0;
2481                 loop {
2482                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2483                                 outbound_scid_alias += 1;
2484                         } else {
2485                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2486                         }
2487                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2488                                 break;
2489                         }
2490                         i += 1;
2491                         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"); }
2492                 }
2493                 outbound_scid_alias
2494         }
2495
2496         /// Creates a new outbound channel to the given remote node and with the given value.
2497         ///
2498         /// `user_channel_id` will be provided back as in
2499         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2500         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2501         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2502         /// is simply copied to events and otherwise ignored.
2503         ///
2504         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2505         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2506         ///
2507         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2508         /// generate a shutdown scriptpubkey or destination script set by
2509         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2510         ///
2511         /// Note that we do not check if you are currently connected to the given peer. If no
2512         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2513         /// the channel eventually being silently forgotten (dropped on reload).
2514         ///
2515         /// If `temporary_channel_id` is specified, it will be used as the temporary channel ID of the
2516         /// channel. Otherwise, a random one will be generated for you.
2517         ///
2518         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2519         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2520         /// [`ChannelDetails::channel_id`] until after
2521         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2522         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2523         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2524         ///
2525         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2526         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2527         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2528         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> {
2529                 if channel_value_satoshis < 1000 {
2530                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2531                 }
2532
2533                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2534                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2535                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2536
2537                 let per_peer_state = self.per_peer_state.read().unwrap();
2538
2539                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2540                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2541
2542                 let mut peer_state = peer_state_mutex.lock().unwrap();
2543
2544                 if let Some(temporary_channel_id) = temporary_channel_id {
2545                         if peer_state.channel_by_id.contains_key(&temporary_channel_id) {
2546                                 return Err(APIError::APIMisuseError{ err: format!("Channel with temporary channel ID {} already exists!", temporary_channel_id)});
2547                         }
2548                 }
2549
2550                 let channel = {
2551                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2552                         let their_features = &peer_state.latest_features;
2553                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2554                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2555                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2556                                 self.best_block.read().unwrap().height(), outbound_scid_alias, temporary_channel_id)
2557                         {
2558                                 Ok(res) => res,
2559                                 Err(e) => {
2560                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2561                                         return Err(e);
2562                                 },
2563                         }
2564                 };
2565                 let res = channel.get_open_channel(self.chain_hash);
2566
2567                 let temporary_channel_id = channel.context.channel_id();
2568                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2569                         hash_map::Entry::Occupied(_) => {
2570                                 if cfg!(fuzzing) {
2571                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2572                                 } else {
2573                                         panic!("RNG is bad???");
2574                                 }
2575                         },
2576                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2577                 }
2578
2579                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2580                         node_id: their_network_key,
2581                         msg: res,
2582                 });
2583                 Ok(temporary_channel_id)
2584         }
2585
2586         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2587                 // Allocate our best estimate of the number of channels we have in the `res`
2588                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2589                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2590                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2591                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2592                 // the same channel.
2593                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2594                 {
2595                         let best_block_height = self.best_block.read().unwrap().height();
2596                         let per_peer_state = self.per_peer_state.read().unwrap();
2597                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2598                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2599                                 let peer_state = &mut *peer_state_lock;
2600                                 res.extend(peer_state.channel_by_id.iter()
2601                                         .filter_map(|(chan_id, phase)| match phase {
2602                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2603                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2604                                                 _ => None,
2605                                         })
2606                                         .filter(f)
2607                                         .map(|(_channel_id, channel)| {
2608                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2609                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2610                                         })
2611                                 );
2612                         }
2613                 }
2614                 res
2615         }
2616
2617         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2618         /// more information.
2619         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2620                 // Allocate our best estimate of the number of channels we have in the `res`
2621                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2622                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2623                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2624                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2625                 // the same channel.
2626                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2627                 {
2628                         let best_block_height = self.best_block.read().unwrap().height();
2629                         let per_peer_state = self.per_peer_state.read().unwrap();
2630                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2631                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2632                                 let peer_state = &mut *peer_state_lock;
2633                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2634                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2635                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2636                                         res.push(details);
2637                                 }
2638                         }
2639                 }
2640                 res
2641         }
2642
2643         /// Gets the list of usable channels, in random order. Useful as an argument to
2644         /// [`Router::find_route`] to ensure non-announced channels are used.
2645         ///
2646         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2647         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2648         /// are.
2649         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2650                 // Note we use is_live here instead of usable which leads to somewhat confused
2651                 // internal/external nomenclature, but that's ok cause that's probably what the user
2652                 // really wanted anyway.
2653                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2654         }
2655
2656         /// Gets the list of channels we have with a given counterparty, in random order.
2657         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2658                 let best_block_height = self.best_block.read().unwrap().height();
2659                 let per_peer_state = self.per_peer_state.read().unwrap();
2660
2661                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2662                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2663                         let peer_state = &mut *peer_state_lock;
2664                         let features = &peer_state.latest_features;
2665                         let context_to_details = |context| {
2666                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2667                         };
2668                         return peer_state.channel_by_id
2669                                 .iter()
2670                                 .map(|(_, phase)| phase.context())
2671                                 .map(context_to_details)
2672                                 .collect();
2673                 }
2674                 vec![]
2675         }
2676
2677         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2678         /// successful path, or have unresolved HTLCs.
2679         ///
2680         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2681         /// result of a crash. If such a payment exists, is not listed here, and an
2682         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2683         ///
2684         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2685         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2686                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2687                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2688                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2689                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2690                                 },
2691                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2692                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2693                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2694                                 },
2695                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2696                                         Some(RecentPaymentDetails::Pending {
2697                                                 payment_id: *payment_id,
2698                                                 payment_hash: *payment_hash,
2699                                                 total_msat: *total_msat,
2700                                         })
2701                                 },
2702                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2703                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2704                                 },
2705                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2706                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2707                                 },
2708                                 PendingOutboundPayment::Legacy { .. } => None
2709                         })
2710                         .collect()
2711         }
2712
2713         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> {
2714                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2715
2716                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
2717                 let mut shutdown_result = None;
2718
2719                 {
2720                         let per_peer_state = self.per_peer_state.read().unwrap();
2721
2722                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2723                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2724
2725                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2726                         let peer_state = &mut *peer_state_lock;
2727
2728                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2729                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2730                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2731                                                 let funding_txo_opt = chan.context.get_funding_txo();
2732                                                 let their_features = &peer_state.latest_features;
2733                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2734                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2735                                                 failed_htlcs = htlcs;
2736
2737                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2738                                                 // here as we don't need the monitor update to complete until we send a
2739                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2740                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2741                                                         node_id: *counterparty_node_id,
2742                                                         msg: shutdown_msg,
2743                                                 });
2744
2745                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2746                                                         "We can't both complete shutdown and generate a monitor update");
2747
2748                                                 // Update the monitor with the shutdown script if necessary.
2749                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2750                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2751                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2752                                                 }
2753                                         } else {
2754                                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2755                                                 shutdown_result = Some(chan_phase.context_mut().force_shutdown(false, ClosureReason::HolderForceClosed));
2756                                         }
2757                                 },
2758                                 hash_map::Entry::Vacant(_) => {
2759                                         return Err(APIError::ChannelUnavailable {
2760                                                 err: format!(
2761                                                         "Channel with id {} not found for the passed counterparty node_id {}",
2762                                                         channel_id, counterparty_node_id,
2763                                                 )
2764                                         });
2765                                 },
2766                         }
2767                 }
2768
2769                 for htlc_source in failed_htlcs.drain(..) {
2770                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2771                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2772                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2773                 }
2774
2775                 if let Some(shutdown_result) = shutdown_result {
2776                         self.finish_close_channel(shutdown_result);
2777                 }
2778
2779                 Ok(())
2780         }
2781
2782         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2783         /// will be accepted on the given channel, and after additional timeout/the closing of all
2784         /// pending HTLCs, the channel will be closed on chain.
2785         ///
2786         ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2787         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2788         ///    fee estimate.
2789         ///  * If our counterparty is the channel initiator, we will require a channel closing
2790         ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2791         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2792         ///    counterparty to pay as much fee as they'd like, however.
2793         ///
2794         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2795         ///
2796         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2797         /// generate a shutdown scriptpubkey or destination script set by
2798         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2799         /// channel.
2800         ///
2801         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2802         /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2803         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2804         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2805         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2806                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2807         }
2808
2809         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2810         /// will be accepted on the given channel, and after additional timeout/the closing of all
2811         /// pending HTLCs, the channel will be closed on chain.
2812         ///
2813         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2814         /// the channel being closed or not:
2815         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2816         ///    transaction. The upper-bound is set by
2817         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2818         ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2819         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2820         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2821         ///    will appear on a force-closure transaction, whichever is lower).
2822         ///
2823         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2824         /// Will fail if a shutdown script has already been set for this channel by
2825         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2826         /// also be compatible with our and the counterparty's features.
2827         ///
2828         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2829         ///
2830         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2831         /// generate a shutdown scriptpubkey or destination script set by
2832         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2833         /// channel.
2834         ///
2835         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2836         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2837         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2838         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> {
2839                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2840         }
2841
2842         fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) {
2843                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2844                 #[cfg(debug_assertions)]
2845                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2846                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2847                 }
2848
2849                 let logger = WithContext::from(
2850                         &self.logger, Some(shutdown_res.counterparty_node_id), Some(shutdown_res.channel_id),
2851                 );
2852
2853                 log_debug!(logger, "Finishing closure of channel due to {} with {} HTLCs to fail",
2854                         shutdown_res.closure_reason, shutdown_res.dropped_outbound_htlcs.len());
2855                 for htlc_source in shutdown_res.dropped_outbound_htlcs.drain(..) {
2856                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2857                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2858                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2859                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2860                 }
2861                 if let Some((_, funding_txo, monitor_update)) = shutdown_res.monitor_update {
2862                         // There isn't anything we can do if we get an update failure - we're already
2863                         // force-closing. The monitor update on the required in-memory copy should broadcast
2864                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2865                         // ignore the result here.
2866                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2867                 }
2868                 let mut shutdown_results = Vec::new();
2869                 if let Some(txid) = shutdown_res.unbroadcasted_batch_funding_txid {
2870                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2871                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2872                         let per_peer_state = self.per_peer_state.read().unwrap();
2873                         let mut has_uncompleted_channel = None;
2874                         for (channel_id, counterparty_node_id, state) in affected_channels {
2875                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2876                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2877                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2878                                                 update_maps_on_chan_removal!(self, &chan.context());
2879                                                 shutdown_results.push(chan.context_mut().force_shutdown(false, ClosureReason::FundingBatchClosure));
2880                                         }
2881                                 }
2882                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2883                         }
2884                         debug_assert!(
2885                                 has_uncompleted_channel.unwrap_or(true),
2886                                 "Closing a batch where all channels have completed initial monitor update",
2887                         );
2888                 }
2889
2890                 {
2891                         let mut pending_events = self.pending_events.lock().unwrap();
2892                         pending_events.push_back((events::Event::ChannelClosed {
2893                                 channel_id: shutdown_res.channel_id,
2894                                 user_channel_id: shutdown_res.user_channel_id,
2895                                 reason: shutdown_res.closure_reason,
2896                                 counterparty_node_id: Some(shutdown_res.counterparty_node_id),
2897                                 channel_capacity_sats: Some(shutdown_res.channel_capacity_satoshis),
2898                                 channel_funding_txo: shutdown_res.channel_funding_txo,
2899                         }, None));
2900
2901                         if let Some(transaction) = shutdown_res.unbroadcasted_funding_tx {
2902                                 pending_events.push_back((events::Event::DiscardFunding {
2903                                         channel_id: shutdown_res.channel_id, transaction
2904                                 }, None));
2905                         }
2906                 }
2907                 for shutdown_result in shutdown_results.drain(..) {
2908                         self.finish_close_channel(shutdown_result);
2909                 }
2910         }
2911
2912         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2913         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2914         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2915         -> Result<PublicKey, APIError> {
2916                 let per_peer_state = self.per_peer_state.read().unwrap();
2917                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2918                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2919                 let (update_opt, counterparty_node_id) = {
2920                         let mut peer_state = peer_state_mutex.lock().unwrap();
2921                         let closure_reason = if let Some(peer_msg) = peer_msg {
2922                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2923                         } else {
2924                                 ClosureReason::HolderForceClosed
2925                         };
2926                         let logger = WithContext::from(&self.logger, Some(*peer_node_id), Some(*channel_id));
2927                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2928                                 log_error!(logger, "Force-closing channel {}", channel_id);
2929                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2930                                 mem::drop(peer_state);
2931                                 mem::drop(per_peer_state);
2932                                 match chan_phase {
2933                                         ChannelPhase::Funded(mut chan) => {
2934                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast, closure_reason));
2935                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2936                                         },
2937                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2938                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false, closure_reason));
2939                                                 // Unfunded channel has no update
2940                                                 (None, chan_phase.context().get_counterparty_node_id())
2941                                         },
2942                                 }
2943                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2944                                 log_error!(logger, "Force-closing channel {}", &channel_id);
2945                                 // N.B. that we don't send any channel close event here: we
2946                                 // don't have a user_channel_id, and we never sent any opening
2947                                 // events anyway.
2948                                 (None, *peer_node_id)
2949                         } else {
2950                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2951                         }
2952                 };
2953                 if let Some(update) = update_opt {
2954                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2955                         // not try to broadcast it via whatever peer we have.
2956                         let per_peer_state = self.per_peer_state.read().unwrap();
2957                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2958                                 .ok_or(per_peer_state.values().next());
2959                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2960                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2961                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2962                                         msg: update
2963                                 });
2964                         }
2965                 }
2966
2967                 Ok(counterparty_node_id)
2968         }
2969
2970         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2971                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2972                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2973                         Ok(counterparty_node_id) => {
2974                                 let per_peer_state = self.per_peer_state.read().unwrap();
2975                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2976                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2977                                         peer_state.pending_msg_events.push(
2978                                                 events::MessageSendEvent::HandleError {
2979                                                         node_id: counterparty_node_id,
2980                                                         action: msgs::ErrorAction::DisconnectPeer {
2981                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2982                                                         },
2983                                                 }
2984                                         );
2985                                 }
2986                                 Ok(())
2987                         },
2988                         Err(e) => Err(e)
2989                 }
2990         }
2991
2992         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2993         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2994         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2995         /// channel.
2996         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2997         -> Result<(), APIError> {
2998                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2999         }
3000
3001         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
3002         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
3003         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
3004         ///
3005         /// You can always get the latest local transaction(s) to broadcast from
3006         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
3007         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
3008         -> Result<(), APIError> {
3009                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
3010         }
3011
3012         /// Force close all channels, immediately broadcasting the latest local commitment transaction
3013         /// for each to the chain and rejecting new HTLCs on each.
3014         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
3015                 for chan in self.list_channels() {
3016                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
3017                 }
3018         }
3019
3020         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
3021         /// local transaction(s).
3022         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
3023                 for chan in self.list_channels() {
3024                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
3025                 }
3026         }
3027
3028         fn decode_update_add_htlc_onion(
3029                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey,
3030         ) -> Result<
3031                 (onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg
3032         > {
3033                 let (next_hop, shared_secret, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(
3034                         msg, &self.node_signer, &self.logger, &self.secp_ctx
3035                 )?;
3036
3037                 let is_intro_node_forward = match next_hop {
3038                         onion_utils::Hop::Forward {
3039                                 next_hop_data: msgs::InboundOnionPayload::BlindedForward {
3040                                         intro_node_blinding_point: Some(_), ..
3041                                 }, ..
3042                         } => true,
3043                         _ => false,
3044                 };
3045
3046                 macro_rules! return_err {
3047                         ($msg: expr, $err_code: expr, $data: expr) => {
3048                                 {
3049                                         log_info!(
3050                                                 WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id)),
3051                                                 "Failed to accept/forward incoming HTLC: {}", $msg
3052                                         );
3053                                         // If `msg.blinding_point` is set, we must always fail with malformed.
3054                                         if msg.blinding_point.is_some() {
3055                                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3056                                                         channel_id: msg.channel_id,
3057                                                         htlc_id: msg.htlc_id,
3058                                                         sha256_of_onion: [0; 32],
3059                                                         failure_code: INVALID_ONION_BLINDING,
3060                                                 }));
3061                                         }
3062
3063                                         let (err_code, err_data) = if is_intro_node_forward {
3064                                                 (INVALID_ONION_BLINDING, &[0; 32][..])
3065                                         } else { ($err_code, $data) };
3066                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3067                                                 channel_id: msg.channel_id,
3068                                                 htlc_id: msg.htlc_id,
3069                                                 reason: HTLCFailReason::reason(err_code, err_data.to_vec())
3070                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3071                                         }));
3072                                 }
3073                         }
3074                 }
3075
3076                 let NextPacketDetails {
3077                         next_packet_pubkey, outgoing_amt_msat, outgoing_scid, outgoing_cltv_value
3078                 } = match next_packet_details_opt {
3079                         Some(next_packet_details) => next_packet_details,
3080                         // it is a receive, so no need for outbound checks
3081                         None => return Ok((next_hop, shared_secret, None)),
3082                 };
3083
3084                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3085                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3086                 if let Some((err, mut code, chan_update)) = loop {
3087                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3088                         let forwarding_chan_info_opt = match id_option {
3089                                 None => { // unknown_next_peer
3090                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3091                                         // phantom or an intercept.
3092                                         if (self.default_configuration.accept_intercept_htlcs &&
3093                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3094                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3095                                         {
3096                                                 None
3097                                         } else {
3098                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3099                                         }
3100                                 },
3101                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3102                         };
3103                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3104                                 let per_peer_state = self.per_peer_state.read().unwrap();
3105                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3106                                 if peer_state_mutex_opt.is_none() {
3107                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3108                                 }
3109                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3110                                 let peer_state = &mut *peer_state_lock;
3111                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3112                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3113                                 ).flatten() {
3114                                         None => {
3115                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3116                                                 // have no consistency guarantees.
3117                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3118                                         },
3119                                         Some(chan) => chan
3120                                 };
3121                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3122                                         // Note that the behavior here should be identical to the above block - we
3123                                         // should NOT reveal the existence or non-existence of a private channel if
3124                                         // we don't allow forwards outbound over them.
3125                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3126                                 }
3127                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3128                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3129                                         // "refuse to forward unless the SCID alias was used", so we pretend
3130                                         // we don't have the channel here.
3131                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3132                                 }
3133                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3134
3135                                 // Note that we could technically not return an error yet here and just hope
3136                                 // that the connection is reestablished or monitor updated by the time we get
3137                                 // around to doing the actual forward, but better to fail early if we can and
3138                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3139                                 // on a small/per-node/per-channel scale.
3140                                 if !chan.context.is_live() { // channel_disabled
3141                                         // If the channel_update we're going to return is disabled (i.e. the
3142                                         // peer has been disabled for some time), return `channel_disabled`,
3143                                         // otherwise return `temporary_channel_failure`.
3144                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3145                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3146                                         } else {
3147                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3148                                         }
3149                                 }
3150                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3151                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3152                                 }
3153                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3154                                         break Some((err, code, chan_update_opt));
3155                                 }
3156                                 chan_update_opt
3157                         } else {
3158                                 None
3159                         };
3160
3161                         let cur_height = self.best_block.read().unwrap().height() + 1;
3162
3163                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
3164                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
3165                         ) {
3166                                 if code & 0x1000 != 0 && chan_update_opt.is_none() {
3167                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3168                                         // forwarding over a real channel we can't generate a channel_update
3169                                         // for it. Instead we just return a generic temporary_node_failure.
3170                                         break Some((err_msg, 0x2000 | 2, None))
3171                                 }
3172                                 let chan_update_opt = if code & 0x1000 != 0 { chan_update_opt } else { None };
3173                                 break Some((err_msg, code, chan_update_opt));
3174                         }
3175
3176                         break None;
3177                 }
3178                 {
3179                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3180                         if let Some(chan_update) = chan_update {
3181                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3182                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3183                                 }
3184                                 else if code == 0x1000 | 13 {
3185                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3186                                 }
3187                                 else if code == 0x1000 | 20 {
3188                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3189                                         0u16.write(&mut res).expect("Writes cannot fail");
3190                                 }
3191                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3192                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3193                                 chan_update.write(&mut res).expect("Writes cannot fail");
3194                         } else if code & 0x1000 == 0x1000 {
3195                                 // If we're trying to return an error that requires a `channel_update` but
3196                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3197                                 // generate an update), just use the generic "temporary_node_failure"
3198                                 // instead.
3199                                 code = 0x2000 | 2;
3200                         }
3201                         return_err!(err, code, &res.0[..]);
3202                 }
3203                 Ok((next_hop, shared_secret, Some(next_packet_pubkey)))
3204         }
3205
3206         fn construct_pending_htlc_status<'a>(
3207                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, shared_secret: [u8; 32],
3208                 decoded_hop: onion_utils::Hop, allow_underpay: bool,
3209                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>,
3210         ) -> PendingHTLCStatus {
3211                 macro_rules! return_err {
3212                         ($msg: expr, $err_code: expr, $data: expr) => {
3213                                 {
3214                                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
3215                                         log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3216                                         if msg.blinding_point.is_some() {
3217                                                 return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
3218                                                         msgs::UpdateFailMalformedHTLC {
3219                                                                 channel_id: msg.channel_id,
3220                                                                 htlc_id: msg.htlc_id,
3221                                                                 sha256_of_onion: [0; 32],
3222                                                                 failure_code: INVALID_ONION_BLINDING,
3223                                                         }
3224                                                 ))
3225                                         }
3226                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3227                                                 channel_id: msg.channel_id,
3228                                                 htlc_id: msg.htlc_id,
3229                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3230                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3231                                         }));
3232                                 }
3233                         }
3234                 }
3235                 match decoded_hop {
3236                         onion_utils::Hop::Receive(next_hop_data) => {
3237                                 // OUR PAYMENT!
3238                                 let current_height: u32 = self.best_block.read().unwrap().height();
3239                                 match create_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3240                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat,
3241                                         current_height, self.default_configuration.accept_mpp_keysend)
3242                                 {
3243                                         Ok(info) => {
3244                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3245                                                 // message, however that would leak that we are the recipient of this payment, so
3246                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3247                                                 // delay) once they've send us a commitment_signed!
3248                                                 PendingHTLCStatus::Forward(info)
3249                                         },
3250                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3251                                 }
3252                         },
3253                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3254                                 match create_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3255                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3256                                         Ok(info) => PendingHTLCStatus::Forward(info),
3257                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3258                                 }
3259                         }
3260                 }
3261         }
3262
3263         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3264         /// public, and thus should be called whenever the result is going to be passed out in a
3265         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3266         ///
3267         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3268         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3269         /// storage and the `peer_state` lock has been dropped.
3270         ///
3271         /// [`channel_update`]: msgs::ChannelUpdate
3272         /// [`internal_closing_signed`]: Self::internal_closing_signed
3273         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3274                 if !chan.context.should_announce() {
3275                         return Err(LightningError {
3276                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3277                                 action: msgs::ErrorAction::IgnoreError
3278                         });
3279                 }
3280                 if chan.context.get_short_channel_id().is_none() {
3281                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3282                 }
3283                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3284                 log_trace!(logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3285                 self.get_channel_update_for_unicast(chan)
3286         }
3287
3288         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3289         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3290         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3291         /// provided evidence that they know about the existence of the channel.
3292         ///
3293         /// Note that through [`internal_closing_signed`], this function is called without the
3294         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3295         /// removed from the storage and the `peer_state` lock has been dropped.
3296         ///
3297         /// [`channel_update`]: msgs::ChannelUpdate
3298         /// [`internal_closing_signed`]: Self::internal_closing_signed
3299         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3300                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3301                 log_trace!(logger, "Attempting to generate channel update for channel {}", chan.context.channel_id());
3302                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3303                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3304                         Some(id) => id,
3305                 };
3306
3307                 self.get_channel_update_for_onion(short_channel_id, chan)
3308         }
3309
3310         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3311                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3312                 log_trace!(logger, "Generating channel update for channel {}", chan.context.channel_id());
3313                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3314
3315                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3316                         ChannelUpdateStatus::Enabled => true,
3317                         ChannelUpdateStatus::DisabledStaged(_) => true,
3318                         ChannelUpdateStatus::Disabled => false,
3319                         ChannelUpdateStatus::EnabledStaged(_) => false,
3320                 };
3321
3322                 let unsigned = msgs::UnsignedChannelUpdate {
3323                         chain_hash: self.chain_hash,
3324                         short_channel_id,
3325                         timestamp: chan.context.get_update_time_counter(),
3326                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3327                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3328                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3329                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3330                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3331                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3332                         excess_data: Vec::new(),
3333                 };
3334                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3335                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3336                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3337                 // channel.
3338                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3339
3340                 Ok(msgs::ChannelUpdate {
3341                         signature: sig,
3342                         contents: unsigned
3343                 })
3344         }
3345
3346         #[cfg(test)]
3347         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> {
3348                 let _lck = self.total_consistency_lock.read().unwrap();
3349                 self.send_payment_along_path(SendAlongPathArgs {
3350                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3351                         session_priv_bytes
3352                 })
3353         }
3354
3355         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3356                 let SendAlongPathArgs {
3357                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3358                         session_priv_bytes
3359                 } = args;
3360                 // The top-level caller should hold the total_consistency_lock read lock.
3361                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3362                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3363                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3364
3365                 let (onion_packet, htlc_msat, htlc_cltv) = onion_utils::create_payment_onion(
3366                         &self.secp_ctx, &path, &session_priv, total_value, recipient_onion, cur_height,
3367                         payment_hash, keysend_preimage, prng_seed
3368                 ).map_err(|e| {
3369                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3370                         log_error!(logger, "Failed to build an onion for path for payment hash {}", payment_hash);
3371                         e
3372                 })?;
3373
3374                 let err: Result<(), _> = loop {
3375                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3376                                 None => {
3377                                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3378                                         log_error!(logger, "Failed to find first-hop for payment hash {}", payment_hash);
3379                                         return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()})
3380                                 },
3381                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3382                         };
3383
3384                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(id));
3385                         log_trace!(logger,
3386                                 "Attempting to send payment with payment hash {} along path with next hop {}",
3387                                 payment_hash, path.hops.first().unwrap().short_channel_id);
3388
3389                         let per_peer_state = self.per_peer_state.read().unwrap();
3390                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3391                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3392                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3393                         let peer_state = &mut *peer_state_lock;
3394                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3395                                 match chan_phase_entry.get_mut() {
3396                                         ChannelPhase::Funded(chan) => {
3397                                                 if !chan.context.is_live() {
3398                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3399                                                 }
3400                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3401                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3402                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3403                                                         htlc_cltv, HTLCSource::OutboundRoute {
3404                                                                 path: path.clone(),
3405                                                                 session_priv: session_priv.clone(),
3406                                                                 first_hop_htlc_msat: htlc_msat,
3407                                                                 payment_id,
3408                                                         }, onion_packet, None, &self.fee_estimator, &&logger);
3409                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3410                                                         Some(monitor_update) => {
3411                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3412                                                                         false => {
3413                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3414                                                                                 // docs) that we will resend the commitment update once monitor
3415                                                                                 // updating completes. Therefore, we must return an error
3416                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3417                                                                                 // which we do in the send_payment check for
3418                                                                                 // MonitorUpdateInProgress, below.
3419                                                                                 return Err(APIError::MonitorUpdateInProgress);
3420                                                                         },
3421                                                                         true => {},
3422                                                                 }
3423                                                         },
3424                                                         None => {},
3425                                                 }
3426                                         },
3427                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3428                                 };
3429                         } else {
3430                                 // The channel was likely removed after we fetched the id from the
3431                                 // `short_to_chan_info` map, but before we successfully locked the
3432                                 // `channel_by_id` map.
3433                                 // This can occur as no consistency guarantees exists between the two maps.
3434                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3435                         }
3436                         return Ok(());
3437                 };
3438                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3439                         Ok(_) => unreachable!(),
3440                         Err(e) => {
3441                                 Err(APIError::ChannelUnavailable { err: e.err })
3442                         },
3443                 }
3444         }
3445
3446         /// Sends a payment along a given route.
3447         ///
3448         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3449         /// fields for more info.
3450         ///
3451         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3452         /// [`PeerManager::process_events`]).
3453         ///
3454         /// # Avoiding Duplicate Payments
3455         ///
3456         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3457         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3458         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3459         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3460         /// second payment with the same [`PaymentId`].
3461         ///
3462         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3463         /// tracking of payments, including state to indicate once a payment has completed. Because you
3464         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3465         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3466         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3467         ///
3468         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3469         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3470         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3471         /// [`ChannelManager::list_recent_payments`] for more information.
3472         ///
3473         /// # Possible Error States on [`PaymentSendFailure`]
3474         ///
3475         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3476         /// each entry matching the corresponding-index entry in the route paths, see
3477         /// [`PaymentSendFailure`] for more info.
3478         ///
3479         /// In general, a path may raise:
3480         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3481         ///    node public key) is specified.
3482         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3483         ///    closed, doesn't exist, or the peer is currently disconnected.
3484         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3485         ///    relevant updates.
3486         ///
3487         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3488         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3489         /// different route unless you intend to pay twice!
3490         ///
3491         /// [`RouteHop`]: crate::routing::router::RouteHop
3492         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3493         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3494         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3495         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3496         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3497         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3498                 let best_block_height = self.best_block.read().unwrap().height();
3499                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3500                 self.pending_outbound_payments
3501                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3502                                 &self.entropy_source, &self.node_signer, best_block_height,
3503                                 |args| self.send_payment_along_path(args))
3504         }
3505
3506         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3507         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3508         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3509                 let best_block_height = self.best_block.read().unwrap().height();
3510                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3511                 self.pending_outbound_payments
3512                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3513                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3514                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3515                                 &self.pending_events, |args| self.send_payment_along_path(args))
3516         }
3517
3518         #[cfg(test)]
3519         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> {
3520                 let best_block_height = self.best_block.read().unwrap().height();
3521                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3522                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3523                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3524                         best_block_height, |args| self.send_payment_along_path(args))
3525         }
3526
3527         #[cfg(test)]
3528         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> {
3529                 let best_block_height = self.best_block.read().unwrap().height();
3530                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3531         }
3532
3533         #[cfg(test)]
3534         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3535                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3536         }
3537
3538         pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3539                 let best_block_height = self.best_block.read().unwrap().height();
3540                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3541                 self.pending_outbound_payments
3542                         .send_payment_for_bolt12_invoice(
3543                                 invoice, payment_id, &self.router, self.list_usable_channels(),
3544                                 || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3545                                 best_block_height, &self.logger, &self.pending_events,
3546                                 |args| self.send_payment_along_path(args)
3547                         )
3548         }
3549
3550         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3551         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3552         /// retries are exhausted.
3553         ///
3554         /// # Event Generation
3555         ///
3556         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3557         /// as there are no remaining pending HTLCs for this payment.
3558         ///
3559         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3560         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3561         /// determine the ultimate status of a payment.
3562         ///
3563         /// # Requested Invoices
3564         ///
3565         /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
3566         /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
3567         /// and prevent any attempts at paying it once received. The other events may only be generated
3568         /// once the invoice has been received.
3569         ///
3570         /// # Restart Behavior
3571         ///
3572         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3573         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
3574         /// [`Event::InvoiceRequestFailed`].
3575         ///
3576         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3577         pub fn abandon_payment(&self, payment_id: PaymentId) {
3578                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3579                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3580         }
3581
3582         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3583         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3584         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3585         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3586         /// never reach the recipient.
3587         ///
3588         /// See [`send_payment`] documentation for more details on the return value of this function
3589         /// and idempotency guarantees provided by the [`PaymentId`] key.
3590         ///
3591         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3592         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3593         ///
3594         /// [`send_payment`]: Self::send_payment
3595         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3596                 let best_block_height = self.best_block.read().unwrap().height();
3597                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3598                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3599                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3600                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3601         }
3602
3603         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3604         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3605         ///
3606         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3607         /// payments.
3608         ///
3609         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3610         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> {
3611                 let best_block_height = self.best_block.read().unwrap().height();
3612                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3613                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3614                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3615                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3616                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3617         }
3618
3619         /// Send a payment that is probing the given route for liquidity. We calculate the
3620         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3621         /// us to easily discern them from real payments.
3622         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3623                 let best_block_height = self.best_block.read().unwrap().height();
3624                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3625                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3626                         &self.entropy_source, &self.node_signer, best_block_height,
3627                         |args| self.send_payment_along_path(args))
3628         }
3629
3630         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3631         /// payment probe.
3632         #[cfg(test)]
3633         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3634                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3635         }
3636
3637         /// Sends payment probes over all paths of a route that would be used to pay the given
3638         /// amount to the given `node_id`.
3639         ///
3640         /// See [`ChannelManager::send_preflight_probes`] for more information.
3641         pub fn send_spontaneous_preflight_probes(
3642                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3643                 liquidity_limit_multiplier: Option<u64>,
3644         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3645                 let payment_params =
3646                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3647
3648                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3649
3650                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3651         }
3652
3653         /// Sends payment probes over all paths of a route that would be used to pay a route found
3654         /// according to the given [`RouteParameters`].
3655         ///
3656         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3657         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3658         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3659         /// confirmation in a wallet UI.
3660         ///
3661         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3662         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3663         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3664         /// payment. To mitigate this issue, channels with available liquidity less than the required
3665         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3666         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3667         pub fn send_preflight_probes(
3668                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3669         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3670                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3671
3672                 let payer = self.get_our_node_id();
3673                 let usable_channels = self.list_usable_channels();
3674                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3675                 let inflight_htlcs = self.compute_inflight_htlcs();
3676
3677                 let route = self
3678                         .router
3679                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3680                         .map_err(|e| {
3681                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3682                                 ProbeSendFailure::RouteNotFound
3683                         })?;
3684
3685                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3686
3687                 let mut res = Vec::new();
3688
3689                 for mut path in route.paths {
3690                         // If the last hop is probably an unannounced channel we refrain from probing all the
3691                         // way through to the end and instead probe up to the second-to-last channel.
3692                         while let Some(last_path_hop) = path.hops.last() {
3693                                 if last_path_hop.maybe_announced_channel {
3694                                         // We found a potentially announced last hop.
3695                                         break;
3696                                 } else {
3697                                         // Drop the last hop, as it's likely unannounced.
3698                                         log_debug!(
3699                                                 self.logger,
3700                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3701                                                 last_path_hop.short_channel_id
3702                                         );
3703                                         let final_value_msat = path.final_value_msat();
3704                                         path.hops.pop();
3705                                         if let Some(new_last) = path.hops.last_mut() {
3706                                                 new_last.fee_msat += final_value_msat;
3707                                         }
3708                                 }
3709                         }
3710
3711                         if path.hops.len() < 2 {
3712                                 log_debug!(
3713                                         self.logger,
3714                                         "Skipped sending payment probe over path with less than two hops."
3715                                 );
3716                                 continue;
3717                         }
3718
3719                         if let Some(first_path_hop) = path.hops.first() {
3720                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3721                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3722                                 }) {
3723                                         let path_value = path.final_value_msat() + path.fee_msat();
3724                                         let used_liquidity =
3725                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3726
3727                                         if first_hop.next_outbound_htlc_limit_msat
3728                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3729                                         {
3730                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3731                                                 continue;
3732                                         } else {
3733                                                 *used_liquidity += path_value;
3734                                         }
3735                                 }
3736                         }
3737
3738                         res.push(self.send_probe(path).map_err(|e| {
3739                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3740                                 ProbeSendFailure::SendingFailed(e)
3741                         })?);
3742                 }
3743
3744                 Ok(res)
3745         }
3746
3747         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3748         /// which checks the correctness of the funding transaction given the associated channel.
3749         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3750                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3751                 mut find_funding_output: FundingOutput,
3752         ) -> Result<(), APIError> {
3753                 let per_peer_state = self.per_peer_state.read().unwrap();
3754                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3755                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3756
3757                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3758                 let peer_state = &mut *peer_state_lock;
3759                 let funding_txo;
3760                 let (mut chan, msg_opt) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3761                         Some(ChannelPhase::UnfundedOutboundV1(mut chan)) => {
3762                                 funding_txo = find_funding_output(&chan, &funding_transaction)?;
3763
3764                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3765                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &&logger)
3766                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3767                                                 let channel_id = chan.context.channel_id();
3768                                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
3769                                                 let shutdown_res = chan.context.force_shutdown(false, reason);
3770                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, None))
3771                                         } else { unreachable!(); });
3772                                 match funding_res {
3773                                         Ok(funding_msg) => (chan, funding_msg),
3774                                         Err((chan, err)) => {
3775                                                 mem::drop(peer_state_lock);
3776                                                 mem::drop(per_peer_state);
3777                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3778                                                 return Err(APIError::ChannelUnavailable {
3779                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3780                                                 });
3781                                         },
3782                                 }
3783                         },
3784                         Some(phase) => {
3785                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3786                                 return Err(APIError::APIMisuseError {
3787                                         err: format!(
3788                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3789                                                 temporary_channel_id, counterparty_node_id),
3790                                 })
3791                         },
3792                         None => return Err(APIError::ChannelUnavailable {err: format!(
3793                                 "Channel with id {} not found for the passed counterparty node_id {}",
3794                                 temporary_channel_id, counterparty_node_id),
3795                                 }),
3796                 };
3797
3798                 if let Some(msg) = msg_opt {
3799                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3800                                 node_id: chan.context.get_counterparty_node_id(),
3801                                 msg,
3802                         });
3803                 }
3804                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3805                         hash_map::Entry::Occupied(_) => {
3806                                 panic!("Generated duplicate funding txid?");
3807                         },
3808                         hash_map::Entry::Vacant(e) => {
3809                                 let mut outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
3810                                 match outpoint_to_peer.entry(funding_txo) {
3811                                         hash_map::Entry::Vacant(e) => { e.insert(chan.context.get_counterparty_node_id()); },
3812                                         hash_map::Entry::Occupied(o) => {
3813                                                 let err = format!(
3814                                                         "An existing channel using outpoint {} is open with peer {}",
3815                                                         funding_txo, o.get()
3816                                                 );
3817                                                 mem::drop(outpoint_to_peer);
3818                                                 mem::drop(peer_state_lock);
3819                                                 mem::drop(per_peer_state);
3820                                                 let reason = ClosureReason::ProcessingError { err: err.clone() };
3821                                                 self.finish_close_channel(chan.context.force_shutdown(true, reason));
3822                                                 return Err(APIError::ChannelUnavailable { err });
3823                                         }
3824                                 }
3825                                 e.insert(ChannelPhase::UnfundedOutboundV1(chan));
3826                         }
3827                 }
3828                 Ok(())
3829         }
3830
3831         #[cfg(test)]
3832         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3833                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3834                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3835                 })
3836         }
3837
3838         /// Call this upon creation of a funding transaction for the given channel.
3839         ///
3840         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3841         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3842         ///
3843         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3844         /// across the p2p network.
3845         ///
3846         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3847         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3848         ///
3849         /// May panic if the output found in the funding transaction is duplicative with some other
3850         /// channel (note that this should be trivially prevented by using unique funding transaction
3851         /// keys per-channel).
3852         ///
3853         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3854         /// counterparty's signature the funding transaction will automatically be broadcast via the
3855         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3856         ///
3857         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3858         /// not currently support replacing a funding transaction on an existing channel. Instead,
3859         /// create a new channel with a conflicting funding transaction.
3860         ///
3861         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3862         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3863         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3864         /// for more details.
3865         ///
3866         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3867         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3868         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3869                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3870         }
3871
3872         /// Call this upon creation of a batch funding transaction for the given channels.
3873         ///
3874         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3875         /// each individual channel and transaction output.
3876         ///
3877         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3878         /// will only be broadcast when we have safely received and persisted the counterparty's
3879         /// signature for each channel.
3880         ///
3881         /// If there is an error, all channels in the batch are to be considered closed.
3882         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3883                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3884                 let mut result = Ok(());
3885
3886                 if !funding_transaction.is_coin_base() {
3887                         for inp in funding_transaction.input.iter() {
3888                                 if inp.witness.is_empty() {
3889                                         result = result.and(Err(APIError::APIMisuseError {
3890                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3891                                         }));
3892                                 }
3893                         }
3894                 }
3895                 if funding_transaction.output.len() > u16::max_value() as usize {
3896                         result = result.and(Err(APIError::APIMisuseError {
3897                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3898                         }));
3899                 }
3900                 {
3901                         let height = self.best_block.read().unwrap().height();
3902                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3903                         // lower than the next block height. However, the modules constituting our Lightning
3904                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3905                         // module is ahead of LDK, only allow one more block of headroom.
3906                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) &&
3907                                 funding_transaction.lock_time.is_block_height() &&
3908                                 funding_transaction.lock_time.to_consensus_u32() > height + 1
3909                         {
3910                                 result = result.and(Err(APIError::APIMisuseError {
3911                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3912                                 }));
3913                         }
3914                 }
3915
3916                 let txid = funding_transaction.txid();
3917                 let is_batch_funding = temporary_channels.len() > 1;
3918                 let mut funding_batch_states = if is_batch_funding {
3919                         Some(self.funding_batch_states.lock().unwrap())
3920                 } else {
3921                         None
3922                 };
3923                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3924                         match states.entry(txid) {
3925                                 btree_map::Entry::Occupied(_) => {
3926                                         result = result.clone().and(Err(APIError::APIMisuseError {
3927                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3928                                         }));
3929                                         None
3930                                 },
3931                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3932                         }
3933                 });
3934                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3935                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3936                                 temporary_channel_id,
3937                                 counterparty_node_id,
3938                                 funding_transaction.clone(),
3939                                 is_batch_funding,
3940                                 |chan, tx| {
3941                                         let mut output_index = None;
3942                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3943                                         for (idx, outp) in tx.output.iter().enumerate() {
3944                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3945                                                         if output_index.is_some() {
3946                                                                 return Err(APIError::APIMisuseError {
3947                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3948                                                                 });
3949                                                         }
3950                                                         output_index = Some(idx as u16);
3951                                                 }
3952                                         }
3953                                         if output_index.is_none() {
3954                                                 return Err(APIError::APIMisuseError {
3955                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3956                                                 });
3957                                         }
3958                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3959                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3960                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3961                                         }
3962                                         Ok(outpoint)
3963                                 })
3964                         );
3965                 }
3966                 if let Err(ref e) = result {
3967                         // Remaining channels need to be removed on any error.
3968                         let e = format!("Error in transaction funding: {:?}", e);
3969                         let mut channels_to_remove = Vec::new();
3970                         channels_to_remove.extend(funding_batch_states.as_mut()
3971                                 .and_then(|states| states.remove(&txid))
3972                                 .into_iter().flatten()
3973                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3974                         );
3975                         channels_to_remove.extend(temporary_channels.iter()
3976                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3977                         );
3978                         let mut shutdown_results = Vec::new();
3979                         {
3980                                 let per_peer_state = self.per_peer_state.read().unwrap();
3981                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3982                                         per_peer_state.get(&counterparty_node_id)
3983                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3984                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3985                                                 .map(|mut chan| {
3986                                                         update_maps_on_chan_removal!(self, &chan.context());
3987                                                         let closure_reason = ClosureReason::ProcessingError { err: e.clone() };
3988                                                         shutdown_results.push(chan.context_mut().force_shutdown(false, closure_reason));
3989                                                 });
3990                                 }
3991                         }
3992                         mem::drop(funding_batch_states);
3993                         for shutdown_result in shutdown_results.drain(..) {
3994                                 self.finish_close_channel(shutdown_result);
3995                         }
3996                 }
3997                 result
3998         }
3999
4000         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
4001         ///
4002         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4003         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4004         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4005         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4006         ///
4007         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4008         /// `counterparty_node_id` is provided.
4009         ///
4010         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4011         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4012         ///
4013         /// If an error is returned, none of the updates should be considered applied.
4014         ///
4015         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4016         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4017         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4018         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4019         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4020         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4021         /// [`APIMisuseError`]: APIError::APIMisuseError
4022         pub fn update_partial_channel_config(
4023                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
4024         ) -> Result<(), APIError> {
4025                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
4026                         return Err(APIError::APIMisuseError {
4027                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
4028                         });
4029                 }
4030
4031                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4032                 let per_peer_state = self.per_peer_state.read().unwrap();
4033                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4034                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4035                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4036                 let peer_state = &mut *peer_state_lock;
4037                 for channel_id in channel_ids {
4038                         if !peer_state.has_channel(channel_id) {
4039                                 return Err(APIError::ChannelUnavailable {
4040                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4041                                 });
4042                         };
4043                 }
4044                 for channel_id in channel_ids {
4045                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4046                                 let mut config = channel_phase.context().config();
4047                                 config.apply(config_update);
4048                                 if !channel_phase.context_mut().update_config(&config) {
4049                                         continue;
4050                                 }
4051                                 if let ChannelPhase::Funded(channel) = channel_phase {
4052                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4053                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4054                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4055                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4056                                                         node_id: channel.context.get_counterparty_node_id(),
4057                                                         msg,
4058                                                 });
4059                                         }
4060                                 }
4061                                 continue;
4062                         } else {
4063                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4064                                 debug_assert!(false);
4065                                 return Err(APIError::ChannelUnavailable {
4066                                         err: format!(
4067                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4068                                                 channel_id, counterparty_node_id),
4069                                 });
4070                         };
4071                 }
4072                 Ok(())
4073         }
4074
4075         /// Atomically updates the [`ChannelConfig`] for the given channels.
4076         ///
4077         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4078         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4079         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4080         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4081         ///
4082         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4083         /// `counterparty_node_id` is provided.
4084         ///
4085         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4086         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4087         ///
4088         /// If an error is returned, none of the updates should be considered applied.
4089         ///
4090         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4091         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4092         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4093         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4094         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4095         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4096         /// [`APIMisuseError`]: APIError::APIMisuseError
4097         pub fn update_channel_config(
4098                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4099         ) -> Result<(), APIError> {
4100                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4101         }
4102
4103         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4104         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4105         ///
4106         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4107         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4108         ///
4109         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4110         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4111         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4112         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4113         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4114         ///
4115         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4116         /// you from forwarding more than you received. See
4117         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4118         /// than expected.
4119         ///
4120         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4121         /// backwards.
4122         ///
4123         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4124         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4125         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4126         // TODO: when we move to deciding the best outbound channel at forward time, only take
4127         // `next_node_id` and not `next_hop_channel_id`
4128         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> {
4129                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4130
4131                 let next_hop_scid = {
4132                         let peer_state_lock = self.per_peer_state.read().unwrap();
4133                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4134                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4135                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4136                         let peer_state = &mut *peer_state_lock;
4137                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4138                                 Some(ChannelPhase::Funded(chan)) => {
4139                                         if !chan.context.is_usable() {
4140                                                 return Err(APIError::ChannelUnavailable {
4141                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4142                                                 })
4143                                         }
4144                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4145                                 },
4146                                 Some(_) => return Err(APIError::ChannelUnavailable {
4147                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4148                                                 next_hop_channel_id, next_node_id)
4149                                 }),
4150                                 None => {
4151                                         let error = format!("Channel with id {} not found for the passed counterparty node_id {}",
4152                                                 next_hop_channel_id, next_node_id);
4153                                         let logger = WithContext::from(&self.logger, Some(next_node_id), Some(*next_hop_channel_id));
4154                                         log_error!(logger, "{} when attempting to forward intercepted HTLC", error);
4155                                         return Err(APIError::ChannelUnavailable {
4156                                                 err: error
4157                                         })
4158                                 }
4159                         }
4160                 };
4161
4162                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4163                         .ok_or_else(|| APIError::APIMisuseError {
4164                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4165                         })?;
4166
4167                 let routing = match payment.forward_info.routing {
4168                         PendingHTLCRouting::Forward { onion_packet, blinded, .. } => {
4169                                 PendingHTLCRouting::Forward {
4170                                         onion_packet, blinded, short_channel_id: next_hop_scid
4171                                 }
4172                         },
4173                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4174                 };
4175                 let skimmed_fee_msat =
4176                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4177                 let pending_htlc_info = PendingHTLCInfo {
4178                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4179                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4180                 };
4181
4182                 let mut per_source_pending_forward = [(
4183                         payment.prev_short_channel_id,
4184                         payment.prev_funding_outpoint,
4185                         payment.prev_user_channel_id,
4186                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4187                 )];
4188                 self.forward_htlcs(&mut per_source_pending_forward);
4189                 Ok(())
4190         }
4191
4192         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4193         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4194         ///
4195         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4196         /// backwards.
4197         ///
4198         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4199         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4200                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4201
4202                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4203                         .ok_or_else(|| APIError::APIMisuseError {
4204                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4205                         })?;
4206
4207                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4208                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4209                                 short_channel_id: payment.prev_short_channel_id,
4210                                 user_channel_id: Some(payment.prev_user_channel_id),
4211                                 outpoint: payment.prev_funding_outpoint,
4212                                 htlc_id: payment.prev_htlc_id,
4213                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4214                                 phantom_shared_secret: None,
4215                                 blinded_failure: payment.forward_info.routing.blinded_failure(),
4216                         });
4217
4218                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4219                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4220                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4221                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4222
4223                 Ok(())
4224         }
4225
4226         /// Processes HTLCs which are pending waiting on random forward delay.
4227         ///
4228         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4229         /// Will likely generate further events.
4230         pub fn process_pending_htlc_forwards(&self) {
4231                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4232
4233                 let mut new_events = VecDeque::new();
4234                 let mut failed_forwards = Vec::new();
4235                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4236                 {
4237                         let mut forward_htlcs = HashMap::new();
4238                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4239
4240                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4241                                 if short_chan_id != 0 {
4242                                         let mut forwarding_counterparty = None;
4243                                         macro_rules! forwarding_channel_not_found {
4244                                                 () => {
4245                                                         for forward_info in pending_forwards.drain(..) {
4246                                                                 match forward_info {
4247                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4248                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4249                                                                                 forward_info: PendingHTLCInfo {
4250                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4251                                                                                         outgoing_cltv_value, ..
4252                                                                                 }
4253                                                                         }) => {
4254                                                                                 macro_rules! failure_handler {
4255                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4256                                                                                                 let logger = WithContext::from(&self.logger, forwarding_counterparty, Some(prev_funding_outpoint.to_channel_id()));
4257                                                                                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4258
4259                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4260                                                                                                         short_channel_id: prev_short_channel_id,
4261                                                                                                         user_channel_id: Some(prev_user_channel_id),
4262                                                                                                         outpoint: prev_funding_outpoint,
4263                                                                                                         htlc_id: prev_htlc_id,
4264                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4265                                                                                                         phantom_shared_secret: $phantom_ss,
4266                                                                                                         blinded_failure: routing.blinded_failure(),
4267                                                                                                 });
4268
4269                                                                                                 let reason = if $next_hop_unknown {
4270                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4271                                                                                                 } else {
4272                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4273                                                                                                 };
4274
4275                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4276                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4277                                                                                                         reason
4278                                                                                                 ));
4279                                                                                                 continue;
4280                                                                                         }
4281                                                                                 }
4282                                                                                 macro_rules! fail_forward {
4283                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4284                                                                                                 {
4285                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4286                                                                                                 }
4287                                                                                         }
4288                                                                                 }
4289                                                                                 macro_rules! failed_payment {
4290                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4291                                                                                                 {
4292                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4293                                                                                                 }
4294                                                                                         }
4295                                                                                 }
4296                                                                                 if let PendingHTLCRouting::Forward { ref onion_packet, .. } = routing {
4297                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4298                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4299                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4300                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4301                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4302                                                                                                         payment_hash, None, &self.node_signer
4303                                                                                                 ) {
4304                                                                                                         Ok(res) => res,
4305                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4306                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).to_byte_array();
4307                                                                                                                 // In this scenario, the phantom would have sent us an
4308                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4309                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4310                                                                                                                 // of the onion.
4311                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4312                                                                                                         },
4313                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4314                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4315                                                                                                         },
4316                                                                                                 };
4317                                                                                                 match next_hop {
4318                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4319                                                                                                                 let current_height: u32 = self.best_block.read().unwrap().height();
4320                                                                                                                 match create_recv_pending_htlc_info(hop_data,
4321                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4322                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None,
4323                                                                                                                         current_height, self.default_configuration.accept_mpp_keysend)
4324                                                                                                                 {
4325                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4326                                                                                                                         Err(InboundHTLCErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4327                                                                                                                 }
4328                                                                                                         },
4329                                                                                                         _ => panic!(),
4330                                                                                                 }
4331                                                                                         } else {
4332                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4333                                                                                         }
4334                                                                                 } else {
4335                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4336                                                                                 }
4337                                                                         },
4338                                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4339                                                                                 // Channel went away before we could fail it. This implies
4340                                                                                 // the channel is now on chain and our counterparty is
4341                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4342                                                                                 // problem, not ours.
4343                                                                         }
4344                                                                 }
4345                                                         }
4346                                                 }
4347                                         }
4348                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4349                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4350                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4351                                                 None => {
4352                                                         forwarding_channel_not_found!();
4353                                                         continue;
4354                                                 }
4355                                         };
4356                                         forwarding_counterparty = Some(counterparty_node_id);
4357                                         let per_peer_state = self.per_peer_state.read().unwrap();
4358                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4359                                         if peer_state_mutex_opt.is_none() {
4360                                                 forwarding_channel_not_found!();
4361                                                 continue;
4362                                         }
4363                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4364                                         let peer_state = &mut *peer_state_lock;
4365                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4366                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4367                                                 for forward_info in pending_forwards.drain(..) {
4368                                                         let queue_fail_htlc_res = match forward_info {
4369                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4370                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4371                                                                         forward_info: PendingHTLCInfo {
4372                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4373                                                                                 routing: PendingHTLCRouting::Forward {
4374                                                                                         onion_packet, blinded, ..
4375                                                                                 }, skimmed_fee_msat, ..
4376                                                                         },
4377                                                                 }) => {
4378                                                                         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);
4379                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4380                                                                                 short_channel_id: prev_short_channel_id,
4381                                                                                 user_channel_id: Some(prev_user_channel_id),
4382                                                                                 outpoint: prev_funding_outpoint,
4383                                                                                 htlc_id: prev_htlc_id,
4384                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4385                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4386                                                                                 phantom_shared_secret: None,
4387                                                                                 blinded_failure: blinded.map(|b| b.failure),
4388                                                                         });
4389                                                                         let next_blinding_point = blinded.and_then(|b| {
4390                                                                                 let encrypted_tlvs_ss = self.node_signer.ecdh(
4391                                                                                         Recipient::Node, &b.inbound_blinding_point, None
4392                                                                                 ).unwrap().secret_bytes();
4393                                                                                 onion_utils::next_hop_pubkey(
4394                                                                                         &self.secp_ctx, b.inbound_blinding_point, &encrypted_tlvs_ss
4395                                                                                 ).ok()
4396                                                                         });
4397                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4398                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4399                                                                                 onion_packet, skimmed_fee_msat, next_blinding_point, &self.fee_estimator,
4400                                                                                 &&logger)
4401                                                                         {
4402                                                                                 if let ChannelError::Ignore(msg) = e {
4403                                                                                         log_trace!(logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4404                                                                                 } else {
4405                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4406                                                                                 }
4407                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4408                                                                                 failed_forwards.push((htlc_source, payment_hash,
4409                                                                                         HTLCFailReason::reason(failure_code, data),
4410                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4411                                                                                 ));
4412                                                                                 continue;
4413                                                                         }
4414                                                                         None
4415                                                                 },
4416                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4417                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4418                                                                 },
4419                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4420                                                                         log_trace!(logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4421                                                                         Some((chan.queue_fail_htlc(htlc_id, err_packet, &&logger), htlc_id))
4422                                                                 },
4423                                                                 HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
4424                                                                         log_trace!(logger, "Failing malformed HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4425                                                                         let res = chan.queue_fail_malformed_htlc(
4426                                                                                 htlc_id, failure_code, sha256_of_onion, &&logger
4427                                                                         );
4428                                                                         Some((res, htlc_id))
4429                                                                 },
4430                                                         };
4431                                                         if let Some((queue_fail_htlc_res, htlc_id)) = queue_fail_htlc_res {
4432                                                                 if let Err(e) = queue_fail_htlc_res {
4433                                                                         if let ChannelError::Ignore(msg) = e {
4434                                                                                 log_trace!(logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4435                                                                         } else {
4436                                                                                 panic!("Stated return value requirements in queue_fail_{{malformed_}}htlc() were not met");
4437                                                                         }
4438                                                                         // fail-backs are best-effort, we probably already have one
4439                                                                         // pending, and if not that's OK, if not, the channel is on
4440                                                                         // the chain and sending the HTLC-Timeout is their problem.
4441                                                                         continue;
4442                                                                 }
4443                                                         }
4444                                                 }
4445                                         } else {
4446                                                 forwarding_channel_not_found!();
4447                                                 continue;
4448                                         }
4449                                 } else {
4450                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4451                                                 match forward_info {
4452                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4453                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4454                                                                 forward_info: PendingHTLCInfo {
4455                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4456                                                                         skimmed_fee_msat, ..
4457                                                                 }
4458                                                         }) => {
4459                                                                 let blinded_failure = routing.blinded_failure();
4460                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4461                                                                         PendingHTLCRouting::Receive {
4462                                                                                 payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret,
4463                                                                                 custom_tlvs, requires_blinded_error: _
4464                                                                         } => {
4465                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4466                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4467                                                                                                 payment_metadata, custom_tlvs };
4468                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4469                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4470                                                                         },
4471                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4472                                                                                 let onion_fields = RecipientOnionFields {
4473                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4474                                                                                         payment_metadata,
4475                                                                                         custom_tlvs,
4476                                                                                 };
4477                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4478                                                                                         payment_data, None, onion_fields)
4479                                                                         },
4480                                                                         _ => {
4481                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4482                                                                         }
4483                                                                 };
4484                                                                 let claimable_htlc = ClaimableHTLC {
4485                                                                         prev_hop: HTLCPreviousHopData {
4486                                                                                 short_channel_id: prev_short_channel_id,
4487                                                                                 user_channel_id: Some(prev_user_channel_id),
4488                                                                                 outpoint: prev_funding_outpoint,
4489                                                                                 htlc_id: prev_htlc_id,
4490                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4491                                                                                 phantom_shared_secret,
4492                                                                                 blinded_failure,
4493                                                                         },
4494                                                                         // We differentiate the received value from the sender intended value
4495                                                                         // if possible so that we don't prematurely mark MPP payments complete
4496                                                                         // if routing nodes overpay
4497                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4498                                                                         sender_intended_value: outgoing_amt_msat,
4499                                                                         timer_ticks: 0,
4500                                                                         total_value_received: None,
4501                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4502                                                                         cltv_expiry,
4503                                                                         onion_payload,
4504                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4505                                                                 };
4506
4507                                                                 let mut committed_to_claimable = false;
4508
4509                                                                 macro_rules! fail_htlc {
4510                                                                         ($htlc: expr, $payment_hash: expr) => {
4511                                                                                 debug_assert!(!committed_to_claimable);
4512                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4513                                                                                 htlc_msat_height_data.extend_from_slice(
4514                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4515                                                                                 );
4516                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4517                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4518                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4519                                                                                                 outpoint: prev_funding_outpoint,
4520                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4521                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4522                                                                                                 phantom_shared_secret,
4523                                                                                                 blinded_failure,
4524                                                                                         }), payment_hash,
4525                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4526                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4527                                                                                 ));
4528                                                                                 continue 'next_forwardable_htlc;
4529                                                                         }
4530                                                                 }
4531                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4532                                                                 let mut receiver_node_id = self.our_network_pubkey;
4533                                                                 if phantom_shared_secret.is_some() {
4534                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4535                                                                                 .expect("Failed to get node_id for phantom node recipient");
4536                                                                 }
4537
4538                                                                 macro_rules! check_total_value {
4539                                                                         ($purpose: expr) => {{
4540                                                                                 let mut payment_claimable_generated = false;
4541                                                                                 let is_keysend = match $purpose {
4542                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4543                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4544                                                                                 };
4545                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4546                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4547                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4548                                                                                 }
4549                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4550                                                                                         .entry(payment_hash)
4551                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4552                                                                                         .or_insert_with(|| {
4553                                                                                                 committed_to_claimable = true;
4554                                                                                                 ClaimablePayment {
4555                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4556                                                                                                 }
4557                                                                                         });
4558                                                                                 if $purpose != claimable_payment.purpose {
4559                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4560                                                                                         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));
4561                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4562                                                                                 }
4563                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4564                                                                                         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);
4565                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4566                                                                                 }
4567                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4568                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4569                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4570                                                                                         }
4571                                                                                 } else {
4572                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4573                                                                                 }
4574                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4575                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4576                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4577                                                                                 for htlc in htlcs.iter() {
4578                                                                                         total_value += htlc.sender_intended_value;
4579                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4580                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4581                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4582                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4583                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4584                                                                                         }
4585                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4586                                                                                 }
4587                                                                                 // The condition determining whether an MPP is complete must
4588                                                                                 // match exactly the condition used in `timer_tick_occurred`
4589                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4590                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4591                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4592                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4593                                                                                                 &payment_hash);
4594                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4595                                                                                 } else if total_value >= claimable_htlc.total_msat {
4596                                                                                         #[allow(unused_assignments)] {
4597                                                                                                 committed_to_claimable = true;
4598                                                                                         }
4599                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4600                                                                                         htlcs.push(claimable_htlc);
4601                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4602                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4603                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4604                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4605                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4606                                                                                                 counterparty_skimmed_fee_msat);
4607                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4608                                                                                                 receiver_node_id: Some(receiver_node_id),
4609                                                                                                 payment_hash,
4610                                                                                                 purpose: $purpose,
4611                                                                                                 amount_msat,
4612                                                                                                 counterparty_skimmed_fee_msat,
4613                                                                                                 via_channel_id: Some(prev_channel_id),
4614                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4615                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4616                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4617                                                                                         }, None));
4618                                                                                         payment_claimable_generated = true;
4619                                                                                 } else {
4620                                                                                         // Nothing to do - we haven't reached the total
4621                                                                                         // payment value yet, wait until we receive more
4622                                                                                         // MPP parts.
4623                                                                                         htlcs.push(claimable_htlc);
4624                                                                                         #[allow(unused_assignments)] {
4625                                                                                                 committed_to_claimable = true;
4626                                                                                         }
4627                                                                                 }
4628                                                                                 payment_claimable_generated
4629                                                                         }}
4630                                                                 }
4631
4632                                                                 // Check that the payment hash and secret are known. Note that we
4633                                                                 // MUST take care to handle the "unknown payment hash" and
4634                                                                 // "incorrect payment secret" cases here identically or we'd expose
4635                                                                 // that we are the ultimate recipient of the given payment hash.
4636                                                                 // Further, we must not expose whether we have any other HTLCs
4637                                                                 // associated with the same payment_hash pending or not.
4638                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4639                                                                 match payment_secrets.entry(payment_hash) {
4640                                                                         hash_map::Entry::Vacant(_) => {
4641                                                                                 match claimable_htlc.onion_payload {
4642                                                                                         OnionPayload::Invoice { .. } => {
4643                                                                                                 let payment_data = payment_data.unwrap();
4644                                                                                                 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) {
4645                                                                                                         Ok(result) => result,
4646                                                                                                         Err(()) => {
4647                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4648                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4649                                                                                                         }
4650                                                                                                 };
4651                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4652                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4653                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4654                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4655                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4656                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4657                                                                                                         }
4658                                                                                                 }
4659                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4660                                                                                                         payment_preimage: payment_preimage.clone(),
4661                                                                                                         payment_secret: payment_data.payment_secret,
4662                                                                                                 };
4663                                                                                                 check_total_value!(purpose);
4664                                                                                         },
4665                                                                                         OnionPayload::Spontaneous(preimage) => {
4666                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4667                                                                                                 check_total_value!(purpose);
4668                                                                                         }
4669                                                                                 }
4670                                                                         },
4671                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4672                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4673                                                                                         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);
4674                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4675                                                                                 }
4676                                                                                 let payment_data = payment_data.unwrap();
4677                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4678                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4679                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4680                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4681                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4682                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4683                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4684                                                                                 } else {
4685                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4686                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4687                                                                                                 payment_secret: payment_data.payment_secret,
4688                                                                                         };
4689                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4690                                                                                         if payment_claimable_generated {
4691                                                                                                 inbound_payment.remove_entry();
4692                                                                                         }
4693                                                                                 }
4694                                                                         },
4695                                                                 };
4696                                                         },
4697                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4698                                                                 panic!("Got pending fail of our own HTLC");
4699                                                         }
4700                                                 }
4701                                         }
4702                                 }
4703                         }
4704                 }
4705
4706                 let best_block_height = self.best_block.read().unwrap().height();
4707                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4708                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4709                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4710
4711                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4712                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4713                 }
4714                 self.forward_htlcs(&mut phantom_receives);
4715
4716                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4717                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4718                 // nice to do the work now if we can rather than while we're trying to get messages in the
4719                 // network stack.
4720                 self.check_free_holding_cells();
4721
4722                 if new_events.is_empty() { return }
4723                 let mut events = self.pending_events.lock().unwrap();
4724                 events.append(&mut new_events);
4725         }
4726
4727         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4728         ///
4729         /// Expects the caller to have a total_consistency_lock read lock.
4730         fn process_background_events(&self) -> NotifyOption {
4731                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4732
4733                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4734
4735                 let mut background_events = Vec::new();
4736                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4737                 if background_events.is_empty() {
4738                         return NotifyOption::SkipPersistNoEvents;
4739                 }
4740
4741                 for event in background_events.drain(..) {
4742                         match event {
4743                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4744                                         // The channel has already been closed, so no use bothering to care about the
4745                                         // monitor updating completing.
4746                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4747                                 },
4748                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4749                                         let mut updated_chan = false;
4750                                         {
4751                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4752                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4753                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4754                                                         let peer_state = &mut *peer_state_lock;
4755                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4756                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4757                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4758                                                                                 updated_chan = true;
4759                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4760                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4761                                                                         } else {
4762                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4763                                                                         }
4764                                                                 },
4765                                                                 hash_map::Entry::Vacant(_) => {},
4766                                                         }
4767                                                 }
4768                                         }
4769                                         if !updated_chan {
4770                                                 // TODO: Track this as in-flight even though the channel is closed.
4771                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4772                                         }
4773                                 },
4774                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4775                                         let per_peer_state = self.per_peer_state.read().unwrap();
4776                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4777                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4778                                                 let peer_state = &mut *peer_state_lock;
4779                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4780                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4781                                                 } else {
4782                                                         let update_actions = peer_state.monitor_update_blocked_actions
4783                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4784                                                         mem::drop(peer_state_lock);
4785                                                         mem::drop(per_peer_state);
4786                                                         self.handle_monitor_update_completion_actions(update_actions);
4787                                                 }
4788                                         }
4789                                 },
4790                         }
4791                 }
4792                 NotifyOption::DoPersist
4793         }
4794
4795         #[cfg(any(test, feature = "_test_utils"))]
4796         /// Process background events, for functional testing
4797         pub fn test_process_background_events(&self) {
4798                 let _lck = self.total_consistency_lock.read().unwrap();
4799                 let _ = self.process_background_events();
4800         }
4801
4802         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4803                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4804
4805                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4806
4807                 // If the feerate has decreased by less than half, don't bother
4808                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4809                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4810                                 log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4811                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4812                         }
4813                         return NotifyOption::SkipPersistNoEvents;
4814                 }
4815                 if !chan.context.is_live() {
4816                         log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
4817                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4818                         return NotifyOption::SkipPersistNoEvents;
4819                 }
4820                 log_trace!(logger, "Channel {} qualifies for a feerate change from {} to {}.",
4821                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4822
4823                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &&logger);
4824                 NotifyOption::DoPersist
4825         }
4826
4827         #[cfg(fuzzing)]
4828         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4829         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4830         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4831         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4832         pub fn maybe_update_chan_fees(&self) {
4833                 PersistenceNotifierGuard::optionally_notify(self, || {
4834                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4835
4836                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4837                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4838
4839                         let per_peer_state = self.per_peer_state.read().unwrap();
4840                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4841                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4842                                 let peer_state = &mut *peer_state_lock;
4843                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4844                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4845                                 ) {
4846                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4847                                                 anchor_feerate
4848                                         } else {
4849                                                 non_anchor_feerate
4850                                         };
4851                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4852                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4853                                 }
4854                         }
4855
4856                         should_persist
4857                 });
4858         }
4859
4860         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4861         ///
4862         /// This currently includes:
4863         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4864         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4865         ///    than a minute, informing the network that they should no longer attempt to route over
4866         ///    the channel.
4867         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4868         ///    with the current [`ChannelConfig`].
4869         ///  * Removing peers which have disconnected but and no longer have any channels.
4870         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4871         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4872         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4873         ///    The latter is determined using the system clock in `std` and the highest seen block time
4874         ///    minus two hours in `no-std`.
4875         ///
4876         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4877         /// estimate fetches.
4878         ///
4879         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4880         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4881         pub fn timer_tick_occurred(&self) {
4882                 PersistenceNotifierGuard::optionally_notify(self, || {
4883                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4884
4885                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4886                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4887
4888                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4889                         let mut timed_out_mpp_htlcs = Vec::new();
4890                         let mut pending_peers_awaiting_removal = Vec::new();
4891                         let mut shutdown_channels = Vec::new();
4892
4893                         let mut process_unfunded_channel_tick = |
4894                                 chan_id: &ChannelId,
4895                                 context: &mut ChannelContext<SP>,
4896                                 unfunded_context: &mut UnfundedChannelContext,
4897                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4898                                 counterparty_node_id: PublicKey,
4899                         | {
4900                                 context.maybe_expire_prev_config();
4901                                 if unfunded_context.should_expire_unfunded_channel() {
4902                                         let logger = WithChannelContext::from(&self.logger, context);
4903                                         log_error!(logger,
4904                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4905                                         update_maps_on_chan_removal!(self, &context);
4906                                         shutdown_channels.push(context.force_shutdown(false, ClosureReason::HolderForceClosed));
4907                                         pending_msg_events.push(MessageSendEvent::HandleError {
4908                                                 node_id: counterparty_node_id,
4909                                                 action: msgs::ErrorAction::SendErrorMessage {
4910                                                         msg: msgs::ErrorMessage {
4911                                                                 channel_id: *chan_id,
4912                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4913                                                         },
4914                                                 },
4915                                         });
4916                                         false
4917                                 } else {
4918                                         true
4919                                 }
4920                         };
4921
4922                         {
4923                                 let per_peer_state = self.per_peer_state.read().unwrap();
4924                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4925                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4926                                         let peer_state = &mut *peer_state_lock;
4927                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4928                                         let counterparty_node_id = *counterparty_node_id;
4929                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4930                                                 match phase {
4931                                                         ChannelPhase::Funded(chan) => {
4932                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4933                                                                         anchor_feerate
4934                                                                 } else {
4935                                                                         non_anchor_feerate
4936                                                                 };
4937                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4938                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4939
4940                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4941                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4942                                                                         handle_errors.push((Err(err), counterparty_node_id));
4943                                                                         if needs_close { return false; }
4944                                                                 }
4945
4946                                                                 match chan.channel_update_status() {
4947                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4948                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4949                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4950                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4951                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4952                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4953                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4954                                                                                 n += 1;
4955                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4956                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4957                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4958                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4959                                                                                                         msg: update
4960                                                                                                 });
4961                                                                                         }
4962                                                                                         should_persist = NotifyOption::DoPersist;
4963                                                                                 } else {
4964                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4965                                                                                 }
4966                                                                         },
4967                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4968                                                                                 n += 1;
4969                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4970                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4971                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4972                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4973                                                                                                         msg: update
4974                                                                                                 });
4975                                                                                         }
4976                                                                                         should_persist = NotifyOption::DoPersist;
4977                                                                                 } else {
4978                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4979                                                                                 }
4980                                                                         },
4981                                                                         _ => {},
4982                                                                 }
4983
4984                                                                 chan.context.maybe_expire_prev_config();
4985
4986                                                                 if chan.should_disconnect_peer_awaiting_response() {
4987                                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
4988                                                                         log_debug!(logger, "Disconnecting peer {} due to not making any progress on channel {}",
4989                                                                                         counterparty_node_id, chan_id);
4990                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4991                                                                                 node_id: counterparty_node_id,
4992                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4993                                                                                         msg: msgs::WarningMessage {
4994                                                                                                 channel_id: *chan_id,
4995                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4996                                                                                         },
4997                                                                                 },
4998                                                                         });
4999                                                                 }
5000
5001                                                                 true
5002                                                         },
5003                                                         ChannelPhase::UnfundedInboundV1(chan) => {
5004                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5005                                                                         pending_msg_events, counterparty_node_id)
5006                                                         },
5007                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
5008                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5009                                                                         pending_msg_events, counterparty_node_id)
5010                                                         },
5011                                                 }
5012                                         });
5013
5014                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
5015                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
5016                                                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(*chan_id));
5017                                                         log_error!(logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
5018                                                         peer_state.pending_msg_events.push(
5019                                                                 events::MessageSendEvent::HandleError {
5020                                                                         node_id: counterparty_node_id,
5021                                                                         action: msgs::ErrorAction::SendErrorMessage {
5022                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
5023                                                                         },
5024                                                                 }
5025                                                         );
5026                                                 }
5027                                         }
5028                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
5029
5030                                         if peer_state.ok_to_remove(true) {
5031                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
5032                                         }
5033                                 }
5034                         }
5035
5036                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
5037                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
5038                         // of to that peer is later closed while still being disconnected (i.e. force closed),
5039                         // we therefore need to remove the peer from `peer_state` separately.
5040                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
5041                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
5042                         // negative effects on parallelism as much as possible.
5043                         if pending_peers_awaiting_removal.len() > 0 {
5044                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
5045                                 for counterparty_node_id in pending_peers_awaiting_removal {
5046                                         match per_peer_state.entry(counterparty_node_id) {
5047                                                 hash_map::Entry::Occupied(entry) => {
5048                                                         // Remove the entry if the peer is still disconnected and we still
5049                                                         // have no channels to the peer.
5050                                                         let remove_entry = {
5051                                                                 let peer_state = entry.get().lock().unwrap();
5052                                                                 peer_state.ok_to_remove(true)
5053                                                         };
5054                                                         if remove_entry {
5055                                                                 entry.remove_entry();
5056                                                         }
5057                                                 },
5058                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
5059                                         }
5060                                 }
5061                         }
5062
5063                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
5064                                 if payment.htlcs.is_empty() {
5065                                         // This should be unreachable
5066                                         debug_assert!(false);
5067                                         return false;
5068                                 }
5069                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
5070                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
5071                                         // In this case we're not going to handle any timeouts of the parts here.
5072                                         // This condition determining whether the MPP is complete here must match
5073                                         // exactly the condition used in `process_pending_htlc_forwards`.
5074                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5075                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5076                                         {
5077                                                 return true;
5078                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5079                                                 htlc.timer_ticks += 1;
5080                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5081                                         }) {
5082                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5083                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5084                                                 return false;
5085                                         }
5086                                 }
5087                                 true
5088                         });
5089
5090                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5091                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5092                                 let reason = HTLCFailReason::from_failure_code(23);
5093                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5094                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5095                         }
5096
5097                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5098                                 let _ = handle_error!(self, err, counterparty_node_id);
5099                         }
5100
5101                         for shutdown_res in shutdown_channels {
5102                                 self.finish_close_channel(shutdown_res);
5103                         }
5104
5105                         #[cfg(feature = "std")]
5106                         let duration_since_epoch = std::time::SystemTime::now()
5107                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5108                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5109                         #[cfg(not(feature = "std"))]
5110                         let duration_since_epoch = Duration::from_secs(
5111                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5112                         );
5113
5114                         self.pending_outbound_payments.remove_stale_payments(
5115                                 duration_since_epoch, &self.pending_events
5116                         );
5117
5118                         // Technically we don't need to do this here, but if we have holding cell entries in a
5119                         // channel that need freeing, it's better to do that here and block a background task
5120                         // than block the message queueing pipeline.
5121                         if self.check_free_holding_cells() {
5122                                 should_persist = NotifyOption::DoPersist;
5123                         }
5124
5125                         should_persist
5126                 });
5127         }
5128
5129         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5130         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5131         /// along the path (including in our own channel on which we received it).
5132         ///
5133         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5134         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5135         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5136         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5137         ///
5138         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5139         /// [`ChannelManager::claim_funds`]), you should still monitor for
5140         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5141         /// startup during which time claims that were in-progress at shutdown may be replayed.
5142         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5143                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5144         }
5145
5146         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5147         /// reason for the failure.
5148         ///
5149         /// See [`FailureCode`] for valid failure codes.
5150         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5151                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5152
5153                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5154                 if let Some(payment) = removed_source {
5155                         for htlc in payment.htlcs {
5156                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5157                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5158                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5159                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5160                         }
5161                 }
5162         }
5163
5164         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5165         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5166                 match failure_code {
5167                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5168                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5169                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5170                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5171                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5172                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5173                         },
5174                         FailureCode::InvalidOnionPayload(data) => {
5175                                 let fail_data = match data {
5176                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5177                                         None => Vec::new(),
5178                                 };
5179                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5180                         }
5181                 }
5182         }
5183
5184         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5185         /// that we want to return and a channel.
5186         ///
5187         /// This is for failures on the channel on which the HTLC was *received*, not failures
5188         /// forwarding
5189         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5190                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5191                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5192                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5193                 // an inbound SCID alias before the real SCID.
5194                 let scid_pref = if chan.context.should_announce() {
5195                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5196                 } else {
5197                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5198                 };
5199                 if let Some(scid) = scid_pref {
5200                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5201                 } else {
5202                         (0x4000|10, Vec::new())
5203                 }
5204         }
5205
5206
5207         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5208         /// that we want to return and a channel.
5209         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5210                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5211                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5212                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5213                         if desired_err_code == 0x1000 | 20 {
5214                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5215                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5216                                 0u16.write(&mut enc).expect("Writes cannot fail");
5217                         }
5218                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5219                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5220                         upd.write(&mut enc).expect("Writes cannot fail");
5221                         (desired_err_code, enc.0)
5222                 } else {
5223                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5224                         // which means we really shouldn't have gotten a payment to be forwarded over this
5225                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5226                         // PERM|no_such_channel should be fine.
5227                         (0x4000|10, Vec::new())
5228                 }
5229         }
5230
5231         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5232         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5233         // be surfaced to the user.
5234         fn fail_holding_cell_htlcs(
5235                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5236                 counterparty_node_id: &PublicKey
5237         ) {
5238                 let (failure_code, onion_failure_data) = {
5239                         let per_peer_state = self.per_peer_state.read().unwrap();
5240                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5241                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5242                                 let peer_state = &mut *peer_state_lock;
5243                                 match peer_state.channel_by_id.entry(channel_id) {
5244                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5245                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5246                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5247                                                 } else {
5248                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5249                                                         debug_assert!(false);
5250                                                         (0x4000|10, Vec::new())
5251                                                 }
5252                                         },
5253                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5254                                 }
5255                         } else { (0x4000|10, Vec::new()) }
5256                 };
5257
5258                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5259                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5260                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5261                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5262                 }
5263         }
5264
5265         /// Fails an HTLC backwards to the sender of it to us.
5266         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5267         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5268                 // Ensure that no peer state channel storage lock is held when calling this function.
5269                 // This ensures that future code doesn't introduce a lock-order requirement for
5270                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5271                 // this function with any `per_peer_state` peer lock acquired would.
5272                 #[cfg(debug_assertions)]
5273                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5274                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5275                 }
5276
5277                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5278                 //identify whether we sent it or not based on the (I presume) very different runtime
5279                 //between the branches here. We should make this async and move it into the forward HTLCs
5280                 //timer handling.
5281
5282                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5283                 // from block_connected which may run during initialization prior to the chain_monitor
5284                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5285                 match source {
5286                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5287                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5288                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5289                                         &self.pending_events, &self.logger)
5290                                 { self.push_pending_forwards_ev(); }
5291                         },
5292                         HTLCSource::PreviousHopData(HTLCPreviousHopData {
5293                                 ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret,
5294                                 ref phantom_shared_secret, ref outpoint, ref blinded_failure, ..
5295                         }) => {
5296                                 log_trace!(
5297                                         WithContext::from(&self.logger, None, Some(outpoint.to_channel_id())),
5298                                         "Failing {}HTLC with payment_hash {} backwards from us: {:?}",
5299                                         if blinded_failure.is_some() { "blinded " } else { "" }, &payment_hash, onion_error
5300                                 );
5301                                 let failure = match blinded_failure {
5302                                         Some(BlindedFailure::FromIntroductionNode) => {
5303                                                 let blinded_onion_error = HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32]);
5304                                                 let err_packet = blinded_onion_error.get_encrypted_failure_packet(
5305                                                         incoming_packet_shared_secret, phantom_shared_secret
5306                                                 );
5307                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5308                                         },
5309                                         Some(BlindedFailure::FromBlindedNode) => {
5310                                                 HTLCForwardInfo::FailMalformedHTLC {
5311                                                         htlc_id: *htlc_id,
5312                                                         failure_code: INVALID_ONION_BLINDING,
5313                                                         sha256_of_onion: [0; 32]
5314                                                 }
5315                                         },
5316                                         None => {
5317                                                 let err_packet = onion_error.get_encrypted_failure_packet(
5318                                                         incoming_packet_shared_secret, phantom_shared_secret
5319                                                 );
5320                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5321                                         }
5322                                 };
5323
5324                                 let mut push_forward_ev = false;
5325                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5326                                 if forward_htlcs.is_empty() {
5327                                         push_forward_ev = true;
5328                                 }
5329                                 match forward_htlcs.entry(*short_channel_id) {
5330                                         hash_map::Entry::Occupied(mut entry) => {
5331                                                 entry.get_mut().push(failure);
5332                                         },
5333                                         hash_map::Entry::Vacant(entry) => {
5334                                                 entry.insert(vec!(failure));
5335                                         }
5336                                 }
5337                                 mem::drop(forward_htlcs);
5338                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5339                                 let mut pending_events = self.pending_events.lock().unwrap();
5340                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5341                                         prev_channel_id: outpoint.to_channel_id(),
5342                                         failed_next_destination: destination,
5343                                 }, None));
5344                         },
5345                 }
5346         }
5347
5348         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5349         /// [`MessageSendEvent`]s needed to claim the payment.
5350         ///
5351         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5352         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5353         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5354         /// successful. It will generally be available in the next [`process_pending_events`] call.
5355         ///
5356         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5357         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5358         /// event matches your expectation. If you fail to do so and call this method, you may provide
5359         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5360         ///
5361         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5362         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5363         /// [`claim_funds_with_known_custom_tlvs`].
5364         ///
5365         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5366         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5367         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5368         /// [`process_pending_events`]: EventsProvider::process_pending_events
5369         /// [`create_inbound_payment`]: Self::create_inbound_payment
5370         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5371         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5372         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5373                 self.claim_payment_internal(payment_preimage, false);
5374         }
5375
5376         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5377         /// even type numbers.
5378         ///
5379         /// # Note
5380         ///
5381         /// You MUST check you've understood all even TLVs before using this to
5382         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5383         ///
5384         /// [`claim_funds`]: Self::claim_funds
5385         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5386                 self.claim_payment_internal(payment_preimage, true);
5387         }
5388
5389         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5390                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
5391
5392                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5393
5394                 let mut sources = {
5395                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5396                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5397                                 let mut receiver_node_id = self.our_network_pubkey;
5398                                 for htlc in payment.htlcs.iter() {
5399                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5400                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5401                                                         .expect("Failed to get node_id for phantom node recipient");
5402                                                 receiver_node_id = phantom_pubkey;
5403                                                 break;
5404                                         }
5405                                 }
5406
5407                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5408                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5409                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5410                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5411                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5412                                 });
5413                                 if dup_purpose.is_some() {
5414                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5415                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5416                                                 &payment_hash);
5417                                 }
5418
5419                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5420                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5421                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5422                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5423                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5424                                                 mem::drop(claimable_payments);
5425                                                 for htlc in payment.htlcs {
5426                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5427                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5428                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5429                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5430                                                 }
5431                                                 return;
5432                                         }
5433                                 }
5434
5435                                 payment.htlcs
5436                         } else { return; }
5437                 };
5438                 debug_assert!(!sources.is_empty());
5439
5440                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5441                 // and when we got here we need to check that the amount we're about to claim matches the
5442                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5443                 // the MPP parts all have the same `total_msat`.
5444                 let mut claimable_amt_msat = 0;
5445                 let mut prev_total_msat = None;
5446                 let mut expected_amt_msat = None;
5447                 let mut valid_mpp = true;
5448                 let mut errs = Vec::new();
5449                 let per_peer_state = self.per_peer_state.read().unwrap();
5450                 for htlc in sources.iter() {
5451                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5452                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5453                                 debug_assert!(false);
5454                                 valid_mpp = false;
5455                                 break;
5456                         }
5457                         prev_total_msat = Some(htlc.total_msat);
5458
5459                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5460                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5461                                 debug_assert!(false);
5462                                 valid_mpp = false;
5463                                 break;
5464                         }
5465                         expected_amt_msat = htlc.total_value_received;
5466                         claimable_amt_msat += htlc.value;
5467                 }
5468                 mem::drop(per_peer_state);
5469                 if sources.is_empty() || expected_amt_msat.is_none() {
5470                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5471                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5472                         return;
5473                 }
5474                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5475                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5476                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5477                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5478                         return;
5479                 }
5480                 if valid_mpp {
5481                         for htlc in sources.drain(..) {
5482                                 let prev_hop_chan_id = htlc.prev_hop.outpoint.to_channel_id();
5483                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5484                                         htlc.prev_hop, payment_preimage,
5485                                         |_, definitely_duplicate| {
5486                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5487                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5488                                         }
5489                                 ) {
5490                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5491                                                 // We got a temporary failure updating monitor, but will claim the
5492                                                 // HTLC when the monitor updating is restored (or on chain).
5493                                                 let logger = WithContext::from(&self.logger, None, Some(prev_hop_chan_id));
5494                                                 log_error!(logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5495                                         } else { errs.push((pk, err)); }
5496                                 }
5497                         }
5498                 }
5499                 if !valid_mpp {
5500                         for htlc in sources.drain(..) {
5501                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5502                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5503                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5504                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5505                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5506                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5507                         }
5508                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5509                 }
5510
5511                 // Now we can handle any errors which were generated.
5512                 for (counterparty_node_id, err) in errs.drain(..) {
5513                         let res: Result<(), _> = Err(err);
5514                         let _ = handle_error!(self, res, counterparty_node_id);
5515                 }
5516         }
5517
5518         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5519                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5520         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5521                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5522
5523                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5524                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5525                 // `BackgroundEvent`s.
5526                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5527
5528                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5529                 // the required mutexes are not held before we start.
5530                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5531                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5532
5533                 {
5534                         let per_peer_state = self.per_peer_state.read().unwrap();
5535                         let chan_id = prev_hop.outpoint.to_channel_id();
5536                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5537                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5538                                 None => None
5539                         };
5540
5541                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5542                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5543                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5544                         ).unwrap_or(None);
5545
5546                         if peer_state_opt.is_some() {
5547                                 let mut peer_state_lock = peer_state_opt.unwrap();
5548                                 let peer_state = &mut *peer_state_lock;
5549                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5550                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5551                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5552                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
5553                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &&logger);
5554
5555                                                 match fulfill_res {
5556                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5557                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5558                                                                         log_trace!(logger, "Tracking monitor update completion action for channel {}: {:?}",
5559                                                                                 chan_id, action);
5560                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5561                                                                 }
5562                                                                 if !during_init {
5563                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5564                                                                                 peer_state, per_peer_state, chan);
5565                                                                 } else {
5566                                                                         // If we're running during init we cannot update a monitor directly -
5567                                                                         // they probably haven't actually been loaded yet. Instead, push the
5568                                                                         // monitor update as a background event.
5569                                                                         self.pending_background_events.lock().unwrap().push(
5570                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5571                                                                                         counterparty_node_id,
5572                                                                                         funding_txo: prev_hop.outpoint,
5573                                                                                         update: monitor_update.clone(),
5574                                                                                 });
5575                                                                 }
5576                                                         }
5577                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5578                                                                 let action = if let Some(action) = completion_action(None, true) {
5579                                                                         action
5580                                                                 } else {
5581                                                                         return Ok(());
5582                                                                 };
5583                                                                 mem::drop(peer_state_lock);
5584
5585                                                                 log_trace!(logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5586                                                                         chan_id, action);
5587                                                                 let (node_id, funding_outpoint, blocker) =
5588                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5589                                                                         downstream_counterparty_node_id: node_id,
5590                                                                         downstream_funding_outpoint: funding_outpoint,
5591                                                                         blocking_action: blocker,
5592                                                                 } = action {
5593                                                                         (node_id, funding_outpoint, blocker)
5594                                                                 } else {
5595                                                                         debug_assert!(false,
5596                                                                                 "Duplicate claims should always free another channel immediately");
5597                                                                         return Ok(());
5598                                                                 };
5599                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5600                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5601                                                                         if let Some(blockers) = peer_state
5602                                                                                 .actions_blocking_raa_monitor_updates
5603                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5604                                                                         {
5605                                                                                 let mut found_blocker = false;
5606                                                                                 blockers.retain(|iter| {
5607                                                                                         // Note that we could actually be blocked, in
5608                                                                                         // which case we need to only remove the one
5609                                                                                         // blocker which was added duplicatively.
5610                                                                                         let first_blocker = !found_blocker;
5611                                                                                         if *iter == blocker { found_blocker = true; }
5612                                                                                         *iter != blocker || !first_blocker
5613                                                                                 });
5614                                                                                 debug_assert!(found_blocker);
5615                                                                         }
5616                                                                 } else {
5617                                                                         debug_assert!(false);
5618                                                                 }
5619                                                         }
5620                                                 }
5621                                         }
5622                                         return Ok(());
5623                                 }
5624                         }
5625                 }
5626                 let preimage_update = ChannelMonitorUpdate {
5627                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5628                         counterparty_node_id: None,
5629                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5630                                 payment_preimage,
5631                         }],
5632                 };
5633
5634                 if !during_init {
5635                         // We update the ChannelMonitor on the backward link, after
5636                         // receiving an `update_fulfill_htlc` from the forward link.
5637                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5638                         if update_res != ChannelMonitorUpdateStatus::Completed {
5639                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5640                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5641                                 // channel, or we must have an ability to receive the same event and try
5642                                 // again on restart.
5643                                 log_error!(WithContext::from(&self.logger, None, Some(prev_hop.outpoint.to_channel_id())), "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5644                                         payment_preimage, update_res);
5645                         }
5646                 } else {
5647                         // If we're running during init we cannot update a monitor directly - they probably
5648                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5649                         // event.
5650                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5651                         // channel is already closed) we need to ultimately handle the monitor update
5652                         // completion action only after we've completed the monitor update. This is the only
5653                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5654                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5655                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5656                         // complete the monitor update completion action from `completion_action`.
5657                         self.pending_background_events.lock().unwrap().push(
5658                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5659                                         prev_hop.outpoint, preimage_update,
5660                                 )));
5661                 }
5662                 // Note that we do process the completion action here. This totally could be a
5663                 // duplicate claim, but we have no way of knowing without interrogating the
5664                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5665                 // generally always allowed to be duplicative (and it's specifically noted in
5666                 // `PaymentForwarded`).
5667                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5668                 Ok(())
5669         }
5670
5671         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5672                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5673         }
5674
5675         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5676                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5677                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5678         ) {
5679                 match source {
5680                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5681                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5682                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5683                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5684                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5685                                 }
5686                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5687                                         channel_funding_outpoint: next_channel_outpoint,
5688                                         counterparty_node_id: path.hops[0].pubkey,
5689                                 };
5690                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5691                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5692                                         &self.logger);
5693                         },
5694                         HTLCSource::PreviousHopData(hop_data) => {
5695                                 let prev_outpoint = hop_data.outpoint;
5696                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5697                                 #[cfg(debug_assertions)]
5698                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5699                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5700                                         |htlc_claim_value_msat, definitely_duplicate| {
5701                                                 let chan_to_release =
5702                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5703                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5704                                                         } else {
5705                                                                 // We can only get `None` here if we are processing a
5706                                                                 // `ChannelMonitor`-originated event, in which case we
5707                                                                 // don't care about ensuring we wake the downstream
5708                                                                 // channel's monitor updating - the channel is already
5709                                                                 // closed.
5710                                                                 None
5711                                                         };
5712
5713                                                 if definitely_duplicate && startup_replay {
5714                                                         // On startup we may get redundant claims which are related to
5715                                                         // monitor updates still in flight. In that case, we shouldn't
5716                                                         // immediately free, but instead let that monitor update complete
5717                                                         // in the background.
5718                                                         #[cfg(debug_assertions)] {
5719                                                                 let background_events = self.pending_background_events.lock().unwrap();
5720                                                                 // There should be a `BackgroundEvent` pending...
5721                                                                 assert!(background_events.iter().any(|ev| {
5722                                                                         match ev {
5723                                                                                 // to apply a monitor update that blocked the claiming channel,
5724                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5725                                                                                         funding_txo, update, ..
5726                                                                                 } => {
5727                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5728                                                                                                 assert!(update.updates.iter().any(|upd|
5729                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5730                                                                                                                 payment_preimage: update_preimage
5731                                                                                                         } = upd {
5732                                                                                                                 payment_preimage == *update_preimage
5733                                                                                                         } else { false }
5734                                                                                                 ), "{:?}", update);
5735                                                                                                 true
5736                                                                                         } else { false }
5737                                                                                 },
5738                                                                                 // or the channel we'd unblock is already closed,
5739                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5740                                                                                         (funding_txo, monitor_update)
5741                                                                                 ) => {
5742                                                                                         if *funding_txo == next_channel_outpoint {
5743                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5744                                                                                                 assert!(matches!(
5745                                                                                                         monitor_update.updates[0],
5746                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5747                                                                                                 ));
5748                                                                                                 true
5749                                                                                         } else { false }
5750                                                                                 },
5751                                                                                 // or the monitor update has completed and will unblock
5752                                                                                 // immediately once we get going.
5753                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5754                                                                                         channel_id, ..
5755                                                                                 } =>
5756                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5757                                                                         }
5758                                                                 }), "{:?}", *background_events);
5759                                                         }
5760                                                         None
5761                                                 } else if definitely_duplicate {
5762                                                         if let Some(other_chan) = chan_to_release {
5763                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5764                                                                         downstream_counterparty_node_id: other_chan.0,
5765                                                                         downstream_funding_outpoint: other_chan.1,
5766                                                                         blocking_action: other_chan.2,
5767                                                                 })
5768                                                         } else { None }
5769                                                 } else {
5770                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5771                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5772                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5773                                                                 } else { None }
5774                                                         } else { None };
5775                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5776                                                                 event: events::Event::PaymentForwarded {
5777                                                                         fee_earned_msat,
5778                                                                         claim_from_onchain_tx: from_onchain,
5779                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5780                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5781                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5782                                                                 },
5783                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5784                                                         })
5785                                                 }
5786                                         });
5787                                 if let Err((pk, err)) = res {
5788                                         let result: Result<(), _> = Err(err);
5789                                         let _ = handle_error!(self, result, pk);
5790                                 }
5791                         },
5792                 }
5793         }
5794
5795         /// Gets the node_id held by this ChannelManager
5796         pub fn get_our_node_id(&self) -> PublicKey {
5797                 self.our_network_pubkey.clone()
5798         }
5799
5800         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5801                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5802                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5803                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5804
5805                 for action in actions.into_iter() {
5806                         match action {
5807                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5808                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5809                                         if let Some(ClaimingPayment {
5810                                                 amount_msat,
5811                                                 payment_purpose: purpose,
5812                                                 receiver_node_id,
5813                                                 htlcs,
5814                                                 sender_intended_value: sender_intended_total_msat,
5815                                         }) = payment {
5816                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5817                                                         payment_hash,
5818                                                         purpose,
5819                                                         amount_msat,
5820                                                         receiver_node_id: Some(receiver_node_id),
5821                                                         htlcs,
5822                                                         sender_intended_total_msat,
5823                                                 }, None));
5824                                         }
5825                                 },
5826                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5827                                         event, downstream_counterparty_and_funding_outpoint
5828                                 } => {
5829                                         self.pending_events.lock().unwrap().push_back((event, None));
5830                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5831                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5832                                         }
5833                                 },
5834                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5835                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5836                                 } => {
5837                                         self.handle_monitor_update_release(
5838                                                 downstream_counterparty_node_id,
5839                                                 downstream_funding_outpoint,
5840                                                 Some(blocking_action),
5841                                         );
5842                                 },
5843                         }
5844                 }
5845         }
5846
5847         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5848         /// update completion.
5849         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5850                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5851                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5852                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5853                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5854         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5855                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5856                 log_trace!(logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5857                         &channel.context.channel_id(),
5858                         if raa.is_some() { "an" } else { "no" },
5859                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5860                         if funding_broadcastable.is_some() { "" } else { "not " },
5861                         if channel_ready.is_some() { "sending" } else { "without" },
5862                         if announcement_sigs.is_some() { "sending" } else { "without" });
5863
5864                 let mut htlc_forwards = None;
5865
5866                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5867                 if !pending_forwards.is_empty() {
5868                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5869                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5870                 }
5871
5872                 if let Some(msg) = channel_ready {
5873                         send_channel_ready!(self, pending_msg_events, channel, msg);
5874                 }
5875                 if let Some(msg) = announcement_sigs {
5876                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5877                                 node_id: counterparty_node_id,
5878                                 msg,
5879                         });
5880                 }
5881
5882                 macro_rules! handle_cs { () => {
5883                         if let Some(update) = commitment_update {
5884                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5885                                         node_id: counterparty_node_id,
5886                                         updates: update,
5887                                 });
5888                         }
5889                 } }
5890                 macro_rules! handle_raa { () => {
5891                         if let Some(revoke_and_ack) = raa {
5892                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5893                                         node_id: counterparty_node_id,
5894                                         msg: revoke_and_ack,
5895                                 });
5896                         }
5897                 } }
5898                 match order {
5899                         RAACommitmentOrder::CommitmentFirst => {
5900                                 handle_cs!();
5901                                 handle_raa!();
5902                         },
5903                         RAACommitmentOrder::RevokeAndACKFirst => {
5904                                 handle_raa!();
5905                                 handle_cs!();
5906                         },
5907                 }
5908
5909                 if let Some(tx) = funding_broadcastable {
5910                         log_info!(logger, "Broadcasting funding transaction with txid {}", tx.txid());
5911                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5912                 }
5913
5914                 {
5915                         let mut pending_events = self.pending_events.lock().unwrap();
5916                         emit_channel_pending_event!(pending_events, channel);
5917                         emit_channel_ready_event!(pending_events, channel);
5918                 }
5919
5920                 htlc_forwards
5921         }
5922
5923         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5924                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5925
5926                 let counterparty_node_id = match counterparty_node_id {
5927                         Some(cp_id) => cp_id.clone(),
5928                         None => {
5929                                 // TODO: Once we can rely on the counterparty_node_id from the
5930                                 // monitor event, this and the outpoint_to_peer map should be removed.
5931                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
5932                                 match outpoint_to_peer.get(&funding_txo) {
5933                                         Some(cp_id) => cp_id.clone(),
5934                                         None => return,
5935                                 }
5936                         }
5937                 };
5938                 let per_peer_state = self.per_peer_state.read().unwrap();
5939                 let mut peer_state_lock;
5940                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5941                 if peer_state_mutex_opt.is_none() { return }
5942                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5943                 let peer_state = &mut *peer_state_lock;
5944                 let channel =
5945                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5946                                 chan
5947                         } else {
5948                                 let update_actions = peer_state.monitor_update_blocked_actions
5949                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5950                                 mem::drop(peer_state_lock);
5951                                 mem::drop(per_peer_state);
5952                                 self.handle_monitor_update_completion_actions(update_actions);
5953                                 return;
5954                         };
5955                 let remaining_in_flight =
5956                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5957                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5958                                 pending.len()
5959                         } else { 0 };
5960                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5961                 log_trace!(logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5962                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5963                         remaining_in_flight);
5964                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5965                         return;
5966                 }
5967                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5968         }
5969
5970         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5971         ///
5972         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5973         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5974         /// the channel.
5975         ///
5976         /// The `user_channel_id` parameter will be provided back in
5977         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5978         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5979         ///
5980         /// Note that this method will return an error and reject the channel, if it requires support
5981         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5982         /// used to accept such channels.
5983         ///
5984         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5985         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5986         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5987                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5988         }
5989
5990         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5991         /// it as confirmed immediately.
5992         ///
5993         /// The `user_channel_id` parameter will be provided back in
5994         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5995         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5996         ///
5997         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5998         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5999         ///
6000         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
6001         /// transaction and blindly assumes that it will eventually confirm.
6002         ///
6003         /// If it does not confirm before we decide to close the channel, or if the funding transaction
6004         /// does not pay to the correct script the correct amount, *you will lose funds*.
6005         ///
6006         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
6007         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
6008         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
6009                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
6010         }
6011
6012         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
6013
6014                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(*temporary_channel_id));
6015                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6016
6017                 let peers_without_funded_channels =
6018                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
6019                 let per_peer_state = self.per_peer_state.read().unwrap();
6020                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6021                 .ok_or_else(|| {
6022                         let err_str = format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id);
6023                         log_error!(logger, "{}", err_str);
6024
6025                         APIError::ChannelUnavailable { err: err_str }
6026                 })?;
6027                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6028                 let peer_state = &mut *peer_state_lock;
6029                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
6030
6031                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
6032                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
6033                 // that we can delay allocating the SCID until after we're sure that the checks below will
6034                 // succeed.
6035                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
6036                         Some(unaccepted_channel) => {
6037                                 let best_block_height = self.best_block.read().unwrap().height();
6038                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6039                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
6040                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
6041                                         &self.logger, accept_0conf).map_err(|e| {
6042                                                 let err_str = e.to_string();
6043                                                 log_error!(logger, "{}", err_str);
6044
6045                                                 APIError::ChannelUnavailable { err: err_str }
6046                                         })
6047                                 }
6048                         _ => {
6049                                 let err_str = "No such channel awaiting to be accepted.".to_owned();
6050                                 log_error!(logger, "{}", err_str);
6051
6052                                 Err(APIError::APIMisuseError { err: err_str })
6053                         }
6054                 }?;
6055
6056                 if accept_0conf {
6057                         // This should have been correctly configured by the call to InboundV1Channel::new.
6058                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
6059                 } else if channel.context.get_channel_type().requires_zero_conf() {
6060                         let send_msg_err_event = events::MessageSendEvent::HandleError {
6061                                 node_id: channel.context.get_counterparty_node_id(),
6062                                 action: msgs::ErrorAction::SendErrorMessage{
6063                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
6064                                 }
6065                         };
6066                         peer_state.pending_msg_events.push(send_msg_err_event);
6067                         let err_str = "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned();
6068                         log_error!(logger, "{}", err_str);
6069
6070                         return Err(APIError::APIMisuseError { err: err_str });
6071                 } else {
6072                         // If this peer already has some channels, a new channel won't increase our number of peers
6073                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6074                         // channels per-peer we can accept channels from a peer with existing ones.
6075                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
6076                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
6077                                         node_id: channel.context.get_counterparty_node_id(),
6078                                         action: msgs::ErrorAction::SendErrorMessage{
6079                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
6080                                         }
6081                                 };
6082                                 peer_state.pending_msg_events.push(send_msg_err_event);
6083                                 let err_str = "Too many peers with unfunded channels, refusing to accept new ones".to_owned();
6084                                 log_error!(logger, "{}", err_str);
6085
6086                                 return Err(APIError::APIMisuseError { err: err_str });
6087                         }
6088                 }
6089
6090                 // Now that we know we have a channel, assign an outbound SCID alias.
6091                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6092                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6093
6094                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6095                         node_id: channel.context.get_counterparty_node_id(),
6096                         msg: channel.accept_inbound_channel(),
6097                 });
6098
6099                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
6100
6101                 Ok(())
6102         }
6103
6104         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
6105         /// or 0-conf channels.
6106         ///
6107         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6108         /// non-0-conf channels we have with the peer.
6109         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6110         where Filter: Fn(&PeerState<SP>) -> bool {
6111                 let mut peers_without_funded_channels = 0;
6112                 let best_block_height = self.best_block.read().unwrap().height();
6113                 {
6114                         let peer_state_lock = self.per_peer_state.read().unwrap();
6115                         for (_, peer_mtx) in peer_state_lock.iter() {
6116                                 let peer = peer_mtx.lock().unwrap();
6117                                 if !maybe_count_peer(&*peer) { continue; }
6118                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6119                                 if num_unfunded_channels == peer.total_channel_count() {
6120                                         peers_without_funded_channels += 1;
6121                                 }
6122                         }
6123                 }
6124                 return peers_without_funded_channels;
6125         }
6126
6127         fn unfunded_channel_count(
6128                 peer: &PeerState<SP>, best_block_height: u32
6129         ) -> usize {
6130                 let mut num_unfunded_channels = 0;
6131                 for (_, phase) in peer.channel_by_id.iter() {
6132                         match phase {
6133                                 ChannelPhase::Funded(chan) => {
6134                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6135                                         // which have not yet had any confirmations on-chain.
6136                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6137                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6138                                         {
6139                                                 num_unfunded_channels += 1;
6140                                         }
6141                                 },
6142                                 ChannelPhase::UnfundedInboundV1(chan) => {
6143                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6144                                                 num_unfunded_channels += 1;
6145                                         }
6146                                 },
6147                                 ChannelPhase::UnfundedOutboundV1(_) => {
6148                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6149                                         continue;
6150                                 }
6151                         }
6152                 }
6153                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6154         }
6155
6156         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6157                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6158                 // likely to be lost on restart!
6159                 if msg.chain_hash != self.chain_hash {
6160                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
6161                 }
6162
6163                 if !self.default_configuration.accept_inbound_channels {
6164                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6165                 }
6166
6167                 // Get the number of peers with channels, but without funded ones. We don't care too much
6168                 // about peers that never open a channel, so we filter by peers that have at least one
6169                 // channel, and then limit the number of those with unfunded channels.
6170                 let channeled_peers_without_funding =
6171                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6172
6173                 let per_peer_state = self.per_peer_state.read().unwrap();
6174                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6175                     .ok_or_else(|| {
6176                                 debug_assert!(false);
6177                                 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())
6178                         })?;
6179                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6180                 let peer_state = &mut *peer_state_lock;
6181
6182                 // If this peer already has some channels, a new channel won't increase our number of peers
6183                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6184                 // channels per-peer we can accept channels from a peer with existing ones.
6185                 if peer_state.total_channel_count() == 0 &&
6186                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6187                         !self.default_configuration.manually_accept_inbound_channels
6188                 {
6189                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6190                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6191                                 msg.temporary_channel_id.clone()));
6192                 }
6193
6194                 let best_block_height = self.best_block.read().unwrap().height();
6195                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6196                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6197                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6198                                 msg.temporary_channel_id.clone()));
6199                 }
6200
6201                 let channel_id = msg.temporary_channel_id;
6202                 let channel_exists = peer_state.has_channel(&channel_id);
6203                 if channel_exists {
6204                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
6205                 }
6206
6207                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6208                 if self.default_configuration.manually_accept_inbound_channels {
6209                         let channel_type = channel::channel_type_from_open_channel(
6210                                         &msg, &peer_state.latest_features, &self.channel_type_features()
6211                                 ).map_err(|e|
6212                                         MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id)
6213                                 )?;
6214                         let mut pending_events = self.pending_events.lock().unwrap();
6215                         pending_events.push_back((events::Event::OpenChannelRequest {
6216                                 temporary_channel_id: msg.temporary_channel_id.clone(),
6217                                 counterparty_node_id: counterparty_node_id.clone(),
6218                                 funding_satoshis: msg.funding_satoshis,
6219                                 push_msat: msg.push_msat,
6220                                 channel_type,
6221                         }, None));
6222                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6223                                 open_channel_msg: msg.clone(),
6224                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6225                         });
6226                         return Ok(());
6227                 }
6228
6229                 // Otherwise create the channel right now.
6230                 let mut random_bytes = [0u8; 16];
6231                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6232                 let user_channel_id = u128::from_be_bytes(random_bytes);
6233                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6234                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6235                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6236                 {
6237                         Err(e) => {
6238                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
6239                         },
6240                         Ok(res) => res
6241                 };
6242
6243                 let channel_type = channel.context.get_channel_type();
6244                 if channel_type.requires_zero_conf() {
6245                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6246                 }
6247                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6248                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
6249                 }
6250
6251                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6252                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6253
6254                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6255                         node_id: counterparty_node_id.clone(),
6256                         msg: channel.accept_inbound_channel(),
6257                 });
6258                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6259                 Ok(())
6260         }
6261
6262         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6263                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6264                 // likely to be lost on restart!
6265                 let (value, output_script, user_id) = {
6266                         let per_peer_state = self.per_peer_state.read().unwrap();
6267                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6268                                 .ok_or_else(|| {
6269                                         debug_assert!(false);
6270                                         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)
6271                                 })?;
6272                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6273                         let peer_state = &mut *peer_state_lock;
6274                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6275                                 hash_map::Entry::Occupied(mut phase) => {
6276                                         match phase.get_mut() {
6277                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6278                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6279                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6280                                                 },
6281                                                 _ => {
6282                                                         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));
6283                                                 }
6284                                         }
6285                                 },
6286                                 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))
6287                         }
6288                 };
6289                 let mut pending_events = self.pending_events.lock().unwrap();
6290                 pending_events.push_back((events::Event::FundingGenerationReady {
6291                         temporary_channel_id: msg.temporary_channel_id,
6292                         counterparty_node_id: *counterparty_node_id,
6293                         channel_value_satoshis: value,
6294                         output_script,
6295                         user_channel_id: user_id,
6296                 }, None));
6297                 Ok(())
6298         }
6299
6300         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6301                 let best_block = *self.best_block.read().unwrap();
6302
6303                 let per_peer_state = self.per_peer_state.read().unwrap();
6304                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6305                         .ok_or_else(|| {
6306                                 debug_assert!(false);
6307                                 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)
6308                         })?;
6309
6310                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6311                 let peer_state = &mut *peer_state_lock;
6312                 let (mut chan, funding_msg_opt, monitor) =
6313                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6314                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6315                                         let logger = WithChannelContext::from(&self.logger, &inbound_chan.context);
6316                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &&logger) {
6317                                                 Ok(res) => res,
6318                                                 Err((inbound_chan, err)) => {
6319                                                         // We've already removed this inbound channel from the map in `PeerState`
6320                                                         // above so at this point we just need to clean up any lingering entries
6321                                                         // concerning this channel as it is safe to do so.
6322                                                         debug_assert!(matches!(err, ChannelError::Close(_)));
6323                                                         // Really we should be returning the channel_id the peer expects based
6324                                                         // on their funding info here, but they're horribly confused anyway, so
6325                                                         // there's not a lot we can do to save them.
6326                                                         return Err(convert_chan_phase_err!(self, err, &mut ChannelPhase::UnfundedInboundV1(inbound_chan), &msg.temporary_channel_id).1);
6327                                                 },
6328                                         }
6329                                 },
6330                                 Some(mut phase) => {
6331                                         let err_msg = format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id);
6332                                         let err = ChannelError::Close(err_msg);
6333                                         return Err(convert_chan_phase_err!(self, err, &mut phase, &msg.temporary_channel_id).1);
6334                                 },
6335                                 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))
6336                         };
6337
6338                 let funded_channel_id = chan.context.channel_id();
6339
6340                 macro_rules! fail_chan { ($err: expr) => { {
6341                         // Note that at this point we've filled in the funding outpoint on our
6342                         // channel, but its actually in conflict with another channel. Thus, if
6343                         // we call `convert_chan_phase_err` immediately (thus calling
6344                         // `update_maps_on_chan_removal`), we'll remove the existing channel
6345                         // from `outpoint_to_peer`. Thus, we must first unset the funding outpoint
6346                         // on the channel.
6347                         let err = ChannelError::Close($err.to_owned());
6348                         chan.unset_funding_info(msg.temporary_channel_id);
6349                         return Err(convert_chan_phase_err!(self, err, chan, &funded_channel_id, UNFUNDED_CHANNEL).1);
6350                 } } }
6351
6352                 match peer_state.channel_by_id.entry(funded_channel_id) {
6353                         hash_map::Entry::Occupied(_) => {
6354                                 fail_chan!("Already had channel with the new channel_id");
6355                         },
6356                         hash_map::Entry::Vacant(e) => {
6357                                 let mut outpoint_to_peer_lock = self.outpoint_to_peer.lock().unwrap();
6358                                 match outpoint_to_peer_lock.entry(monitor.get_funding_txo().0) {
6359                                         hash_map::Entry::Occupied(_) => {
6360                                                 fail_chan!("The funding_created message had the same funding_txid as an existing channel - funding is not possible");
6361                                         },
6362                                         hash_map::Entry::Vacant(i_e) => {
6363                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6364                                                 if let Ok(persist_state) = monitor_res {
6365                                                         i_e.insert(chan.context.get_counterparty_node_id());
6366                                                         mem::drop(outpoint_to_peer_lock);
6367
6368                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6369                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6370                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6371                                                         // until we have persisted our monitor.
6372                                                         if let Some(msg) = funding_msg_opt {
6373                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6374                                                                         node_id: counterparty_node_id.clone(),
6375                                                                         msg,
6376                                                                 });
6377                                                         }
6378
6379                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6380                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6381                                                                         per_peer_state, chan, INITIAL_MONITOR);
6382                                                         } else {
6383                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6384                                                         }
6385                                                         Ok(())
6386                                                 } else {
6387                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6388                                                         log_error!(logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6389                                                         fail_chan!("Duplicate funding outpoint");
6390                                                 }
6391                                         }
6392                                 }
6393                         }
6394                 }
6395         }
6396
6397         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6398                 let best_block = *self.best_block.read().unwrap();
6399                 let per_peer_state = self.per_peer_state.read().unwrap();
6400                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6401                         .ok_or_else(|| {
6402                                 debug_assert!(false);
6403                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6404                         })?;
6405
6406                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6407                 let peer_state = &mut *peer_state_lock;
6408                 match peer_state.channel_by_id.entry(msg.channel_id) {
6409                         hash_map::Entry::Occupied(chan_phase_entry) => {
6410                                 if matches!(chan_phase_entry.get(), ChannelPhase::UnfundedOutboundV1(_)) {
6411                                         let chan = if let ChannelPhase::UnfundedOutboundV1(chan) = chan_phase_entry.remove() { chan } else { unreachable!() };
6412                                         let logger = WithContext::from(
6413                                                 &self.logger,
6414                                                 Some(chan.context.get_counterparty_node_id()),
6415                                                 Some(chan.context.channel_id())
6416                                         );
6417                                         let res =
6418                                                 chan.funding_signed(&msg, best_block, &self.signer_provider, &&logger);
6419                                         match res {
6420                                                 Ok((mut chan, monitor)) => {
6421                                                         if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6422                                                                 // We really should be able to insert here without doing a second
6423                                                                 // lookup, but sadly rust stdlib doesn't currently allow keeping
6424                                                                 // the original Entry around with the value removed.
6425                                                                 let mut chan = peer_state.channel_by_id.entry(msg.channel_id).or_insert(ChannelPhase::Funded(chan));
6426                                                                 if let ChannelPhase::Funded(ref mut chan) = &mut chan {
6427                                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6428                                                                 } else { unreachable!(); }
6429                                                                 Ok(())
6430                                                         } else {
6431                                                                 let e = ChannelError::Close("Channel funding outpoint was a duplicate".to_owned());
6432                                                                 // We weren't able to watch the channel to begin with, so no
6433                                                                 // updates should be made on it. Previously, full_stack_target
6434                                                                 // found an (unreachable) panic when the monitor update contained
6435                                                                 // within `shutdown_finish` was applied.
6436                                                                 chan.unset_funding_info(msg.channel_id);
6437                                                                 return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::Funded(chan), &msg.channel_id).1);
6438                                                         }
6439                                                 },
6440                                                 Err((chan, e)) => {
6441                                                         debug_assert!(matches!(e, ChannelError::Close(_)),
6442                                                                 "We don't have a channel anymore, so the error better have expected close");
6443                                                         // We've already removed this outbound channel from the map in
6444                                                         // `PeerState` above so at this point we just need to clean up any
6445                                                         // lingering entries concerning this channel as it is safe to do so.
6446                                                         return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::UnfundedOutboundV1(chan), &msg.channel_id).1);
6447                                                 }
6448                                         }
6449                                 } else {
6450                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6451                                 }
6452                         },
6453                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6454                 }
6455         }
6456
6457         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6458                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6459                 // closing a channel), so any changes are likely to be lost on restart!
6460                 let per_peer_state = self.per_peer_state.read().unwrap();
6461                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6462                         .ok_or_else(|| {
6463                                 debug_assert!(false);
6464                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6465                         })?;
6466                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6467                 let peer_state = &mut *peer_state_lock;
6468                 match peer_state.channel_by_id.entry(msg.channel_id) {
6469                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6470                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6471                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6472                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6473                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &&logger), chan_phase_entry);
6474                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6475                                                 log_trace!(logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6476                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6477                                                         node_id: counterparty_node_id.clone(),
6478                                                         msg: announcement_sigs,
6479                                                 });
6480                                         } else if chan.context.is_usable() {
6481                                                 // If we're sending an announcement_signatures, we'll send the (public)
6482                                                 // channel_update after sending a channel_announcement when we receive our
6483                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6484                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6485                                                 // announcement_signatures.
6486                                                 log_trace!(logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6487                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6488                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6489                                                                 node_id: counterparty_node_id.clone(),
6490                                                                 msg,
6491                                                         });
6492                                                 }
6493                                         }
6494
6495                                         {
6496                                                 let mut pending_events = self.pending_events.lock().unwrap();
6497                                                 emit_channel_ready_event!(pending_events, chan);
6498                                         }
6499
6500                                         Ok(())
6501                                 } else {
6502                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6503                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6504                                 }
6505                         },
6506                         hash_map::Entry::Vacant(_) => {
6507                                 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))
6508                         }
6509                 }
6510         }
6511
6512         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6513                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6514                 let mut finish_shutdown = None;
6515                 {
6516                         let per_peer_state = self.per_peer_state.read().unwrap();
6517                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6518                                 .ok_or_else(|| {
6519                                         debug_assert!(false);
6520                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6521                                 })?;
6522                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6523                         let peer_state = &mut *peer_state_lock;
6524                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6525                                 let phase = chan_phase_entry.get_mut();
6526                                 match phase {
6527                                         ChannelPhase::Funded(chan) => {
6528                                                 if !chan.received_shutdown() {
6529                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6530                                                         log_info!(logger, "Received a shutdown message from our counterparty for channel {}{}.",
6531                                                                 msg.channel_id,
6532                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6533                                                 }
6534
6535                                                 let funding_txo_opt = chan.context.get_funding_txo();
6536                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6537                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6538                                                 dropped_htlcs = htlcs;
6539
6540                                                 if let Some(msg) = shutdown {
6541                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6542                                                         // here as we don't need the monitor update to complete until we send a
6543                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6544                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6545                                                                 node_id: *counterparty_node_id,
6546                                                                 msg,
6547                                                         });
6548                                                 }
6549                                                 // Update the monitor with the shutdown script if necessary.
6550                                                 if let Some(monitor_update) = monitor_update_opt {
6551                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6552                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6553                                                 }
6554                                         },
6555                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6556                                                 let context = phase.context_mut();
6557                                                 let logger = WithChannelContext::from(&self.logger, context);
6558                                                 log_error!(logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6559                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6560                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false, ClosureReason::CounterpartyCoopClosedUnfundedChannel));
6561                                         },
6562                                 }
6563                         } else {
6564                                 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))
6565                         }
6566                 }
6567                 for htlc_source in dropped_htlcs.drain(..) {
6568                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6569                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6570                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6571                 }
6572                 if let Some(shutdown_res) = finish_shutdown {
6573                         self.finish_close_channel(shutdown_res);
6574                 }
6575
6576                 Ok(())
6577         }
6578
6579         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6580                 let per_peer_state = self.per_peer_state.read().unwrap();
6581                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6582                         .ok_or_else(|| {
6583                                 debug_assert!(false);
6584                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6585                         })?;
6586                 let (tx, chan_option, shutdown_result) = {
6587                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6588                         let peer_state = &mut *peer_state_lock;
6589                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6590                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6591                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6592                                                 let (closing_signed, tx, shutdown_result) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6593                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
6594                                                 if let Some(msg) = closing_signed {
6595                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6596                                                                 node_id: counterparty_node_id.clone(),
6597                                                                 msg,
6598                                                         });
6599                                                 }
6600                                                 if tx.is_some() {
6601                                                         // We're done with this channel, we've got a signed closing transaction and
6602                                                         // will send the closing_signed back to the remote peer upon return. This
6603                                                         // also implies there are no pending HTLCs left on the channel, so we can
6604                                                         // fully delete it from tracking (the channel monitor is still around to
6605                                                         // watch for old state broadcasts)!
6606                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)), shutdown_result)
6607                                                 } else { (tx, None, shutdown_result) }
6608                                         } else {
6609                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6610                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6611                                         }
6612                                 },
6613                                 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))
6614                         }
6615                 };
6616                 if let Some(broadcast_tx) = tx {
6617                         let channel_id = chan_option.as_ref().map(|channel| channel.context().channel_id());
6618                         log_info!(WithContext::from(&self.logger, Some(*counterparty_node_id), channel_id), "Broadcasting {}", log_tx!(broadcast_tx));
6619                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6620                 }
6621                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6622                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6623                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6624                                 let peer_state = &mut *peer_state_lock;
6625                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6626                                         msg: update
6627                                 });
6628                         }
6629                 }
6630                 mem::drop(per_peer_state);
6631                 if let Some(shutdown_result) = shutdown_result {
6632                         self.finish_close_channel(shutdown_result);
6633                 }
6634                 Ok(())
6635         }
6636
6637         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6638                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6639                 //determine the state of the payment based on our response/if we forward anything/the time
6640                 //we take to respond. We should take care to avoid allowing such an attack.
6641                 //
6642                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6643                 //us repeatedly garbled in different ways, and compare our error messages, which are
6644                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6645                 //but we should prevent it anyway.
6646
6647                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6648                 // closing a channel), so any changes are likely to be lost on restart!
6649
6650                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg, counterparty_node_id);
6651                 let per_peer_state = self.per_peer_state.read().unwrap();
6652                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6653                         .ok_or_else(|| {
6654                                 debug_assert!(false);
6655                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6656                         })?;
6657                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6658                 let peer_state = &mut *peer_state_lock;
6659                 match peer_state.channel_by_id.entry(msg.channel_id) {
6660                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6661                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6662                                         let pending_forward_info = match decoded_hop_res {
6663                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6664                                                         self.construct_pending_htlc_status(
6665                                                                 msg, counterparty_node_id, shared_secret, next_hop,
6666                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt,
6667                                                         ),
6668                                                 Err(e) => PendingHTLCStatus::Fail(e)
6669                                         };
6670                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6671                                                 if msg.blinding_point.is_some() {
6672                                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
6673                                                                         msgs::UpdateFailMalformedHTLC {
6674                                                                                 channel_id: msg.channel_id,
6675                                                                                 htlc_id: msg.htlc_id,
6676                                                                                 sha256_of_onion: [0; 32],
6677                                                                                 failure_code: INVALID_ONION_BLINDING,
6678                                                                         }
6679                                                         ))
6680                                                 }
6681                                                 // If the update_add is completely bogus, the call will Err and we will close,
6682                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6683                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6684                                                 match pending_forward_info {
6685                                                         PendingHTLCStatus::Forward(PendingHTLCInfo {
6686                                                                 ref incoming_shared_secret, ref routing, ..
6687                                                         }) => {
6688                                                                 let reason = if routing.blinded_failure().is_some() {
6689                                                                         HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32])
6690                                                                 } else if (error_code & 0x1000) != 0 {
6691                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6692                                                                         HTLCFailReason::reason(real_code, error_data)
6693                                                                 } else {
6694                                                                         HTLCFailReason::from_failure_code(error_code)
6695                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6696                                                                 let msg = msgs::UpdateFailHTLC {
6697                                                                         channel_id: msg.channel_id,
6698                                                                         htlc_id: msg.htlc_id,
6699                                                                         reason
6700                                                                 };
6701                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6702                                                         },
6703                                                         _ => pending_forward_info
6704                                                 }
6705                                         };
6706                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6707                                         try_chan_phase_entry!(self, chan.update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &&logger), chan_phase_entry);
6708                                 } else {
6709                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6710                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6711                                 }
6712                         },
6713                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6714                 }
6715                 Ok(())
6716         }
6717
6718         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6719                 let funding_txo;
6720                 let (htlc_source, forwarded_htlc_value) = {
6721                         let per_peer_state = self.per_peer_state.read().unwrap();
6722                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6723                                 .ok_or_else(|| {
6724                                         debug_assert!(false);
6725                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6726                                 })?;
6727                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6728                         let peer_state = &mut *peer_state_lock;
6729                         match peer_state.channel_by_id.entry(msg.channel_id) {
6730                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6731                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6732                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6733                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6734                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6735                                                         log_trace!(logger,
6736                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6737                                                                 msg.channel_id);
6738                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6739                                                                 .or_insert_with(Vec::new)
6740                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6741                                                 }
6742                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6743                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6744                                                 // We do this instead in the `claim_funds_internal` by attaching a
6745                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6746                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6747                                                 // process the RAA as messages are processed from single peers serially.
6748                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6749                                                 res
6750                                         } else {
6751                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6752                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6753                                         }
6754                                 },
6755                                 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))
6756                         }
6757                 };
6758                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6759                 Ok(())
6760         }
6761
6762         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6763                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6764                 // closing a channel), so any changes are likely to be lost on restart!
6765                 let per_peer_state = self.per_peer_state.read().unwrap();
6766                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6767                         .ok_or_else(|| {
6768                                 debug_assert!(false);
6769                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6770                         })?;
6771                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6772                 let peer_state = &mut *peer_state_lock;
6773                 match peer_state.channel_by_id.entry(msg.channel_id) {
6774                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6775                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6776                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6777                                 } else {
6778                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6779                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6780                                 }
6781                         },
6782                         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))
6783                 }
6784                 Ok(())
6785         }
6786
6787         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6788                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6789                 // closing a channel), so any changes are likely to be lost on restart!
6790                 let per_peer_state = self.per_peer_state.read().unwrap();
6791                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6792                         .ok_or_else(|| {
6793                                 debug_assert!(false);
6794                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6795                         })?;
6796                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6797                 let peer_state = &mut *peer_state_lock;
6798                 match peer_state.channel_by_id.entry(msg.channel_id) {
6799                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6800                                 if (msg.failure_code & 0x8000) == 0 {
6801                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6802                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6803                                 }
6804                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6805                                         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);
6806                                 } else {
6807                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6808                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6809                                 }
6810                                 Ok(())
6811                         },
6812                         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))
6813                 }
6814         }
6815
6816         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6817                 let per_peer_state = self.per_peer_state.read().unwrap();
6818                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6819                         .ok_or_else(|| {
6820                                 debug_assert!(false);
6821                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6822                         })?;
6823                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6824                 let peer_state = &mut *peer_state_lock;
6825                 match peer_state.channel_by_id.entry(msg.channel_id) {
6826                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6827                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6828                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6829                                         let funding_txo = chan.context.get_funding_txo();
6830                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &&logger), chan_phase_entry);
6831                                         if let Some(monitor_update) = monitor_update_opt {
6832                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6833                                                         peer_state, per_peer_state, chan);
6834                                         }
6835                                         Ok(())
6836                                 } else {
6837                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6838                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6839                                 }
6840                         },
6841                         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))
6842                 }
6843         }
6844
6845         #[inline]
6846         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6847                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6848                         let mut push_forward_event = false;
6849                         let mut new_intercept_events = VecDeque::new();
6850                         let mut failed_intercept_forwards = Vec::new();
6851                         if !pending_forwards.is_empty() {
6852                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6853                                         let scid = match forward_info.routing {
6854                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6855                                                 PendingHTLCRouting::Receive { .. } => 0,
6856                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6857                                         };
6858                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6859                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6860
6861                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6862                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6863                                         match forward_htlcs.entry(scid) {
6864                                                 hash_map::Entry::Occupied(mut entry) => {
6865                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6866                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6867                                                 },
6868                                                 hash_map::Entry::Vacant(entry) => {
6869                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6870                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6871                                                         {
6872                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).to_byte_array());
6873                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6874                                                                 match pending_intercepts.entry(intercept_id) {
6875                                                                         hash_map::Entry::Vacant(entry) => {
6876                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6877                                                                                         requested_next_hop_scid: scid,
6878                                                                                         payment_hash: forward_info.payment_hash,
6879                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6880                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6881                                                                                         intercept_id
6882                                                                                 }, None));
6883                                                                                 entry.insert(PendingAddHTLCInfo {
6884                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6885                                                                         },
6886                                                                         hash_map::Entry::Occupied(_) => {
6887                                                                                 let logger = WithContext::from(&self.logger, None, Some(prev_funding_outpoint.to_channel_id()));
6888                                                                                 log_info!(logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6889                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6890                                                                                         short_channel_id: prev_short_channel_id,
6891                                                                                         user_channel_id: Some(prev_user_channel_id),
6892                                                                                         outpoint: prev_funding_outpoint,
6893                                                                                         htlc_id: prev_htlc_id,
6894                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6895                                                                                         phantom_shared_secret: None,
6896                                                                                         blinded_failure: forward_info.routing.blinded_failure(),
6897                                                                                 });
6898
6899                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6900                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6901                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6902                                                                                 ));
6903                                                                         }
6904                                                                 }
6905                                                         } else {
6906                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6907                                                                 // payments are being processed.
6908                                                                 if forward_htlcs_empty {
6909                                                                         push_forward_event = true;
6910                                                                 }
6911                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6912                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6913                                                         }
6914                                                 }
6915                                         }
6916                                 }
6917                         }
6918
6919                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6920                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6921                         }
6922
6923                         if !new_intercept_events.is_empty() {
6924                                 let mut events = self.pending_events.lock().unwrap();
6925                                 events.append(&mut new_intercept_events);
6926                         }
6927                         if push_forward_event { self.push_pending_forwards_ev() }
6928                 }
6929         }
6930
6931         fn push_pending_forwards_ev(&self) {
6932                 let mut pending_events = self.pending_events.lock().unwrap();
6933                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6934                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6935                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6936                 ).count();
6937                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6938                 // events is done in batches and they are not removed until we're done processing each
6939                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6940                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6941                 // payments will need an additional forwarding event before being claimed to make them look
6942                 // real by taking more time.
6943                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6944                         pending_events.push_back((Event::PendingHTLCsForwardable {
6945                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6946                         }, None));
6947                 }
6948         }
6949
6950         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6951         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6952         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6953         /// the [`ChannelMonitorUpdate`] in question.
6954         fn raa_monitor_updates_held(&self,
6955                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6956                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6957         ) -> bool {
6958                 actions_blocking_raa_monitor_updates
6959                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6960                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6961                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6962                                 channel_funding_outpoint,
6963                                 counterparty_node_id,
6964                         })
6965                 })
6966         }
6967
6968         #[cfg(any(test, feature = "_test_utils"))]
6969         pub(crate) fn test_raa_monitor_updates_held(&self,
6970                 counterparty_node_id: PublicKey, channel_id: ChannelId
6971         ) -> bool {
6972                 let per_peer_state = self.per_peer_state.read().unwrap();
6973                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6974                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6975                         let peer_state = &mut *peer_state_lck;
6976
6977                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6978                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6979                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6980                         }
6981                 }
6982                 false
6983         }
6984
6985         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6986                 let htlcs_to_fail = {
6987                         let per_peer_state = self.per_peer_state.read().unwrap();
6988                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6989                                 .ok_or_else(|| {
6990                                         debug_assert!(false);
6991                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6992                                 }).map(|mtx| mtx.lock().unwrap())?;
6993                         let peer_state = &mut *peer_state_lock;
6994                         match peer_state.channel_by_id.entry(msg.channel_id) {
6995                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6996                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6997                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
6998                                                 let funding_txo_opt = chan.context.get_funding_txo();
6999                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
7000                                                         self.raa_monitor_updates_held(
7001                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
7002                                                                 *counterparty_node_id)
7003                                                 } else { false };
7004                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
7005                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &&logger, mon_update_blocked), chan_phase_entry);
7006                                                 if let Some(monitor_update) = monitor_update_opt {
7007                                                         let funding_txo = funding_txo_opt
7008                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
7009                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
7010                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7011                                                 }
7012                                                 htlcs_to_fail
7013                                         } else {
7014                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7015                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
7016                                         }
7017                                 },
7018                                 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))
7019                         }
7020                 };
7021                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
7022                 Ok(())
7023         }
7024
7025         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
7026                 let per_peer_state = self.per_peer_state.read().unwrap();
7027                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7028                         .ok_or_else(|| {
7029                                 debug_assert!(false);
7030                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7031                         })?;
7032                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7033                 let peer_state = &mut *peer_state_lock;
7034                 match peer_state.channel_by_id.entry(msg.channel_id) {
7035                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7036                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7037                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7038                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &&logger), chan_phase_entry);
7039                                 } else {
7040                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7041                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
7042                                 }
7043                         },
7044                         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))
7045                 }
7046                 Ok(())
7047         }
7048
7049         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
7050                 let per_peer_state = self.per_peer_state.read().unwrap();
7051                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7052                         .ok_or_else(|| {
7053                                 debug_assert!(false);
7054                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7055                         })?;
7056                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7057                 let peer_state = &mut *peer_state_lock;
7058                 match peer_state.channel_by_id.entry(msg.channel_id) {
7059                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7060                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7061                                         if !chan.context.is_usable() {
7062                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
7063                                         }
7064
7065                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7066                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
7067                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
7068                                                         msg, &self.default_configuration
7069                                                 ), chan_phase_entry),
7070                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7071                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7072                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
7073                                         });
7074                                 } else {
7075                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7076                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
7077                                 }
7078                         },
7079                         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))
7080                 }
7081                 Ok(())
7082         }
7083
7084         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
7085         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
7086                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
7087                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
7088                         None => {
7089                                 // It's not a local channel
7090                                 return Ok(NotifyOption::SkipPersistNoEvents)
7091                         }
7092                 };
7093                 let per_peer_state = self.per_peer_state.read().unwrap();
7094                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
7095                 if peer_state_mutex_opt.is_none() {
7096                         return Ok(NotifyOption::SkipPersistNoEvents)
7097                 }
7098                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7099                 let peer_state = &mut *peer_state_lock;
7100                 match peer_state.channel_by_id.entry(chan_id) {
7101                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7102                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7103                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
7104                                                 if chan.context.should_announce() {
7105                                                         // If the announcement is about a channel of ours which is public, some
7106                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
7107                                                         // a scary-looking error message and return Ok instead.
7108                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7109                                                 }
7110                                                 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));
7111                                         }
7112                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
7113                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
7114                                         if were_node_one == msg_from_node_one {
7115                                                 return Ok(NotifyOption::SkipPersistNoEvents);
7116                                         } else {
7117                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
7118                                                 log_debug!(logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
7119                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
7120                                                 // If nothing changed after applying their update, we don't need to bother
7121                                                 // persisting.
7122                                                 if !did_change {
7123                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7124                                                 }
7125                                         }
7126                                 } else {
7127                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7128                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
7129                                 }
7130                         },
7131                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
7132                 }
7133                 Ok(NotifyOption::DoPersist)
7134         }
7135
7136         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
7137                 let htlc_forwards;
7138                 let need_lnd_workaround = {
7139                         let per_peer_state = self.per_peer_state.read().unwrap();
7140
7141                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7142                                 .ok_or_else(|| {
7143                                         debug_assert!(false);
7144                                         MsgHandleErrInternal::send_err_msg_no_close(
7145                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
7146                                                 msg.channel_id
7147                                         )
7148                                 })?;
7149                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
7150                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7151                         let peer_state = &mut *peer_state_lock;
7152                         match peer_state.channel_by_id.entry(msg.channel_id) {
7153                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
7154                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7155                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
7156                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
7157                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
7158                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
7159                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
7160                                                         msg, &&logger, &self.node_signer, self.chain_hash,
7161                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
7162                                                 let mut channel_update = None;
7163                                                 if let Some(msg) = responses.shutdown_msg {
7164                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
7165                                                                 node_id: counterparty_node_id.clone(),
7166                                                                 msg,
7167                                                         });
7168                                                 } else if chan.context.is_usable() {
7169                                                         // If the channel is in a usable state (ie the channel is not being shut
7170                                                         // down), send a unicast channel_update to our counterparty to make sure
7171                                                         // they have the latest channel parameters.
7172                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
7173                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
7174                                                                         node_id: chan.context.get_counterparty_node_id(),
7175                                                                         msg,
7176                                                                 });
7177                                                         }
7178                                                 }
7179                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7180                                                 htlc_forwards = self.handle_channel_resumption(
7181                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7182                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7183                                                 if let Some(upd) = channel_update {
7184                                                         peer_state.pending_msg_events.push(upd);
7185                                                 }
7186                                                 need_lnd_workaround
7187                                         } else {
7188                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7189                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7190                                         }
7191                                 },
7192                                 hash_map::Entry::Vacant(_) => {
7193                                         log_debug!(logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7194                                                 msg.channel_id);
7195                                         // Unfortunately, lnd doesn't force close on errors
7196                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7197                                         // One of the few ways to get an lnd counterparty to force close is by
7198                                         // replicating what they do when restoring static channel backups (SCBs). They
7199                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7200                                         // invalid `your_last_per_commitment_secret`.
7201                                         //
7202                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7203                                         // can assume it's likely the channel closed from our point of view, but it
7204                                         // remains open on the counterparty's side. By sending this bogus
7205                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7206                                         // force close broadcasting their latest state. If the closing transaction from
7207                                         // our point of view remains unconfirmed, it'll enter a race with the
7208                                         // counterparty's to-be-broadcast latest commitment transaction.
7209                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7210                                                 node_id: *counterparty_node_id,
7211                                                 msg: msgs::ChannelReestablish {
7212                                                         channel_id: msg.channel_id,
7213                                                         next_local_commitment_number: 0,
7214                                                         next_remote_commitment_number: 0,
7215                                                         your_last_per_commitment_secret: [1u8; 32],
7216                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7217                                                         next_funding_txid: None,
7218                                                 },
7219                                         });
7220                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7221                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7222                                                         counterparty_node_id), msg.channel_id)
7223                                         )
7224                                 }
7225                         }
7226                 };
7227
7228                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7229                 if let Some(forwards) = htlc_forwards {
7230                         self.forward_htlcs(&mut [forwards][..]);
7231                         persist = NotifyOption::DoPersist;
7232                 }
7233
7234                 if let Some(channel_ready_msg) = need_lnd_workaround {
7235                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7236                 }
7237                 Ok(persist)
7238         }
7239
7240         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7241         fn process_pending_monitor_events(&self) -> bool {
7242                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7243
7244                 let mut failed_channels = Vec::new();
7245                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7246                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7247                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7248                         for monitor_event in monitor_events.drain(..) {
7249                                 match monitor_event {
7250                                         MonitorEvent::HTLCEvent(htlc_update) => {
7251                                                 let logger = WithContext::from(&self.logger, counterparty_node_id, Some(funding_outpoint.to_channel_id()));
7252                                                 if let Some(preimage) = htlc_update.payment_preimage {
7253                                                         log_trace!(logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7254                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
7255                                                 } else {
7256                                                         log_trace!(logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7257                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
7258                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7259                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7260                                                 }
7261                                         },
7262                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
7263                                                 let counterparty_node_id_opt = match counterparty_node_id {
7264                                                         Some(cp_id) => Some(cp_id),
7265                                                         None => {
7266                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7267                                                                 // monitor event, this and the outpoint_to_peer map should be removed.
7268                                                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
7269                                                                 outpoint_to_peer.get(&funding_outpoint).cloned()
7270                                                         }
7271                                                 };
7272                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7273                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7274                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7275                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7276                                                                 let peer_state = &mut *peer_state_lock;
7277                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7278                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
7279                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7280                                                                                 failed_channels.push(chan.context.force_shutdown(false, ClosureReason::HolderForceClosed));
7281                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7282                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7283                                                                                                 msg: update
7284                                                                                         });
7285                                                                                 }
7286                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7287                                                                                         node_id: chan.context.get_counterparty_node_id(),
7288                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7289                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7290                                                                                         },
7291                                                                                 });
7292                                                                         }
7293                                                                 }
7294                                                         }
7295                                                 }
7296                                         },
7297                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
7298                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
7299                                         },
7300                                 }
7301                         }
7302                 }
7303
7304                 for failure in failed_channels.drain(..) {
7305                         self.finish_close_channel(failure);
7306                 }
7307
7308                 has_pending_monitor_events
7309         }
7310
7311         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7312         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7313         /// update events as a separate process method here.
7314         #[cfg(fuzzing)]
7315         pub fn process_monitor_events(&self) {
7316                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7317                 self.process_pending_monitor_events();
7318         }
7319
7320         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7321         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7322         /// update was applied.
7323         fn check_free_holding_cells(&self) -> bool {
7324                 let mut has_monitor_update = false;
7325                 let mut failed_htlcs = Vec::new();
7326
7327                 // Walk our list of channels and find any that need to update. Note that when we do find an
7328                 // update, if it includes actions that must be taken afterwards, we have to drop the
7329                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7330                 // manage to go through all our peers without finding a single channel to update.
7331                 'peer_loop: loop {
7332                         let per_peer_state = self.per_peer_state.read().unwrap();
7333                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7334                                 'chan_loop: loop {
7335                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7336                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7337                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7338                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7339                                         ) {
7340                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7341                                                 let funding_txo = chan.context.get_funding_txo();
7342                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7343                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &&WithChannelContext::from(&self.logger, &chan.context));
7344                                                 if !holding_cell_failed_htlcs.is_empty() {
7345                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7346                                                 }
7347                                                 if let Some(monitor_update) = monitor_opt {
7348                                                         has_monitor_update = true;
7349
7350                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7351                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7352                                                         continue 'peer_loop;
7353                                                 }
7354                                         }
7355                                         break 'chan_loop;
7356                                 }
7357                         }
7358                         break 'peer_loop;
7359                 }
7360
7361                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7362                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7363                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7364                 }
7365
7366                 has_update
7367         }
7368
7369         /// When a call to a [`ChannelSigner`] method returns an error, this indicates that the signer
7370         /// is (temporarily) unavailable, and the operation should be retried later.
7371         ///
7372         /// This method allows for that retry - either checking for any signer-pending messages to be
7373         /// attempted in every channel, or in the specifically provided channel.
7374         ///
7375         /// [`ChannelSigner`]: crate::sign::ChannelSigner
7376         #[cfg(async_signing)]
7377         pub fn signer_unblocked(&self, channel_opt: Option<(PublicKey, ChannelId)>) {
7378                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7379
7380                 let unblock_chan = |phase: &mut ChannelPhase<SP>, pending_msg_events: &mut Vec<MessageSendEvent>| {
7381                         let node_id = phase.context().get_counterparty_node_id();
7382                         match phase {
7383                                 ChannelPhase::Funded(chan) => {
7384                                         let msgs = chan.signer_maybe_unblocked(&self.logger);
7385                                         if let Some(updates) = msgs.commitment_update {
7386                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
7387                                                         node_id,
7388                                                         updates,
7389                                                 });
7390                                         }
7391                                         if let Some(msg) = msgs.funding_signed {
7392                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
7393                                                         node_id,
7394                                                         msg,
7395                                                 });
7396                                         }
7397                                         if let Some(msg) = msgs.channel_ready {
7398                                                 send_channel_ready!(self, pending_msg_events, chan, msg);
7399                                         }
7400                                 }
7401                                 ChannelPhase::UnfundedOutboundV1(chan) => {
7402                                         if let Some(msg) = chan.signer_maybe_unblocked(&self.logger) {
7403                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
7404                                                         node_id,
7405                                                         msg,
7406                                                 });
7407                                         }
7408                                 }
7409                                 ChannelPhase::UnfundedInboundV1(_) => {},
7410                         }
7411                 };
7412
7413                 let per_peer_state = self.per_peer_state.read().unwrap();
7414                 if let Some((counterparty_node_id, channel_id)) = channel_opt {
7415                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7416                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7417                                 let peer_state = &mut *peer_state_lock;
7418                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&channel_id) {
7419                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7420                                 }
7421                         }
7422                 } else {
7423                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7424                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7425                                 let peer_state = &mut *peer_state_lock;
7426                                 for (_, chan) in peer_state.channel_by_id.iter_mut() {
7427                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7428                                 }
7429                         }
7430                 }
7431         }
7432
7433         /// Check whether any channels have finished removing all pending updates after a shutdown
7434         /// exchange and can now send a closing_signed.
7435         /// Returns whether any closing_signed messages were generated.
7436         fn maybe_generate_initial_closing_signed(&self) -> bool {
7437                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7438                 let mut has_update = false;
7439                 let mut shutdown_results = Vec::new();
7440                 {
7441                         let per_peer_state = self.per_peer_state.read().unwrap();
7442
7443                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7444                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7445                                 let peer_state = &mut *peer_state_lock;
7446                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7447                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7448                                         match phase {
7449                                                 ChannelPhase::Funded(chan) => {
7450                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7451                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &&logger) {
7452                                                                 Ok((msg_opt, tx_opt, shutdown_result_opt)) => {
7453                                                                         if let Some(msg) = msg_opt {
7454                                                                                 has_update = true;
7455                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7456                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7457                                                                                 });
7458                                                                         }
7459                                                                         debug_assert_eq!(shutdown_result_opt.is_some(), chan.is_shutdown());
7460                                                                         if let Some(shutdown_result) = shutdown_result_opt {
7461                                                                                 shutdown_results.push(shutdown_result);
7462                                                                         }
7463                                                                         if let Some(tx) = tx_opt {
7464                                                                                 // We're done with this channel. We got a closing_signed and sent back
7465                                                                                 // a closing_signed with a closing transaction to broadcast.
7466                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7467                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7468                                                                                                 msg: update
7469                                                                                         });
7470                                                                                 }
7471
7472                                                                                 log_info!(logger, "Broadcasting {}", log_tx!(tx));
7473                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7474                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7475                                                                                 false
7476                                                                         } else { true }
7477                                                                 },
7478                                                                 Err(e) => {
7479                                                                         has_update = true;
7480                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7481                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7482                                                                         !close_channel
7483                                                                 }
7484                                                         }
7485                                                 },
7486                                                 _ => true, // Retain unfunded channels if present.
7487                                         }
7488                                 });
7489                         }
7490                 }
7491
7492                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7493                         let _ = handle_error!(self, err, counterparty_node_id);
7494                 }
7495
7496                 for shutdown_result in shutdown_results.drain(..) {
7497                         self.finish_close_channel(shutdown_result);
7498                 }
7499
7500                 has_update
7501         }
7502
7503         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7504         /// pushing the channel monitor update (if any) to the background events queue and removing the
7505         /// Channel object.
7506         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7507                 for mut failure in failed_channels.drain(..) {
7508                         // Either a commitment transactions has been confirmed on-chain or
7509                         // Channel::block_disconnected detected that the funding transaction has been
7510                         // reorganized out of the main chain.
7511                         // We cannot broadcast our latest local state via monitor update (as
7512                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7513                         // so we track the update internally and handle it when the user next calls
7514                         // timer_tick_occurred, guaranteeing we're running normally.
7515                         if let Some((counterparty_node_id, funding_txo, update)) = failure.monitor_update.take() {
7516                                 assert_eq!(update.updates.len(), 1);
7517                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7518                                         assert!(should_broadcast);
7519                                 } else { unreachable!(); }
7520                                 self.pending_background_events.lock().unwrap().push(
7521                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7522                                                 counterparty_node_id, funding_txo, update
7523                                         });
7524                         }
7525                         self.finish_close_channel(failure);
7526                 }
7527         }
7528 }
7529
7530 macro_rules! create_offer_builder { ($self: ident, $builder: ty) => {
7531         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7532         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7533         /// not have an expiration unless otherwise set on the builder.
7534         ///
7535         /// # Privacy
7536         ///
7537         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the offer.
7538         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7539         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7540         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7541         /// order to send the [`InvoiceRequest`].
7542         ///
7543         /// Also, uses a derived signing pubkey in the offer for recipient privacy.
7544         ///
7545         /// # Limitations
7546         ///
7547         /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
7548         /// reply path.
7549         ///
7550         /// # Errors
7551         ///
7552         /// Errors if the parameterized [`Router`] is unable to create a blinded path for the offer.
7553         ///
7554         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7555         ///
7556         /// [`Offer`]: crate::offers::offer::Offer
7557         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7558         pub fn create_offer_builder(
7559                 &$self, description: String
7560         ) -> Result<$builder, Bolt12SemanticError> {
7561                 let node_id = $self.get_our_node_id();
7562                 let expanded_key = &$self.inbound_payment_key;
7563                 let entropy = &*$self.entropy_source;
7564                 let secp_ctx = &$self.secp_ctx;
7565
7566                 let path = $self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7567                 let builder = OfferBuilder::deriving_signing_pubkey(
7568                         description, node_id, expanded_key, entropy, secp_ctx
7569                 )
7570                         .chain_hash($self.chain_hash)
7571                         .path(path);
7572
7573                 Ok(builder.into())
7574         }
7575 } }
7576
7577 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>
7578 where
7579         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
7580         T::Target: BroadcasterInterface,
7581         ES::Target: EntropySource,
7582         NS::Target: NodeSigner,
7583         SP::Target: SignerProvider,
7584         F::Target: FeeEstimator,
7585         R::Target: Router,
7586         L::Target: Logger,
7587 {
7588         #[cfg(not(c_bindings))]
7589         create_offer_builder!(self, OfferBuilder<DerivedMetadata, secp256k1::All>);
7590
7591         #[cfg(c_bindings)]
7592         create_offer_builder!(self, OfferWithDerivedMetadataBuilder);
7593
7594         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7595         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7596         ///
7597         /// # Payment
7598         ///
7599         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7600         /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
7601         ///
7602         /// The builder will have the provided expiration set. Any changes to the expiration on the
7603         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7604         /// block time minus two hours is used for the current time when determining if the refund has
7605         /// expired.
7606         ///
7607         /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
7608         /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
7609         /// with an [`Event::InvoiceRequestFailed`].
7610         ///
7611         /// If `max_total_routing_fee_msat` is not specified, The default from
7612         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7613         ///
7614         /// # Privacy
7615         ///
7616         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the refund.
7617         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7618         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7619         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7620         /// order to send the [`Bolt12Invoice`].
7621         ///
7622         /// Also, uses a derived payer id in the refund for payer privacy.
7623         ///
7624         /// # Limitations
7625         ///
7626         /// Requires a direct connection to an introduction node in the responding
7627         /// [`Bolt12Invoice::payment_paths`].
7628         ///
7629         /// # Errors
7630         ///
7631         /// Errors if:
7632         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7633         /// - `amount_msats` is invalid, or
7634         /// - the parameterized [`Router`] is unable to create a blinded path for the refund.
7635         ///
7636         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7637         ///
7638         /// [`Refund`]: crate::offers::refund::Refund
7639         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7640         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7641         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7642         pub fn create_refund_builder(
7643                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7644                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7645         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7646                 let node_id = self.get_our_node_id();
7647                 let expanded_key = &self.inbound_payment_key;
7648                 let entropy = &*self.entropy_source;
7649                 let secp_ctx = &self.secp_ctx;
7650
7651                 let path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7652                 let builder = RefundBuilder::deriving_payer_id(
7653                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7654                 )?
7655                         .chain_hash(self.chain_hash)
7656                         .absolute_expiry(absolute_expiry)
7657                         .path(path);
7658
7659                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7660                 self.pending_outbound_payments
7661                         .add_new_awaiting_invoice(
7662                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7663                         )
7664                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7665
7666                 Ok(builder)
7667         }
7668
7669         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7670         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7671         /// [`Bolt12Invoice`] once it is received.
7672         ///
7673         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7674         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7675         /// The optional parameters are used in the builder, if `Some`:
7676         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7677         ///   [`Offer::expects_quantity`] is `true`.
7678         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7679         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7680         ///
7681         /// If `max_total_routing_fee_msat` is not specified, The default from
7682         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7683         ///
7684         /// # Payment
7685         ///
7686         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7687         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7688         /// been sent.
7689         ///
7690         /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
7691         /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
7692         /// payment will fail with an [`Event::InvoiceRequestFailed`].
7693         ///
7694         /// # Privacy
7695         ///
7696         /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
7697         /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
7698         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7699         /// in order to send the [`Bolt12Invoice`].
7700         ///
7701         /// # Limitations
7702         ///
7703         /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
7704         /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
7705         /// [`Bolt12Invoice::payment_paths`].
7706         ///
7707         /// # Errors
7708         ///
7709         /// Errors if:
7710         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7711         /// - the provided parameters are invalid for the offer,
7712         /// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice
7713         ///   request.
7714         ///
7715         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7716         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7717         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7718         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7719         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7720         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7721         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7722         pub fn pay_for_offer(
7723                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7724                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7725                 max_total_routing_fee_msat: Option<u64>
7726         ) -> Result<(), Bolt12SemanticError> {
7727                 let expanded_key = &self.inbound_payment_key;
7728                 let entropy = &*self.entropy_source;
7729                 let secp_ctx = &self.secp_ctx;
7730
7731                 let builder = offer
7732                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7733                         .chain_hash(self.chain_hash)?;
7734                 let builder = match quantity {
7735                         None => builder,
7736                         Some(quantity) => builder.quantity(quantity)?,
7737                 };
7738                 let builder = match amount_msats {
7739                         None => builder,
7740                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7741                 };
7742                 let builder = match payer_note {
7743                         None => builder,
7744                         Some(payer_note) => builder.payer_note(payer_note),
7745                 };
7746                 let invoice_request = builder.build_and_sign()?;
7747                 let reply_path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7748
7749                 let expiration = StaleExpiration::TimerTicks(1);
7750                 self.pending_outbound_payments
7751                         .add_new_awaiting_invoice(
7752                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7753                         )
7754                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7755
7756                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7757                 if offer.paths().is_empty() {
7758                         let message = new_pending_onion_message(
7759                                 OffersMessage::InvoiceRequest(invoice_request),
7760                                 Destination::Node(offer.signing_pubkey()),
7761                                 Some(reply_path),
7762                         );
7763                         pending_offers_messages.push(message);
7764                 } else {
7765                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7766                         // Using only one path could result in a failure if the path no longer exists. But only
7767                         // one invoice for a given payment id will be paid, even if more than one is received.
7768                         const REQUEST_LIMIT: usize = 10;
7769                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7770                                 let message = new_pending_onion_message(
7771                                         OffersMessage::InvoiceRequest(invoice_request.clone()),
7772                                         Destination::BlindedPath(path.clone()),
7773                                         Some(reply_path.clone()),
7774                                 );
7775                                 pending_offers_messages.push(message);
7776                         }
7777                 }
7778
7779                 Ok(())
7780         }
7781
7782         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7783         /// message.
7784         ///
7785         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7786         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7787         /// [`PaymentPreimage`].
7788         ///
7789         /// # Limitations
7790         ///
7791         /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
7792         /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
7793         /// node meeting the aforementioned criteria, but there's no guarantee that they will be
7794         /// received and no retries will be made.
7795         ///
7796         /// # Errors
7797         ///
7798         /// Errors if the parameterized [`Router`] is unable to create a blinded payment path or reply
7799         /// path for the invoice.
7800         ///
7801         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7802         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7803                 let expanded_key = &self.inbound_payment_key;
7804                 let entropy = &*self.entropy_source;
7805                 let secp_ctx = &self.secp_ctx;
7806
7807                 let amount_msats = refund.amount_msats();
7808                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7809
7810                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7811                         Ok((payment_hash, payment_secret)) => {
7812                                 let payment_paths = self.create_blinded_payment_paths(amount_msats, payment_secret)
7813                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7814
7815                                 #[cfg(feature = "std")]
7816                                 let builder = refund.respond_using_derived_keys(
7817                                         payment_paths, payment_hash, expanded_key, entropy
7818                                 )?;
7819                                 #[cfg(not(feature = "std"))]
7820                                 let created_at = Duration::from_secs(
7821                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7822                                 );
7823                                 #[cfg(not(feature = "std"))]
7824                                 let builder = refund.respond_using_derived_keys_no_std(
7825                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7826                                 )?;
7827                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7828                                 let reply_path = self.create_blinded_path()
7829                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7830
7831                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7832                                 if refund.paths().is_empty() {
7833                                         let message = new_pending_onion_message(
7834                                                 OffersMessage::Invoice(invoice),
7835                                                 Destination::Node(refund.payer_id()),
7836                                                 Some(reply_path),
7837                                         );
7838                                         pending_offers_messages.push(message);
7839                                 } else {
7840                                         for path in refund.paths() {
7841                                                 let message = new_pending_onion_message(
7842                                                         OffersMessage::Invoice(invoice.clone()),
7843                                                         Destination::BlindedPath(path.clone()),
7844                                                         Some(reply_path.clone()),
7845                                                 );
7846                                                 pending_offers_messages.push(message);
7847                                         }
7848                                 }
7849
7850                                 Ok(())
7851                         },
7852                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7853                 }
7854         }
7855
7856         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7857         /// to pay us.
7858         ///
7859         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7860         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7861         ///
7862         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7863         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7864         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7865         /// passed directly to [`claim_funds`].
7866         ///
7867         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7868         ///
7869         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7870         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7871         ///
7872         /// # Note
7873         ///
7874         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7875         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7876         ///
7877         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7878         ///
7879         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7880         /// on versions of LDK prior to 0.0.114.
7881         ///
7882         /// [`claim_funds`]: Self::claim_funds
7883         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7884         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7885         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7886         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7887         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7888         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7889                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7890                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7891                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7892                         min_final_cltv_expiry_delta)
7893         }
7894
7895         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7896         /// stored external to LDK.
7897         ///
7898         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7899         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7900         /// the `min_value_msat` provided here, if one is provided.
7901         ///
7902         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7903         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7904         /// payments.
7905         ///
7906         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7907         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7908         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7909         /// sender "proof-of-payment" unless they have paid the required amount.
7910         ///
7911         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7912         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7913         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7914         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7915         /// invoices when no timeout is set.
7916         ///
7917         /// Note that we use block header time to time-out pending inbound payments (with some margin
7918         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7919         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7920         /// If you need exact expiry semantics, you should enforce them upon receipt of
7921         /// [`PaymentClaimable`].
7922         ///
7923         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7924         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7925         ///
7926         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7927         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7928         ///
7929         /// # Note
7930         ///
7931         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7932         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7933         ///
7934         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7935         ///
7936         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7937         /// on versions of LDK prior to 0.0.114.
7938         ///
7939         /// [`create_inbound_payment`]: Self::create_inbound_payment
7940         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7941         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7942                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7943                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7944                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7945                         min_final_cltv_expiry)
7946         }
7947
7948         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7949         /// previously returned from [`create_inbound_payment`].
7950         ///
7951         /// [`create_inbound_payment`]: Self::create_inbound_payment
7952         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7953                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7954         }
7955
7956         /// Creates a blinded path by delegating to [`MessageRouter::create_blinded_paths`].
7957         ///
7958         /// Errors if the `MessageRouter` errors or returns an empty `Vec`.
7959         fn create_blinded_path(&self) -> Result<BlindedPath, ()> {
7960                 let recipient = self.get_our_node_id();
7961                 let entropy_source = self.entropy_source.deref();
7962                 let secp_ctx = &self.secp_ctx;
7963
7964                 let peers = self.per_peer_state.read().unwrap()
7965                         .iter()
7966                         .filter(|(_, peer)| peer.lock().unwrap().latest_features.supports_onion_messages())
7967                         .map(|(node_id, _)| *node_id)
7968                         .collect::<Vec<_>>();
7969
7970                 self.router
7971                         .create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
7972                         .and_then(|paths| paths.into_iter().next().ok_or(()))
7973         }
7974
7975         /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
7976         /// [`Router::create_blinded_payment_paths`].
7977         fn create_blinded_payment_paths(
7978                 &self, amount_msats: u64, payment_secret: PaymentSecret
7979         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
7980                 let entropy_source = self.entropy_source.deref();
7981                 let secp_ctx = &self.secp_ctx;
7982
7983                 let first_hops = self.list_usable_channels();
7984                 let payee_node_id = self.get_our_node_id();
7985                 let max_cltv_expiry = self.best_block.read().unwrap().height() + CLTV_FAR_FAR_AWAY
7986                         + LATENCY_GRACE_PERIOD_BLOCKS;
7987                 let payee_tlvs = ReceiveTlvs {
7988                         payment_secret,
7989                         payment_constraints: PaymentConstraints {
7990                                 max_cltv_expiry,
7991                                 htlc_minimum_msat: 1,
7992                         },
7993                 };
7994                 self.router.create_blinded_payment_paths(
7995                         payee_node_id, first_hops, payee_tlvs, amount_msats, entropy_source, secp_ctx
7996                 )
7997         }
7998
7999         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
8000         /// are used when constructing the phantom invoice's route hints.
8001         ///
8002         /// [phantom node payments]: crate::sign::PhantomKeysManager
8003         pub fn get_phantom_scid(&self) -> u64 {
8004                 let best_block_height = self.best_block.read().unwrap().height();
8005                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8006                 loop {
8007                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8008                         // Ensure the generated scid doesn't conflict with a real channel.
8009                         match short_to_chan_info.get(&scid_candidate) {
8010                                 Some(_) => continue,
8011                                 None => return scid_candidate
8012                         }
8013                 }
8014         }
8015
8016         /// Gets route hints for use in receiving [phantom node payments].
8017         ///
8018         /// [phantom node payments]: crate::sign::PhantomKeysManager
8019         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
8020                 PhantomRouteHints {
8021                         channels: self.list_usable_channels(),
8022                         phantom_scid: self.get_phantom_scid(),
8023                         real_node_pubkey: self.get_our_node_id(),
8024                 }
8025         }
8026
8027         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
8028         /// used when constructing the route hints for HTLCs intended to be intercepted. See
8029         /// [`ChannelManager::forward_intercepted_htlc`].
8030         ///
8031         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
8032         /// times to get a unique scid.
8033         pub fn get_intercept_scid(&self) -> u64 {
8034                 let best_block_height = self.best_block.read().unwrap().height();
8035                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8036                 loop {
8037                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8038                         // Ensure the generated scid doesn't conflict with a real channel.
8039                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
8040                         return scid_candidate
8041                 }
8042         }
8043
8044         /// Gets inflight HTLC information by processing pending outbound payments that are in
8045         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
8046         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
8047                 let mut inflight_htlcs = InFlightHtlcs::new();
8048
8049                 let per_peer_state = self.per_peer_state.read().unwrap();
8050                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8051                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8052                         let peer_state = &mut *peer_state_lock;
8053                         for chan in peer_state.channel_by_id.values().filter_map(
8054                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
8055                         ) {
8056                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
8057                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
8058                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
8059                                         }
8060                                 }
8061                         }
8062                 }
8063
8064                 inflight_htlcs
8065         }
8066
8067         #[cfg(any(test, feature = "_test_utils"))]
8068         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
8069                 let events = core::cell::RefCell::new(Vec::new());
8070                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
8071                 self.process_pending_events(&event_handler);
8072                 events.into_inner()
8073         }
8074
8075         #[cfg(feature = "_test_utils")]
8076         pub fn push_pending_event(&self, event: events::Event) {
8077                 let mut events = self.pending_events.lock().unwrap();
8078                 events.push_back((event, None));
8079         }
8080
8081         #[cfg(test)]
8082         pub fn pop_pending_event(&self) -> Option<events::Event> {
8083                 let mut events = self.pending_events.lock().unwrap();
8084                 events.pop_front().map(|(e, _)| e)
8085         }
8086
8087         #[cfg(test)]
8088         pub fn has_pending_payments(&self) -> bool {
8089                 self.pending_outbound_payments.has_pending_payments()
8090         }
8091
8092         #[cfg(test)]
8093         pub fn clear_pending_payments(&self) {
8094                 self.pending_outbound_payments.clear_pending_payments()
8095         }
8096
8097         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
8098         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
8099         /// operation. It will double-check that nothing *else* is also blocking the same channel from
8100         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
8101         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
8102                 let logger = WithContext::from(
8103                         &self.logger, Some(counterparty_node_id), Some(channel_funding_outpoint.to_channel_id())
8104                 );
8105                 loop {
8106                         let per_peer_state = self.per_peer_state.read().unwrap();
8107                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
8108                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
8109                                 let peer_state = &mut *peer_state_lck;
8110                                 if let Some(blocker) = completed_blocker.take() {
8111                                         // Only do this on the first iteration of the loop.
8112                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
8113                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
8114                                         {
8115                                                 blockers.retain(|iter| iter != &blocker);
8116                                         }
8117                                 }
8118
8119                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
8120                                         channel_funding_outpoint, counterparty_node_id) {
8121                                         // Check that, while holding the peer lock, we don't have anything else
8122                                         // blocking monitor updates for this channel. If we do, release the monitor
8123                                         // update(s) when those blockers complete.
8124                                         log_trace!(logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
8125                                                 &channel_funding_outpoint.to_channel_id());
8126                                         break;
8127                                 }
8128
8129                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
8130                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
8131                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
8132                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
8133                                                         log_debug!(logger, "Unlocking monitor updating for channel {} and updating monitor",
8134                                                                 channel_funding_outpoint.to_channel_id());
8135                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
8136                                                                 peer_state_lck, peer_state, per_peer_state, chan);
8137                                                         if further_update_exists {
8138                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
8139                                                                 // top of the loop.
8140                                                                 continue;
8141                                                         }
8142                                                 } else {
8143                                                         log_trace!(logger, "Unlocked monitor updating for channel {} without monitors to update",
8144                                                                 channel_funding_outpoint.to_channel_id());
8145                                                 }
8146                                         }
8147                                 }
8148                         } else {
8149                                 log_debug!(logger,
8150                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
8151                                         log_pubkey!(counterparty_node_id));
8152                         }
8153                         break;
8154                 }
8155         }
8156
8157         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
8158                 for action in actions {
8159                         match action {
8160                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
8161                                         channel_funding_outpoint, counterparty_node_id
8162                                 } => {
8163                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
8164                                 }
8165                         }
8166                 }
8167         }
8168
8169         /// Processes any events asynchronously in the order they were generated since the last call
8170         /// using the given event handler.
8171         ///
8172         /// See the trait-level documentation of [`EventsProvider`] for requirements.
8173         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
8174                 &self, handler: H
8175         ) {
8176                 let mut ev;
8177                 process_events_body!(self, ev, { handler(ev).await });
8178         }
8179 }
8180
8181 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>
8182 where
8183         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8184         T::Target: BroadcasterInterface,
8185         ES::Target: EntropySource,
8186         NS::Target: NodeSigner,
8187         SP::Target: SignerProvider,
8188         F::Target: FeeEstimator,
8189         R::Target: Router,
8190         L::Target: Logger,
8191 {
8192         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
8193         /// The returned array will contain `MessageSendEvent`s for different peers if
8194         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
8195         /// is always placed next to each other.
8196         ///
8197         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
8198         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
8199         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
8200         /// will randomly be placed first or last in the returned array.
8201         ///
8202         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
8203         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
8204         /// the `MessageSendEvent`s to the specific peer they were generated under.
8205         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
8206                 let events = RefCell::new(Vec::new());
8207                 PersistenceNotifierGuard::optionally_notify(self, || {
8208                         let mut result = NotifyOption::SkipPersistNoEvents;
8209
8210                         // TODO: This behavior should be documented. It's unintuitive that we query
8211                         // ChannelMonitors when clearing other events.
8212                         if self.process_pending_monitor_events() {
8213                                 result = NotifyOption::DoPersist;
8214                         }
8215
8216                         if self.check_free_holding_cells() {
8217                                 result = NotifyOption::DoPersist;
8218                         }
8219                         if self.maybe_generate_initial_closing_signed() {
8220                                 result = NotifyOption::DoPersist;
8221                         }
8222
8223                         let mut pending_events = Vec::new();
8224                         let per_peer_state = self.per_peer_state.read().unwrap();
8225                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8226                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8227                                 let peer_state = &mut *peer_state_lock;
8228                                 if peer_state.pending_msg_events.len() > 0 {
8229                                         pending_events.append(&mut peer_state.pending_msg_events);
8230                                 }
8231                         }
8232
8233                         if !pending_events.is_empty() {
8234                                 events.replace(pending_events);
8235                         }
8236
8237                         result
8238                 });
8239                 events.into_inner()
8240         }
8241 }
8242
8243 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>
8244 where
8245         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8246         T::Target: BroadcasterInterface,
8247         ES::Target: EntropySource,
8248         NS::Target: NodeSigner,
8249         SP::Target: SignerProvider,
8250         F::Target: FeeEstimator,
8251         R::Target: Router,
8252         L::Target: Logger,
8253 {
8254         /// Processes events that must be periodically handled.
8255         ///
8256         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
8257         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
8258         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
8259                 let mut ev;
8260                 process_events_body!(self, ev, handler.handle_event(ev));
8261         }
8262 }
8263
8264 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>
8265 where
8266         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8267         T::Target: BroadcasterInterface,
8268         ES::Target: EntropySource,
8269         NS::Target: NodeSigner,
8270         SP::Target: SignerProvider,
8271         F::Target: FeeEstimator,
8272         R::Target: Router,
8273         L::Target: Logger,
8274 {
8275         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
8276                 {
8277                         let best_block = self.best_block.read().unwrap();
8278                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
8279                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
8280                         assert_eq!(best_block.height(), height - 1,
8281                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
8282                 }
8283
8284                 self.transactions_confirmed(header, txdata, height);
8285                 self.best_block_updated(header, height);
8286         }
8287
8288         fn block_disconnected(&self, header: &Header, height: u32) {
8289                 let _persistence_guard =
8290                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8291                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8292                 let new_height = height - 1;
8293                 {
8294                         let mut best_block = self.best_block.write().unwrap();
8295                         assert_eq!(best_block.block_hash(), header.block_hash(),
8296                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
8297                         assert_eq!(best_block.height(), height,
8298                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
8299                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
8300                 }
8301
8302                 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)));
8303         }
8304 }
8305
8306 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>
8307 where
8308         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8309         T::Target: BroadcasterInterface,
8310         ES::Target: EntropySource,
8311         NS::Target: NodeSigner,
8312         SP::Target: SignerProvider,
8313         F::Target: FeeEstimator,
8314         R::Target: Router,
8315         L::Target: Logger,
8316 {
8317         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
8318                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8319                 // during initialization prior to the chain_monitor being fully configured in some cases.
8320                 // See the docs for `ChannelManagerReadArgs` for more.
8321
8322                 let block_hash = header.block_hash();
8323                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
8324
8325                 let _persistence_guard =
8326                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8327                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8328                 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))
8329                         .map(|(a, b)| (a, Vec::new(), b)));
8330
8331                 let last_best_block_height = self.best_block.read().unwrap().height();
8332                 if height < last_best_block_height {
8333                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
8334                         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)));
8335                 }
8336         }
8337
8338         fn best_block_updated(&self, header: &Header, height: u32) {
8339                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8340                 // during initialization prior to the chain_monitor being fully configured in some cases.
8341                 // See the docs for `ChannelManagerReadArgs` for more.
8342
8343                 let block_hash = header.block_hash();
8344                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
8345
8346                 let _persistence_guard =
8347                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8348                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8349                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
8350
8351                 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)));
8352
8353                 macro_rules! max_time {
8354                         ($timestamp: expr) => {
8355                                 loop {
8356                                         // Update $timestamp to be the max of its current value and the block
8357                                         // timestamp. This should keep us close to the current time without relying on
8358                                         // having an explicit local time source.
8359                                         // Just in case we end up in a race, we loop until we either successfully
8360                                         // update $timestamp or decide we don't need to.
8361                                         let old_serial = $timestamp.load(Ordering::Acquire);
8362                                         if old_serial >= header.time as usize { break; }
8363                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8364                                                 break;
8365                                         }
8366                                 }
8367                         }
8368                 }
8369                 max_time!(self.highest_seen_timestamp);
8370                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8371                 payment_secrets.retain(|_, inbound_payment| {
8372                         inbound_payment.expiry_time > header.time as u64
8373                 });
8374         }
8375
8376         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
8377                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8378                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8379                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8380                         let peer_state = &mut *peer_state_lock;
8381                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8382                                 let txid_opt = chan.context.get_funding_txo();
8383                                 let height_opt = chan.context.get_funding_tx_confirmation_height();
8384                                 let hash_opt = chan.context.get_funding_tx_confirmed_in();
8385                                 if let (Some(funding_txo), Some(conf_height), Some(block_hash)) = (txid_opt, height_opt, hash_opt) {
8386                                         res.push((funding_txo.txid, conf_height, Some(block_hash)));
8387                                 }
8388                         }
8389                 }
8390                 res
8391         }
8392
8393         fn transaction_unconfirmed(&self, txid: &Txid) {
8394                 let _persistence_guard =
8395                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8396                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8397                 self.do_chain_event(None, |channel| {
8398                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8399                                 if funding_txo.txid == *txid {
8400                                         channel.funding_transaction_unconfirmed(&&WithChannelContext::from(&self.logger, &channel.context)).map(|()| (None, Vec::new(), None))
8401                                 } else { Ok((None, Vec::new(), None)) }
8402                         } else { Ok((None, Vec::new(), None)) }
8403                 });
8404         }
8405 }
8406
8407 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>
8408 where
8409         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8410         T::Target: BroadcasterInterface,
8411         ES::Target: EntropySource,
8412         NS::Target: NodeSigner,
8413         SP::Target: SignerProvider,
8414         F::Target: FeeEstimator,
8415         R::Target: Router,
8416         L::Target: Logger,
8417 {
8418         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8419         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8420         /// the function.
8421         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8422                         (&self, height_opt: Option<u32>, f: FN) {
8423                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8424                 // during initialization prior to the chain_monitor being fully configured in some cases.
8425                 // See the docs for `ChannelManagerReadArgs` for more.
8426
8427                 let mut failed_channels = Vec::new();
8428                 let mut timed_out_htlcs = Vec::new();
8429                 {
8430                         let per_peer_state = self.per_peer_state.read().unwrap();
8431                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8432                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8433                                 let peer_state = &mut *peer_state_lock;
8434                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8435                                 peer_state.channel_by_id.retain(|_, phase| {
8436                                         match phase {
8437                                                 // Retain unfunded channels.
8438                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8439                                                 ChannelPhase::Funded(channel) => {
8440                                                         let res = f(channel);
8441                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8442                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8443                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8444                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8445                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8446                                                                 }
8447                                                                 let logger = WithChannelContext::from(&self.logger, &channel.context);
8448                                                                 if let Some(channel_ready) = channel_ready_opt {
8449                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8450                                                                         if channel.context.is_usable() {
8451                                                                                 log_trace!(logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8452                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8453                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8454                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8455                                                                                                 msg,
8456                                                                                         });
8457                                                                                 }
8458                                                                         } else {
8459                                                                                 log_trace!(logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8460                                                                         }
8461                                                                 }
8462
8463                                                                 {
8464                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8465                                                                         emit_channel_ready_event!(pending_events, channel);
8466                                                                 }
8467
8468                                                                 if let Some(announcement_sigs) = announcement_sigs {
8469                                                                         log_trace!(logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8470                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8471                                                                                 node_id: channel.context.get_counterparty_node_id(),
8472                                                                                 msg: announcement_sigs,
8473                                                                         });
8474                                                                         if let Some(height) = height_opt {
8475                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8476                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8477                                                                                                 msg: announcement,
8478                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8479                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8480                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8481                                                                                         });
8482                                                                                 }
8483                                                                         }
8484                                                                 }
8485                                                                 if channel.is_our_channel_ready() {
8486                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8487                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8488                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8489                                                                                 // can relay using the real SCID at relay-time (i.e.
8490                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8491                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8492                                                                                 // is always consistent.
8493                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8494                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8495                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8496                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8497                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8498                                                                         }
8499                                                                 }
8500                                                         } else if let Err(reason) = res {
8501                                                                 update_maps_on_chan_removal!(self, &channel.context);
8502                                                                 // It looks like our counterparty went on-chain or funding transaction was
8503                                                                 // reorged out of the main chain. Close the channel.
8504                                                                 let reason_message = format!("{}", reason);
8505                                                                 failed_channels.push(channel.context.force_shutdown(true, reason));
8506                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8507                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
8508                                                                                 msg: update
8509                                                                         });
8510                                                                 }
8511                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8512                                                                         node_id: channel.context.get_counterparty_node_id(),
8513                                                                         action: msgs::ErrorAction::DisconnectPeer {
8514                                                                                 msg: Some(msgs::ErrorMessage {
8515                                                                                         channel_id: channel.context.channel_id(),
8516                                                                                         data: reason_message,
8517                                                                                 })
8518                                                                         },
8519                                                                 });
8520                                                                 return false;
8521                                                         }
8522                                                         true
8523                                                 }
8524                                         }
8525                                 });
8526                         }
8527                 }
8528
8529                 if let Some(height) = height_opt {
8530                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8531                                 payment.htlcs.retain(|htlc| {
8532                                         // If height is approaching the number of blocks we think it takes us to get
8533                                         // our commitment transaction confirmed before the HTLC expires, plus the
8534                                         // number of blocks we generally consider it to take to do a commitment update,
8535                                         // just give up on it and fail the HTLC.
8536                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8537                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8538                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8539
8540                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8541                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8542                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8543                                                 false
8544                                         } else { true }
8545                                 });
8546                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8547                         });
8548
8549                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8550                         intercepted_htlcs.retain(|_, htlc| {
8551                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8552                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8553                                                 short_channel_id: htlc.prev_short_channel_id,
8554                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8555                                                 htlc_id: htlc.prev_htlc_id,
8556                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8557                                                 phantom_shared_secret: None,
8558                                                 outpoint: htlc.prev_funding_outpoint,
8559                                                 blinded_failure: htlc.forward_info.routing.blinded_failure(),
8560                                         });
8561
8562                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8563                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8564                                                 _ => unreachable!(),
8565                                         };
8566                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8567                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8568                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8569                                         let logger = WithContext::from(
8570                                                 &self.logger, None, Some(htlc.prev_funding_outpoint.to_channel_id())
8571                                         );
8572                                         log_trace!(logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8573                                         false
8574                                 } else { true }
8575                         });
8576                 }
8577
8578                 self.handle_init_event_channel_failures(failed_channels);
8579
8580                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8581                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8582                 }
8583         }
8584
8585         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8586         /// may have events that need processing.
8587         ///
8588         /// In order to check if this [`ChannelManager`] needs persisting, call
8589         /// [`Self::get_and_clear_needs_persistence`].
8590         ///
8591         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8592         /// [`ChannelManager`] and should instead register actions to be taken later.
8593         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8594                 self.event_persist_notifier.get_future()
8595         }
8596
8597         /// Returns true if this [`ChannelManager`] needs to be persisted.
8598         pub fn get_and_clear_needs_persistence(&self) -> bool {
8599                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8600         }
8601
8602         #[cfg(any(test, feature = "_test_utils"))]
8603         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8604                 self.event_persist_notifier.notify_pending()
8605         }
8606
8607         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8608         /// [`chain::Confirm`] interfaces.
8609         pub fn current_best_block(&self) -> BestBlock {
8610                 self.best_block.read().unwrap().clone()
8611         }
8612
8613         /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
8614         /// [`ChannelManager`].
8615         pub fn node_features(&self) -> NodeFeatures {
8616                 provided_node_features(&self.default_configuration)
8617         }
8618
8619         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
8620         /// [`ChannelManager`].
8621         ///
8622         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8623         /// or not. Thus, this method is not public.
8624         #[cfg(any(feature = "_test_utils", test))]
8625         pub fn bolt11_invoice_features(&self) -> Bolt11InvoiceFeatures {
8626                 provided_bolt11_invoice_features(&self.default_configuration)
8627         }
8628
8629         /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
8630         /// [`ChannelManager`].
8631         fn bolt12_invoice_features(&self) -> Bolt12InvoiceFeatures {
8632                 provided_bolt12_invoice_features(&self.default_configuration)
8633         }
8634
8635         /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
8636         /// [`ChannelManager`].
8637         pub fn channel_features(&self) -> ChannelFeatures {
8638                 provided_channel_features(&self.default_configuration)
8639         }
8640
8641         /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
8642         /// [`ChannelManager`].
8643         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8644                 provided_channel_type_features(&self.default_configuration)
8645         }
8646
8647         /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
8648         /// [`ChannelManager`].
8649         pub fn init_features(&self) -> InitFeatures {
8650                 provided_init_features(&self.default_configuration)
8651         }
8652 }
8653
8654 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8655         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8656 where
8657         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8658         T::Target: BroadcasterInterface,
8659         ES::Target: EntropySource,
8660         NS::Target: NodeSigner,
8661         SP::Target: SignerProvider,
8662         F::Target: FeeEstimator,
8663         R::Target: Router,
8664         L::Target: Logger,
8665 {
8666         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8667                 // Note that we never need to persist the updated ChannelManager for an inbound
8668                 // open_channel message - pre-funded channels are never written so there should be no
8669                 // change to the contents.
8670                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8671                         let res = self.internal_open_channel(counterparty_node_id, msg);
8672                         let persist = match &res {
8673                                 Err(e) if e.closes_channel() => {
8674                                         debug_assert!(false, "We shouldn't close a new channel");
8675                                         NotifyOption::DoPersist
8676                                 },
8677                                 _ => NotifyOption::SkipPersistHandleEvents,
8678                         };
8679                         let _ = handle_error!(self, res, *counterparty_node_id);
8680                         persist
8681                 });
8682         }
8683
8684         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8685                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8686                         "Dual-funded channels not supported".to_owned(),
8687                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8688         }
8689
8690         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8691                 // Note that we never need to persist the updated ChannelManager for an inbound
8692                 // accept_channel message - pre-funded channels are never written so there should be no
8693                 // change to the contents.
8694                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8695                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8696                         NotifyOption::SkipPersistHandleEvents
8697                 });
8698         }
8699
8700         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8701                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8702                         "Dual-funded channels not supported".to_owned(),
8703                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8704         }
8705
8706         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8707                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8708                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8709         }
8710
8711         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8712                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8713                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8714         }
8715
8716         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8717                 // Note that we never need to persist the updated ChannelManager for an inbound
8718                 // channel_ready message - while the channel's state will change, any channel_ready message
8719                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8720                 // will not force-close the channel on startup.
8721                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8722                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8723                         let persist = match &res {
8724                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8725                                 _ => NotifyOption::SkipPersistHandleEvents,
8726                         };
8727                         let _ = handle_error!(self, res, *counterparty_node_id);
8728                         persist
8729                 });
8730         }
8731
8732         fn handle_stfu(&self, counterparty_node_id: &PublicKey, msg: &msgs::Stfu) {
8733                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8734                         "Quiescence not supported".to_owned(),
8735                          msg.channel_id.clone())), *counterparty_node_id);
8736         }
8737
8738         fn handle_splice(&self, counterparty_node_id: &PublicKey, msg: &msgs::Splice) {
8739                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8740                         "Splicing not supported".to_owned(),
8741                          msg.channel_id.clone())), *counterparty_node_id);
8742         }
8743
8744         fn handle_splice_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceAck) {
8745                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8746                         "Splicing not supported (splice_ack)".to_owned(),
8747                          msg.channel_id.clone())), *counterparty_node_id);
8748         }
8749
8750         fn handle_splice_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
8751                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8752                         "Splicing not supported (splice_locked)".to_owned(),
8753                          msg.channel_id.clone())), *counterparty_node_id);
8754         }
8755
8756         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8757                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8758                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8759         }
8760
8761         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8762                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8763                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8764         }
8765
8766         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8767                 // Note that we never need to persist the updated ChannelManager for an inbound
8768                 // update_add_htlc message - the message itself doesn't change our channel state only the
8769                 // `commitment_signed` message afterwards will.
8770                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8771                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8772                         let persist = match &res {
8773                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8774                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8775                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8776                         };
8777                         let _ = handle_error!(self, res, *counterparty_node_id);
8778                         persist
8779                 });
8780         }
8781
8782         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8783                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8784                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8785         }
8786
8787         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8788                 // Note that we never need to persist the updated ChannelManager for an inbound
8789                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8790                 // `commitment_signed` message afterwards will.
8791                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8792                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8793                         let persist = match &res {
8794                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8795                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8796                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8797                         };
8798                         let _ = handle_error!(self, res, *counterparty_node_id);
8799                         persist
8800                 });
8801         }
8802
8803         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8804                 // Note that we never need to persist the updated ChannelManager for an inbound
8805                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8806                 // only the `commitment_signed` message afterwards will.
8807                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8808                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8809                         let persist = match &res {
8810                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8811                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8812                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8813                         };
8814                         let _ = handle_error!(self, res, *counterparty_node_id);
8815                         persist
8816                 });
8817         }
8818
8819         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8820                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8821                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8822         }
8823
8824         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8825                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8826                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8827         }
8828
8829         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8830                 // Note that we never need to persist the updated ChannelManager for an inbound
8831                 // update_fee message - the message itself doesn't change our channel state only the
8832                 // `commitment_signed` message afterwards will.
8833                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8834                         let res = self.internal_update_fee(counterparty_node_id, msg);
8835                         let persist = match &res {
8836                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8837                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8838                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8839                         };
8840                         let _ = handle_error!(self, res, *counterparty_node_id);
8841                         persist
8842                 });
8843         }
8844
8845         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8846                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8847                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8848         }
8849
8850         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8851                 PersistenceNotifierGuard::optionally_notify(self, || {
8852                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8853                                 persist
8854                         } else {
8855                                 NotifyOption::DoPersist
8856                         }
8857                 });
8858         }
8859
8860         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8861                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8862                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8863                         let persist = match &res {
8864                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8865                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8866                                 Ok(persist) => *persist,
8867                         };
8868                         let _ = handle_error!(self, res, *counterparty_node_id);
8869                         persist
8870                 });
8871         }
8872
8873         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8874                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8875                         self, || NotifyOption::SkipPersistHandleEvents);
8876                 let mut failed_channels = Vec::new();
8877                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8878                 let remove_peer = {
8879                         log_debug!(
8880                                 WithContext::from(&self.logger, Some(*counterparty_node_id), None),
8881                                 "Marking channels with {} disconnected and generating channel_updates.",
8882                                 log_pubkey!(counterparty_node_id)
8883                         );
8884                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8885                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8886                                 let peer_state = &mut *peer_state_lock;
8887                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8888                                 peer_state.channel_by_id.retain(|_, phase| {
8889                                         let context = match phase {
8890                                                 ChannelPhase::Funded(chan) => {
8891                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
8892                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&&logger).is_ok() {
8893                                                                 // We only retain funded channels that are not shutdown.
8894                                                                 return true;
8895                                                         }
8896                                                         &mut chan.context
8897                                                 },
8898                                                 // Unfunded channels will always be removed.
8899                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8900                                                         &mut chan.context
8901                                                 },
8902                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8903                                                         &mut chan.context
8904                                                 },
8905                                         };
8906                                         // Clean up for removal.
8907                                         update_maps_on_chan_removal!(self, &context);
8908                                         failed_channels.push(context.force_shutdown(false, ClosureReason::DisconnectedPeer));
8909                                         false
8910                                 });
8911                                 // Note that we don't bother generating any events for pre-accept channels -
8912                                 // they're not considered "channels" yet from the PoV of our events interface.
8913                                 peer_state.inbound_channel_request_by_id.clear();
8914                                 pending_msg_events.retain(|msg| {
8915                                         match msg {
8916                                                 // V1 Channel Establishment
8917                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8918                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8919                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8920                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8921                                                 // V2 Channel Establishment
8922                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8923                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8924                                                 // Common Channel Establishment
8925                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8926                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8927                                                 // Quiescence
8928                                                 &events::MessageSendEvent::SendStfu { .. } => false,
8929                                                 // Splicing
8930                                                 &events::MessageSendEvent::SendSplice { .. } => false,
8931                                                 &events::MessageSendEvent::SendSpliceAck { .. } => false,
8932                                                 &events::MessageSendEvent::SendSpliceLocked { .. } => false,
8933                                                 // Interactive Transaction Construction
8934                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8935                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8936                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8937                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8938                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8939                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8940                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8941                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8942                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8943                                                 // Channel Operations
8944                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8945                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8946                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8947                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8948                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8949                                                 &events::MessageSendEvent::HandleError { .. } => false,
8950                                                 // Gossip
8951                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8952                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8953                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8954                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8955                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8956                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8957                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8958                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8959                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8960                                         }
8961                                 });
8962                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8963                                 peer_state.is_connected = false;
8964                                 peer_state.ok_to_remove(true)
8965                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8966                 };
8967                 if remove_peer {
8968                         per_peer_state.remove(counterparty_node_id);
8969                 }
8970                 mem::drop(per_peer_state);
8971
8972                 for failure in failed_channels.drain(..) {
8973                         self.finish_close_channel(failure);
8974                 }
8975         }
8976
8977         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8978                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), None);
8979                 if !init_msg.features.supports_static_remote_key() {
8980                         log_debug!(logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8981                         return Err(());
8982                 }
8983
8984                 let mut res = Ok(());
8985
8986                 PersistenceNotifierGuard::optionally_notify(self, || {
8987                         // If we have too many peers connected which don't have funded channels, disconnect the
8988                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8989                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8990                         // peers connect, but we'll reject new channels from them.
8991                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8992                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8993
8994                         {
8995                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8996                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8997                                         hash_map::Entry::Vacant(e) => {
8998                                                 if inbound_peer_limited {
8999                                                         res = Err(());
9000                                                         return NotifyOption::SkipPersistNoEvents;
9001                                                 }
9002                                                 e.insert(Mutex::new(PeerState {
9003                                                         channel_by_id: HashMap::new(),
9004                                                         inbound_channel_request_by_id: HashMap::new(),
9005                                                         latest_features: init_msg.features.clone(),
9006                                                         pending_msg_events: Vec::new(),
9007                                                         in_flight_monitor_updates: BTreeMap::new(),
9008                                                         monitor_update_blocked_actions: BTreeMap::new(),
9009                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
9010                                                         is_connected: true,
9011                                                 }));
9012                                         },
9013                                         hash_map::Entry::Occupied(e) => {
9014                                                 let mut peer_state = e.get().lock().unwrap();
9015                                                 peer_state.latest_features = init_msg.features.clone();
9016
9017                                                 let best_block_height = self.best_block.read().unwrap().height();
9018                                                 if inbound_peer_limited &&
9019                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
9020                                                         peer_state.channel_by_id.len()
9021                                                 {
9022                                                         res = Err(());
9023                                                         return NotifyOption::SkipPersistNoEvents;
9024                                                 }
9025
9026                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
9027                                                 peer_state.is_connected = true;
9028                                         },
9029                                 }
9030                         }
9031
9032                         log_debug!(logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
9033
9034                         let per_peer_state = self.per_peer_state.read().unwrap();
9035                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
9036                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9037                                 let peer_state = &mut *peer_state_lock;
9038                                 let pending_msg_events = &mut peer_state.pending_msg_events;
9039
9040                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
9041                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
9042                                 ).for_each(|chan| {
9043                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
9044                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
9045                                                 node_id: chan.context.get_counterparty_node_id(),
9046                                                 msg: chan.get_channel_reestablish(&&logger),
9047                                         });
9048                                 });
9049                         }
9050
9051                         return NotifyOption::SkipPersistHandleEvents;
9052                         //TODO: Also re-broadcast announcement_signatures
9053                 });
9054                 res
9055         }
9056
9057         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
9058                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9059
9060                 match &msg.data as &str {
9061                         "cannot co-op close channel w/ active htlcs"|
9062                         "link failed to shutdown" =>
9063                         {
9064                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
9065                                 // send one while HTLCs are still present. The issue is tracked at
9066                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
9067                                 // to fix it but none so far have managed to land upstream. The issue appears to be
9068                                 // very low priority for the LND team despite being marked "P1".
9069                                 // We're not going to bother handling this in a sensible way, instead simply
9070                                 // repeating the Shutdown message on repeat until morale improves.
9071                                 if !msg.channel_id.is_zero() {
9072                                         let per_peer_state = self.per_peer_state.read().unwrap();
9073                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9074                                         if peer_state_mutex_opt.is_none() { return; }
9075                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
9076                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
9077                                                 if let Some(msg) = chan.get_outbound_shutdown() {
9078                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
9079                                                                 node_id: *counterparty_node_id,
9080                                                                 msg,
9081                                                         });
9082                                                 }
9083                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
9084                                                         node_id: *counterparty_node_id,
9085                                                         action: msgs::ErrorAction::SendWarningMessage {
9086                                                                 msg: msgs::WarningMessage {
9087                                                                         channel_id: msg.channel_id,
9088                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
9089                                                                 },
9090                                                                 log_level: Level::Trace,
9091                                                         }
9092                                                 });
9093                                         }
9094                                 }
9095                                 return;
9096                         }
9097                         _ => {}
9098                 }
9099
9100                 if msg.channel_id.is_zero() {
9101                         let channel_ids: Vec<ChannelId> = {
9102                                 let per_peer_state = self.per_peer_state.read().unwrap();
9103                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9104                                 if peer_state_mutex_opt.is_none() { return; }
9105                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9106                                 let peer_state = &mut *peer_state_lock;
9107                                 // Note that we don't bother generating any events for pre-accept channels -
9108                                 // they're not considered "channels" yet from the PoV of our events interface.
9109                                 peer_state.inbound_channel_request_by_id.clear();
9110                                 peer_state.channel_by_id.keys().cloned().collect()
9111                         };
9112                         for channel_id in channel_ids {
9113                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9114                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
9115                         }
9116                 } else {
9117                         {
9118                                 // First check if we can advance the channel type and try again.
9119                                 let per_peer_state = self.per_peer_state.read().unwrap();
9120                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9121                                 if peer_state_mutex_opt.is_none() { return; }
9122                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9123                                 let peer_state = &mut *peer_state_lock;
9124                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
9125                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
9126                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
9127                                                         node_id: *counterparty_node_id,
9128                                                         msg,
9129                                                 });
9130                                                 return;
9131                                         }
9132                                 }
9133                         }
9134
9135                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9136                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
9137                 }
9138         }
9139
9140         fn provided_node_features(&self) -> NodeFeatures {
9141                 provided_node_features(&self.default_configuration)
9142         }
9143
9144         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
9145                 provided_init_features(&self.default_configuration)
9146         }
9147
9148         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
9149                 Some(vec![self.chain_hash])
9150         }
9151
9152         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
9153                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9154                         "Dual-funded channels not supported".to_owned(),
9155                          msg.channel_id.clone())), *counterparty_node_id);
9156         }
9157
9158         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
9159                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9160                         "Dual-funded channels not supported".to_owned(),
9161                          msg.channel_id.clone())), *counterparty_node_id);
9162         }
9163
9164         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
9165                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9166                         "Dual-funded channels not supported".to_owned(),
9167                          msg.channel_id.clone())), *counterparty_node_id);
9168         }
9169
9170         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
9171                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9172                         "Dual-funded channels not supported".to_owned(),
9173                          msg.channel_id.clone())), *counterparty_node_id);
9174         }
9175
9176         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
9177                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9178                         "Dual-funded channels not supported".to_owned(),
9179                          msg.channel_id.clone())), *counterparty_node_id);
9180         }
9181
9182         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
9183                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9184                         "Dual-funded channels not supported".to_owned(),
9185                          msg.channel_id.clone())), *counterparty_node_id);
9186         }
9187
9188         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
9189                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9190                         "Dual-funded channels not supported".to_owned(),
9191                          msg.channel_id.clone())), *counterparty_node_id);
9192         }
9193
9194         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
9195                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9196                         "Dual-funded channels not supported".to_owned(),
9197                          msg.channel_id.clone())), *counterparty_node_id);
9198         }
9199
9200         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
9201                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9202                         "Dual-funded channels not supported".to_owned(),
9203                          msg.channel_id.clone())), *counterparty_node_id);
9204         }
9205 }
9206
9207 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9208 OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
9209 where
9210         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9211         T::Target: BroadcasterInterface,
9212         ES::Target: EntropySource,
9213         NS::Target: NodeSigner,
9214         SP::Target: SignerProvider,
9215         F::Target: FeeEstimator,
9216         R::Target: Router,
9217         L::Target: Logger,
9218 {
9219         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
9220                 let secp_ctx = &self.secp_ctx;
9221                 let expanded_key = &self.inbound_payment_key;
9222
9223                 match message {
9224                         OffersMessage::InvoiceRequest(invoice_request) => {
9225                                 let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
9226                                         &invoice_request
9227                                 ) {
9228                                         Ok(amount_msats) => amount_msats,
9229                                         Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
9230                                 };
9231                                 let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
9232                                         Ok(invoice_request) => invoice_request,
9233                                         Err(()) => {
9234                                                 let error = Bolt12SemanticError::InvalidMetadata;
9235                                                 return Some(OffersMessage::InvoiceError(error.into()));
9236                                         },
9237                                 };
9238
9239                                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9240                                 let (payment_hash, payment_secret) = match self.create_inbound_payment(
9241                                         Some(amount_msats), relative_expiry, None
9242                                 ) {
9243                                         Ok((payment_hash, payment_secret)) => (payment_hash, payment_secret),
9244                                         Err(()) => {
9245                                                 let error = Bolt12SemanticError::InvalidAmount;
9246                                                 return Some(OffersMessage::InvoiceError(error.into()));
9247                                         },
9248                                 };
9249
9250                                 let payment_paths = match self.create_blinded_payment_paths(
9251                                         amount_msats, payment_secret
9252                                 ) {
9253                                         Ok(payment_paths) => payment_paths,
9254                                         Err(()) => {
9255                                                 let error = Bolt12SemanticError::MissingPaths;
9256                                                 return Some(OffersMessage::InvoiceError(error.into()));
9257                                         },
9258                                 };
9259
9260                                 #[cfg(not(feature = "std"))]
9261                                 let created_at = Duration::from_secs(
9262                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9263                                 );
9264
9265                                 if invoice_request.keys.is_some() {
9266                                         #[cfg(feature = "std")]
9267                                         let builder = invoice_request.respond_using_derived_keys(
9268                                                 payment_paths, payment_hash
9269                                         );
9270                                         #[cfg(not(feature = "std"))]
9271                                         let builder = invoice_request.respond_using_derived_keys_no_std(
9272                                                 payment_paths, payment_hash, created_at
9273                                         );
9274                                         match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
9275                                                 Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
9276                                                 Err(error) => Some(OffersMessage::InvoiceError(error.into())),
9277                                         }
9278                                 } else {
9279                                         #[cfg(feature = "std")]
9280                                         let builder = invoice_request.respond_with(payment_paths, payment_hash);
9281                                         #[cfg(not(feature = "std"))]
9282                                         let builder = invoice_request.respond_with_no_std(
9283                                                 payment_paths, payment_hash, created_at
9284                                         );
9285                                         let response = builder.and_then(|builder| builder.allow_mpp().build())
9286                                                 .map_err(|e| OffersMessage::InvoiceError(e.into()))
9287                                                 .and_then(|invoice|
9288                                                         match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
9289                                                                 Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
9290                                                                 Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
9291                                                                                 InvoiceError::from_string("Failed signing invoice".to_string())
9292                                                                 )),
9293                                                                 Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
9294                                                                                 InvoiceError::from_string("Failed invoice signature verification".to_string())
9295                                                                 )),
9296                                                         });
9297                                         match response {
9298                                                 Ok(invoice) => Some(invoice),
9299                                                 Err(error) => Some(error),
9300                                         }
9301                                 }
9302                         },
9303                         OffersMessage::Invoice(invoice) => {
9304                                 match invoice.verify(expanded_key, secp_ctx) {
9305                                         Err(()) => {
9306                                                 Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
9307                                         },
9308                                         Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
9309                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
9310                                         },
9311                                         Ok(payment_id) => {
9312                                                 if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
9313                                                         log_trace!(self.logger, "Failed paying invoice: {:?}", e);
9314                                                         Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
9315                                                 } else {
9316                                                         None
9317                                                 }
9318                                         },
9319                                 }
9320                         },
9321                         OffersMessage::InvoiceError(invoice_error) => {
9322                                 log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
9323                                 None
9324                         },
9325                 }
9326         }
9327
9328         fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> {
9329                 core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
9330         }
9331 }
9332
9333 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
9334 /// [`ChannelManager`].
9335 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
9336         let mut node_features = provided_init_features(config).to_context();
9337         node_features.set_keysend_optional();
9338         node_features
9339 }
9340
9341 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
9342 /// [`ChannelManager`].
9343 ///
9344 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
9345 /// or not. Thus, this method is not public.
9346 #[cfg(any(feature = "_test_utils", test))]
9347 pub(crate) fn provided_bolt11_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
9348         provided_init_features(config).to_context()
9349 }
9350
9351 /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
9352 /// [`ChannelManager`].
9353 pub(crate) fn provided_bolt12_invoice_features(config: &UserConfig) -> Bolt12InvoiceFeatures {
9354         provided_init_features(config).to_context()
9355 }
9356
9357 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
9358 /// [`ChannelManager`].
9359 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
9360         provided_init_features(config).to_context()
9361 }
9362
9363 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
9364 /// [`ChannelManager`].
9365 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
9366         ChannelTypeFeatures::from_init(&provided_init_features(config))
9367 }
9368
9369 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
9370 /// [`ChannelManager`].
9371 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
9372         // Note that if new features are added here which other peers may (eventually) require, we
9373         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
9374         // [`ErroringMessageHandler`].
9375         let mut features = InitFeatures::empty();
9376         features.set_data_loss_protect_required();
9377         features.set_upfront_shutdown_script_optional();
9378         features.set_variable_length_onion_required();
9379         features.set_static_remote_key_required();
9380         features.set_payment_secret_required();
9381         features.set_basic_mpp_optional();
9382         features.set_wumbo_optional();
9383         features.set_shutdown_any_segwit_optional();
9384         features.set_channel_type_optional();
9385         features.set_scid_privacy_optional();
9386         features.set_zero_conf_optional();
9387         features.set_route_blinding_optional();
9388         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
9389                 features.set_anchors_zero_fee_htlc_tx_optional();
9390         }
9391         features
9392 }
9393
9394 const SERIALIZATION_VERSION: u8 = 1;
9395 const MIN_SERIALIZATION_VERSION: u8 = 1;
9396
9397 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
9398         (2, fee_base_msat, required),
9399         (4, fee_proportional_millionths, required),
9400         (6, cltv_expiry_delta, required),
9401 });
9402
9403 impl_writeable_tlv_based!(ChannelCounterparty, {
9404         (2, node_id, required),
9405         (4, features, required),
9406         (6, unspendable_punishment_reserve, required),
9407         (8, forwarding_info, option),
9408         (9, outbound_htlc_minimum_msat, option),
9409         (11, outbound_htlc_maximum_msat, option),
9410 });
9411
9412 impl Writeable for ChannelDetails {
9413         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9414                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9415                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9416                 let user_channel_id_low = self.user_channel_id as u64;
9417                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
9418                 write_tlv_fields!(writer, {
9419                         (1, self.inbound_scid_alias, option),
9420                         (2, self.channel_id, required),
9421                         (3, self.channel_type, option),
9422                         (4, self.counterparty, required),
9423                         (5, self.outbound_scid_alias, option),
9424                         (6, self.funding_txo, option),
9425                         (7, self.config, option),
9426                         (8, self.short_channel_id, option),
9427                         (9, self.confirmations, option),
9428                         (10, self.channel_value_satoshis, required),
9429                         (12, self.unspendable_punishment_reserve, option),
9430                         (14, user_channel_id_low, required),
9431                         (16, self.balance_msat, required),
9432                         (18, self.outbound_capacity_msat, required),
9433                         (19, self.next_outbound_htlc_limit_msat, required),
9434                         (20, self.inbound_capacity_msat, required),
9435                         (21, self.next_outbound_htlc_minimum_msat, required),
9436                         (22, self.confirmations_required, option),
9437                         (24, self.force_close_spend_delay, option),
9438                         (26, self.is_outbound, required),
9439                         (28, self.is_channel_ready, required),
9440                         (30, self.is_usable, required),
9441                         (32, self.is_public, required),
9442                         (33, self.inbound_htlc_minimum_msat, option),
9443                         (35, self.inbound_htlc_maximum_msat, option),
9444                         (37, user_channel_id_high_opt, option),
9445                         (39, self.feerate_sat_per_1000_weight, option),
9446                         (41, self.channel_shutdown_state, option),
9447                 });
9448                 Ok(())
9449         }
9450 }
9451
9452 impl Readable for ChannelDetails {
9453         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9454                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9455                         (1, inbound_scid_alias, option),
9456                         (2, channel_id, required),
9457                         (3, channel_type, option),
9458                         (4, counterparty, required),
9459                         (5, outbound_scid_alias, option),
9460                         (6, funding_txo, option),
9461                         (7, config, option),
9462                         (8, short_channel_id, option),
9463                         (9, confirmations, option),
9464                         (10, channel_value_satoshis, required),
9465                         (12, unspendable_punishment_reserve, option),
9466                         (14, user_channel_id_low, required),
9467                         (16, balance_msat, required),
9468                         (18, outbound_capacity_msat, required),
9469                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
9470                         // filled in, so we can safely unwrap it here.
9471                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
9472                         (20, inbound_capacity_msat, required),
9473                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
9474                         (22, confirmations_required, option),
9475                         (24, force_close_spend_delay, option),
9476                         (26, is_outbound, required),
9477                         (28, is_channel_ready, required),
9478                         (30, is_usable, required),
9479                         (32, is_public, required),
9480                         (33, inbound_htlc_minimum_msat, option),
9481                         (35, inbound_htlc_maximum_msat, option),
9482                         (37, user_channel_id_high_opt, option),
9483                         (39, feerate_sat_per_1000_weight, option),
9484                         (41, channel_shutdown_state, option),
9485                 });
9486
9487                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9488                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9489                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
9490                 let user_channel_id = user_channel_id_low as u128 +
9491                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
9492
9493                 Ok(Self {
9494                         inbound_scid_alias,
9495                         channel_id: channel_id.0.unwrap(),
9496                         channel_type,
9497                         counterparty: counterparty.0.unwrap(),
9498                         outbound_scid_alias,
9499                         funding_txo,
9500                         config,
9501                         short_channel_id,
9502                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
9503                         unspendable_punishment_reserve,
9504                         user_channel_id,
9505                         balance_msat: balance_msat.0.unwrap(),
9506                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
9507                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
9508                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
9509                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
9510                         confirmations_required,
9511                         confirmations,
9512                         force_close_spend_delay,
9513                         is_outbound: is_outbound.0.unwrap(),
9514                         is_channel_ready: is_channel_ready.0.unwrap(),
9515                         is_usable: is_usable.0.unwrap(),
9516                         is_public: is_public.0.unwrap(),
9517                         inbound_htlc_minimum_msat,
9518                         inbound_htlc_maximum_msat,
9519                         feerate_sat_per_1000_weight,
9520                         channel_shutdown_state,
9521                 })
9522         }
9523 }
9524
9525 impl_writeable_tlv_based!(PhantomRouteHints, {
9526         (2, channels, required_vec),
9527         (4, phantom_scid, required),
9528         (6, real_node_pubkey, required),
9529 });
9530
9531 impl_writeable_tlv_based!(BlindedForward, {
9532         (0, inbound_blinding_point, required),
9533         (1, failure, (default_value, BlindedFailure::FromIntroductionNode)),
9534 });
9535
9536 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
9537         (0, Forward) => {
9538                 (0, onion_packet, required),
9539                 (1, blinded, option),
9540                 (2, short_channel_id, required),
9541         },
9542         (1, Receive) => {
9543                 (0, payment_data, required),
9544                 (1, phantom_shared_secret, option),
9545                 (2, incoming_cltv_expiry, required),
9546                 (3, payment_metadata, option),
9547                 (5, custom_tlvs, optional_vec),
9548                 (7, requires_blinded_error, (default_value, false)),
9549         },
9550         (2, ReceiveKeysend) => {
9551                 (0, payment_preimage, required),
9552                 (2, incoming_cltv_expiry, required),
9553                 (3, payment_metadata, option),
9554                 (4, payment_data, option), // Added in 0.0.116
9555                 (5, custom_tlvs, optional_vec),
9556         },
9557 ;);
9558
9559 impl_writeable_tlv_based!(PendingHTLCInfo, {
9560         (0, routing, required),
9561         (2, incoming_shared_secret, required),
9562         (4, payment_hash, required),
9563         (6, outgoing_amt_msat, required),
9564         (8, outgoing_cltv_value, required),
9565         (9, incoming_amt_msat, option),
9566         (10, skimmed_fee_msat, option),
9567 });
9568
9569
9570 impl Writeable for HTLCFailureMsg {
9571         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9572                 match self {
9573                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9574                                 0u8.write(writer)?;
9575                                 channel_id.write(writer)?;
9576                                 htlc_id.write(writer)?;
9577                                 reason.write(writer)?;
9578                         },
9579                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9580                                 channel_id, htlc_id, sha256_of_onion, failure_code
9581                         }) => {
9582                                 1u8.write(writer)?;
9583                                 channel_id.write(writer)?;
9584                                 htlc_id.write(writer)?;
9585                                 sha256_of_onion.write(writer)?;
9586                                 failure_code.write(writer)?;
9587                         },
9588                 }
9589                 Ok(())
9590         }
9591 }
9592
9593 impl Readable for HTLCFailureMsg {
9594         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9595                 let id: u8 = Readable::read(reader)?;
9596                 match id {
9597                         0 => {
9598                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9599                                         channel_id: Readable::read(reader)?,
9600                                         htlc_id: Readable::read(reader)?,
9601                                         reason: Readable::read(reader)?,
9602                                 }))
9603                         },
9604                         1 => {
9605                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9606                                         channel_id: Readable::read(reader)?,
9607                                         htlc_id: Readable::read(reader)?,
9608                                         sha256_of_onion: Readable::read(reader)?,
9609                                         failure_code: Readable::read(reader)?,
9610                                 }))
9611                         },
9612                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9613                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9614                         // messages contained in the variants.
9615                         // In version 0.0.101, support for reading the variants with these types was added, and
9616                         // we should migrate to writing these variants when UpdateFailHTLC or
9617                         // UpdateFailMalformedHTLC get TLV fields.
9618                         2 => {
9619                                 let length: BigSize = Readable::read(reader)?;
9620                                 let mut s = FixedLengthReader::new(reader, length.0);
9621                                 let res = Readable::read(&mut s)?;
9622                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9623                                 Ok(HTLCFailureMsg::Relay(res))
9624                         },
9625                         3 => {
9626                                 let length: BigSize = Readable::read(reader)?;
9627                                 let mut s = FixedLengthReader::new(reader, length.0);
9628                                 let res = Readable::read(&mut s)?;
9629                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9630                                 Ok(HTLCFailureMsg::Malformed(res))
9631                         },
9632                         _ => Err(DecodeError::UnknownRequiredFeature),
9633                 }
9634         }
9635 }
9636
9637 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9638         (0, Forward),
9639         (1, Fail),
9640 );
9641
9642 impl_writeable_tlv_based_enum!(BlindedFailure,
9643         (0, FromIntroductionNode) => {},
9644         (2, FromBlindedNode) => {}, ;
9645 );
9646
9647 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9648         (0, short_channel_id, required),
9649         (1, phantom_shared_secret, option),
9650         (2, outpoint, required),
9651         (3, blinded_failure, option),
9652         (4, htlc_id, required),
9653         (6, incoming_packet_shared_secret, required),
9654         (7, user_channel_id, option),
9655 });
9656
9657 impl Writeable for ClaimableHTLC {
9658         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9659                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9660                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9661                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9662                 };
9663                 write_tlv_fields!(writer, {
9664                         (0, self.prev_hop, required),
9665                         (1, self.total_msat, required),
9666                         (2, self.value, required),
9667                         (3, self.sender_intended_value, required),
9668                         (4, payment_data, option),
9669                         (5, self.total_value_received, option),
9670                         (6, self.cltv_expiry, required),
9671                         (8, keysend_preimage, option),
9672                         (10, self.counterparty_skimmed_fee_msat, option),
9673                 });
9674                 Ok(())
9675         }
9676 }
9677
9678 impl Readable for ClaimableHTLC {
9679         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9680                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9681                         (0, prev_hop, required),
9682                         (1, total_msat, option),
9683                         (2, value_ser, required),
9684                         (3, sender_intended_value, option),
9685                         (4, payment_data_opt, option),
9686                         (5, total_value_received, option),
9687                         (6, cltv_expiry, required),
9688                         (8, keysend_preimage, option),
9689                         (10, counterparty_skimmed_fee_msat, option),
9690                 });
9691                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9692                 let value = value_ser.0.unwrap();
9693                 let onion_payload = match keysend_preimage {
9694                         Some(p) => {
9695                                 if payment_data.is_some() {
9696                                         return Err(DecodeError::InvalidValue)
9697                                 }
9698                                 if total_msat.is_none() {
9699                                         total_msat = Some(value);
9700                                 }
9701                                 OnionPayload::Spontaneous(p)
9702                         },
9703                         None => {
9704                                 if total_msat.is_none() {
9705                                         if payment_data.is_none() {
9706                                                 return Err(DecodeError::InvalidValue)
9707                                         }
9708                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9709                                 }
9710                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9711                         },
9712                 };
9713                 Ok(Self {
9714                         prev_hop: prev_hop.0.unwrap(),
9715                         timer_ticks: 0,
9716                         value,
9717                         sender_intended_value: sender_intended_value.unwrap_or(value),
9718                         total_value_received,
9719                         total_msat: total_msat.unwrap(),
9720                         onion_payload,
9721                         cltv_expiry: cltv_expiry.0.unwrap(),
9722                         counterparty_skimmed_fee_msat,
9723                 })
9724         }
9725 }
9726
9727 impl Readable for HTLCSource {
9728         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9729                 let id: u8 = Readable::read(reader)?;
9730                 match id {
9731                         0 => {
9732                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9733                                 let mut first_hop_htlc_msat: u64 = 0;
9734                                 let mut path_hops = Vec::new();
9735                                 let mut payment_id = None;
9736                                 let mut payment_params: Option<PaymentParameters> = None;
9737                                 let mut blinded_tail: Option<BlindedTail> = None;
9738                                 read_tlv_fields!(reader, {
9739                                         (0, session_priv, required),
9740                                         (1, payment_id, option),
9741                                         (2, first_hop_htlc_msat, required),
9742                                         (4, path_hops, required_vec),
9743                                         (5, payment_params, (option: ReadableArgs, 0)),
9744                                         (6, blinded_tail, option),
9745                                 });
9746                                 if payment_id.is_none() {
9747                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9748                                         // instead.
9749                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9750                                 }
9751                                 let path = Path { hops: path_hops, blinded_tail };
9752                                 if path.hops.len() == 0 {
9753                                         return Err(DecodeError::InvalidValue);
9754                                 }
9755                                 if let Some(params) = payment_params.as_mut() {
9756                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9757                                                 if final_cltv_expiry_delta == &0 {
9758                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9759                                                 }
9760                                         }
9761                                 }
9762                                 Ok(HTLCSource::OutboundRoute {
9763                                         session_priv: session_priv.0.unwrap(),
9764                                         first_hop_htlc_msat,
9765                                         path,
9766                                         payment_id: payment_id.unwrap(),
9767                                 })
9768                         }
9769                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9770                         _ => Err(DecodeError::UnknownRequiredFeature),
9771                 }
9772         }
9773 }
9774
9775 impl Writeable for HTLCSource {
9776         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9777                 match self {
9778                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9779                                 0u8.write(writer)?;
9780                                 let payment_id_opt = Some(payment_id);
9781                                 write_tlv_fields!(writer, {
9782                                         (0, session_priv, required),
9783                                         (1, payment_id_opt, option),
9784                                         (2, first_hop_htlc_msat, required),
9785                                         // 3 was previously used to write a PaymentSecret for the payment.
9786                                         (4, path.hops, required_vec),
9787                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9788                                         (6, path.blinded_tail, option),
9789                                  });
9790                         }
9791                         HTLCSource::PreviousHopData(ref field) => {
9792                                 1u8.write(writer)?;
9793                                 field.write(writer)?;
9794                         }
9795                 }
9796                 Ok(())
9797         }
9798 }
9799
9800 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9801         (0, forward_info, required),
9802         (1, prev_user_channel_id, (default_value, 0)),
9803         (2, prev_short_channel_id, required),
9804         (4, prev_htlc_id, required),
9805         (6, prev_funding_outpoint, required),
9806 });
9807
9808 impl Writeable for HTLCForwardInfo {
9809         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9810                 const FAIL_HTLC_VARIANT_ID: u8 = 1;
9811                 match self {
9812                         Self::AddHTLC(info) => {
9813                                 0u8.write(w)?;
9814                                 info.write(w)?;
9815                         },
9816                         Self::FailHTLC { htlc_id, err_packet } => {
9817                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9818                                 write_tlv_fields!(w, {
9819                                         (0, htlc_id, required),
9820                                         (2, err_packet, required),
9821                                 });
9822                         },
9823                         Self::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
9824                                 // Since this variant was added in 0.0.119, write this as `::FailHTLC` with an empty error
9825                                 // packet so older versions have something to fail back with, but serialize the real data as
9826                                 // optional TLVs for the benefit of newer versions.
9827                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9828                                 let dummy_err_packet = msgs::OnionErrorPacket { data: Vec::new() };
9829                                 write_tlv_fields!(w, {
9830                                         (0, htlc_id, required),
9831                                         (1, failure_code, required),
9832                                         (2, dummy_err_packet, required),
9833                                         (3, sha256_of_onion, required),
9834                                 });
9835                         },
9836                 }
9837                 Ok(())
9838         }
9839 }
9840
9841 impl Readable for HTLCForwardInfo {
9842         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
9843                 let id: u8 = Readable::read(r)?;
9844                 Ok(match id {
9845                         0 => Self::AddHTLC(Readable::read(r)?),
9846                         1 => {
9847                                 _init_and_read_len_prefixed_tlv_fields!(r, {
9848                                         (0, htlc_id, required),
9849                                         (1, malformed_htlc_failure_code, option),
9850                                         (2, err_packet, required),
9851                                         (3, sha256_of_onion, option),
9852                                 });
9853                                 if let Some(failure_code) = malformed_htlc_failure_code {
9854                                         Self::FailMalformedHTLC {
9855                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
9856                                                 failure_code,
9857                                                 sha256_of_onion: sha256_of_onion.ok_or(DecodeError::InvalidValue)?,
9858                                         }
9859                                 } else {
9860                                         Self::FailHTLC {
9861                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
9862                                                 err_packet: _init_tlv_based_struct_field!(err_packet, required),
9863                                         }
9864                                 }
9865                         },
9866                         _ => return Err(DecodeError::InvalidValue),
9867                 })
9868         }
9869 }
9870
9871 impl_writeable_tlv_based!(PendingInboundPayment, {
9872         (0, payment_secret, required),
9873         (2, expiry_time, required),
9874         (4, user_payment_id, required),
9875         (6, payment_preimage, required),
9876         (8, min_value_msat, required),
9877 });
9878
9879 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>
9880 where
9881         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9882         T::Target: BroadcasterInterface,
9883         ES::Target: EntropySource,
9884         NS::Target: NodeSigner,
9885         SP::Target: SignerProvider,
9886         F::Target: FeeEstimator,
9887         R::Target: Router,
9888         L::Target: Logger,
9889 {
9890         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9891                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9892
9893                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9894
9895                 self.chain_hash.write(writer)?;
9896                 {
9897                         let best_block = self.best_block.read().unwrap();
9898                         best_block.height().write(writer)?;
9899                         best_block.block_hash().write(writer)?;
9900                 }
9901
9902                 let mut serializable_peer_count: u64 = 0;
9903                 {
9904                         let per_peer_state = self.per_peer_state.read().unwrap();
9905                         let mut number_of_funded_channels = 0;
9906                         for (_, peer_state_mutex) in per_peer_state.iter() {
9907                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9908                                 let peer_state = &mut *peer_state_lock;
9909                                 if !peer_state.ok_to_remove(false) {
9910                                         serializable_peer_count += 1;
9911                                 }
9912
9913                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9914                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9915                                 ).count();
9916                         }
9917
9918                         (number_of_funded_channels as u64).write(writer)?;
9919
9920                         for (_, peer_state_mutex) in per_peer_state.iter() {
9921                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9922                                 let peer_state = &mut *peer_state_lock;
9923                                 for channel in peer_state.channel_by_id.iter().filter_map(
9924                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9925                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9926                                         } else { None }
9927                                 ) {
9928                                         channel.write(writer)?;
9929                                 }
9930                         }
9931                 }
9932
9933                 {
9934                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9935                         (forward_htlcs.len() as u64).write(writer)?;
9936                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9937                                 short_channel_id.write(writer)?;
9938                                 (pending_forwards.len() as u64).write(writer)?;
9939                                 for forward in pending_forwards {
9940                                         forward.write(writer)?;
9941                                 }
9942                         }
9943                 }
9944
9945                 let per_peer_state = self.per_peer_state.write().unwrap();
9946
9947                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9948                 let claimable_payments = self.claimable_payments.lock().unwrap();
9949                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9950
9951                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9952                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9953                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9954                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9955                         payment_hash.write(writer)?;
9956                         (payment.htlcs.len() as u64).write(writer)?;
9957                         for htlc in payment.htlcs.iter() {
9958                                 htlc.write(writer)?;
9959                         }
9960                         htlc_purposes.push(&payment.purpose);
9961                         htlc_onion_fields.push(&payment.onion_fields);
9962                 }
9963
9964                 let mut monitor_update_blocked_actions_per_peer = None;
9965                 let mut peer_states = Vec::new();
9966                 for (_, peer_state_mutex) in per_peer_state.iter() {
9967                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9968                         // of a lockorder violation deadlock - no other thread can be holding any
9969                         // per_peer_state lock at all.
9970                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9971                 }
9972
9973                 (serializable_peer_count).write(writer)?;
9974                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9975                         // Peers which we have no channels to should be dropped once disconnected. As we
9976                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9977                         // consider all peers as disconnected here. There's therefore no need write peers with
9978                         // no channels.
9979                         if !peer_state.ok_to_remove(false) {
9980                                 peer_pubkey.write(writer)?;
9981                                 peer_state.latest_features.write(writer)?;
9982                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9983                                         monitor_update_blocked_actions_per_peer
9984                                                 .get_or_insert_with(Vec::new)
9985                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9986                                 }
9987                         }
9988                 }
9989
9990                 let events = self.pending_events.lock().unwrap();
9991                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9992                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9993                 // refuse to read the new ChannelManager.
9994                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9995                 if events_not_backwards_compatible {
9996                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9997                         // well save the space and not write any events here.
9998                         0u64.write(writer)?;
9999                 } else {
10000                         (events.len() as u64).write(writer)?;
10001                         for (event, _) in events.iter() {
10002                                 event.write(writer)?;
10003                         }
10004                 }
10005
10006                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
10007                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
10008                 // the closing monitor updates were always effectively replayed on startup (either directly
10009                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
10010                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
10011                 0u64.write(writer)?;
10012
10013                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
10014                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
10015                 // likely to be identical.
10016                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10017                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10018
10019                 (pending_inbound_payments.len() as u64).write(writer)?;
10020                 for (hash, pending_payment) in pending_inbound_payments.iter() {
10021                         hash.write(writer)?;
10022                         pending_payment.write(writer)?;
10023                 }
10024
10025                 // For backwards compat, write the session privs and their total length.
10026                 let mut num_pending_outbounds_compat: u64 = 0;
10027                 for (_, outbound) in pending_outbound_payments.iter() {
10028                         if !outbound.is_fulfilled() && !outbound.abandoned() {
10029                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
10030                         }
10031                 }
10032                 num_pending_outbounds_compat.write(writer)?;
10033                 for (_, outbound) in pending_outbound_payments.iter() {
10034                         match outbound {
10035                                 PendingOutboundPayment::Legacy { session_privs } |
10036                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10037                                         for session_priv in session_privs.iter() {
10038                                                 session_priv.write(writer)?;
10039                                         }
10040                                 }
10041                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
10042                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
10043                                 PendingOutboundPayment::Fulfilled { .. } => {},
10044                                 PendingOutboundPayment::Abandoned { .. } => {},
10045                         }
10046                 }
10047
10048                 // Encode without retry info for 0.0.101 compatibility.
10049                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
10050                 for (id, outbound) in pending_outbound_payments.iter() {
10051                         match outbound {
10052                                 PendingOutboundPayment::Legacy { session_privs } |
10053                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10054                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
10055                                 },
10056                                 _ => {},
10057                         }
10058                 }
10059
10060                 let mut pending_intercepted_htlcs = None;
10061                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
10062                 if our_pending_intercepts.len() != 0 {
10063                         pending_intercepted_htlcs = Some(our_pending_intercepts);
10064                 }
10065
10066                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
10067                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
10068                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
10069                         // map. Thus, if there are no entries we skip writing a TLV for it.
10070                         pending_claiming_payments = None;
10071                 }
10072
10073                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
10074                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
10075                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
10076                                 if !updates.is_empty() {
10077                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
10078                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
10079                                 }
10080                         }
10081                 }
10082
10083                 write_tlv_fields!(writer, {
10084                         (1, pending_outbound_payments_no_retry, required),
10085                         (2, pending_intercepted_htlcs, option),
10086                         (3, pending_outbound_payments, required),
10087                         (4, pending_claiming_payments, option),
10088                         (5, self.our_network_pubkey, required),
10089                         (6, monitor_update_blocked_actions_per_peer, option),
10090                         (7, self.fake_scid_rand_bytes, required),
10091                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
10092                         (9, htlc_purposes, required_vec),
10093                         (10, in_flight_monitor_updates, option),
10094                         (11, self.probing_cookie_secret, required),
10095                         (13, htlc_onion_fields, optional_vec),
10096                 });
10097
10098                 Ok(())
10099         }
10100 }
10101
10102 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
10103         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
10104                 (self.len() as u64).write(w)?;
10105                 for (event, action) in self.iter() {
10106                         event.write(w)?;
10107                         action.write(w)?;
10108                         #[cfg(debug_assertions)] {
10109                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
10110                                 // be persisted and are regenerated on restart. However, if such an event has a
10111                                 // post-event-handling action we'll write nothing for the event and would have to
10112                                 // either forget the action or fail on deserialization (which we do below). Thus,
10113                                 // check that the event is sane here.
10114                                 let event_encoded = event.encode();
10115                                 let event_read: Option<Event> =
10116                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
10117                                 if action.is_some() { assert!(event_read.is_some()); }
10118                         }
10119                 }
10120                 Ok(())
10121         }
10122 }
10123 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
10124         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
10125                 let len: u64 = Readable::read(reader)?;
10126                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
10127                 let mut events: Self = VecDeque::with_capacity(cmp::min(
10128                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
10129                         len) as usize);
10130                 for _ in 0..len {
10131                         let ev_opt = MaybeReadable::read(reader)?;
10132                         let action = Readable::read(reader)?;
10133                         if let Some(ev) = ev_opt {
10134                                 events.push_back((ev, action));
10135                         } else if action.is_some() {
10136                                 return Err(DecodeError::InvalidValue);
10137                         }
10138                 }
10139                 Ok(events)
10140         }
10141 }
10142
10143 impl_writeable_tlv_based_enum!(ChannelShutdownState,
10144         (0, NotShuttingDown) => {},
10145         (2, ShutdownInitiated) => {},
10146         (4, ResolvingHTLCs) => {},
10147         (6, NegotiatingClosingFee) => {},
10148         (8, ShutdownComplete) => {}, ;
10149 );
10150
10151 /// Arguments for the creation of a ChannelManager that are not deserialized.
10152 ///
10153 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
10154 /// is:
10155 /// 1) Deserialize all stored [`ChannelMonitor`]s.
10156 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
10157 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
10158 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
10159 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
10160 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
10161 ///    same way you would handle a [`chain::Filter`] call using
10162 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
10163 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
10164 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
10165 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
10166 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
10167 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
10168 ///    the next step.
10169 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
10170 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
10171 ///
10172 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
10173 /// call any other methods on the newly-deserialized [`ChannelManager`].
10174 ///
10175 /// Note that because some channels may be closed during deserialization, it is critical that you
10176 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
10177 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
10178 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
10179 /// not force-close the same channels but consider them live), you may end up revoking a state for
10180 /// which you've already broadcasted the transaction.
10181 ///
10182 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
10183 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10184 where
10185         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10186         T::Target: BroadcasterInterface,
10187         ES::Target: EntropySource,
10188         NS::Target: NodeSigner,
10189         SP::Target: SignerProvider,
10190         F::Target: FeeEstimator,
10191         R::Target: Router,
10192         L::Target: Logger,
10193 {
10194         /// A cryptographically secure source of entropy.
10195         pub entropy_source: ES,
10196
10197         /// A signer that is able to perform node-scoped cryptographic operations.
10198         pub node_signer: NS,
10199
10200         /// The keys provider which will give us relevant keys. Some keys will be loaded during
10201         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
10202         /// signing data.
10203         pub signer_provider: SP,
10204
10205         /// The fee_estimator for use in the ChannelManager in the future.
10206         ///
10207         /// No calls to the FeeEstimator will be made during deserialization.
10208         pub fee_estimator: F,
10209         /// The chain::Watch for use in the ChannelManager in the future.
10210         ///
10211         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
10212         /// you have deserialized ChannelMonitors separately and will add them to your
10213         /// chain::Watch after deserializing this ChannelManager.
10214         pub chain_monitor: M,
10215
10216         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
10217         /// used to broadcast the latest local commitment transactions of channels which must be
10218         /// force-closed during deserialization.
10219         pub tx_broadcaster: T,
10220         /// The router which will be used in the ChannelManager in the future for finding routes
10221         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
10222         ///
10223         /// No calls to the router will be made during deserialization.
10224         pub router: R,
10225         /// The Logger for use in the ChannelManager and which may be used to log information during
10226         /// deserialization.
10227         pub logger: L,
10228         /// Default settings used for new channels. Any existing channels will continue to use the
10229         /// runtime settings which were stored when the ChannelManager was serialized.
10230         pub default_config: UserConfig,
10231
10232         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
10233         /// value.context.get_funding_txo() should be the key).
10234         ///
10235         /// If a monitor is inconsistent with the channel state during deserialization the channel will
10236         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
10237         /// is true for missing channels as well. If there is a monitor missing for which we find
10238         /// channel data Err(DecodeError::InvalidValue) will be returned.
10239         ///
10240         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
10241         /// this struct.
10242         ///
10243         /// This is not exported to bindings users because we have no HashMap bindings
10244         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>,
10245 }
10246
10247 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10248                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
10249 where
10250         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10251         T::Target: BroadcasterInterface,
10252         ES::Target: EntropySource,
10253         NS::Target: NodeSigner,
10254         SP::Target: SignerProvider,
10255         F::Target: FeeEstimator,
10256         R::Target: Router,
10257         L::Target: Logger,
10258 {
10259         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
10260         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
10261         /// populate a HashMap directly from C.
10262         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,
10263                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>) -> Self {
10264                 Self {
10265                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
10266                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
10267                 }
10268         }
10269 }
10270
10271 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
10272 // SipmleArcChannelManager type:
10273 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10274         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
10275 where
10276         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10277         T::Target: BroadcasterInterface,
10278         ES::Target: EntropySource,
10279         NS::Target: NodeSigner,
10280         SP::Target: SignerProvider,
10281         F::Target: FeeEstimator,
10282         R::Target: Router,
10283         L::Target: Logger,
10284 {
10285         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10286                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
10287                 Ok((blockhash, Arc::new(chan_manager)))
10288         }
10289 }
10290
10291 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10292         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
10293 where
10294         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10295         T::Target: BroadcasterInterface,
10296         ES::Target: EntropySource,
10297         NS::Target: NodeSigner,
10298         SP::Target: SignerProvider,
10299         F::Target: FeeEstimator,
10300         R::Target: Router,
10301         L::Target: Logger,
10302 {
10303         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10304                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
10305
10306                 let chain_hash: ChainHash = Readable::read(reader)?;
10307                 let best_block_height: u32 = Readable::read(reader)?;
10308                 let best_block_hash: BlockHash = Readable::read(reader)?;
10309
10310                 let mut failed_htlcs = Vec::new();
10311
10312                 let channel_count: u64 = Readable::read(reader)?;
10313                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
10314                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10315                 let mut outpoint_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10316                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10317                 let mut channel_closures = VecDeque::new();
10318                 let mut close_background_events = Vec::new();
10319                 for _ in 0..channel_count {
10320                         let mut channel: Channel<SP> = Channel::read(reader, (
10321                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
10322                         ))?;
10323                         let logger = WithChannelContext::from(&args.logger, &channel.context);
10324                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10325                         funding_txo_set.insert(funding_txo.clone());
10326                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10327                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
10328                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
10329                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
10330                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10331                                         // But if the channel is behind of the monitor, close the channel:
10332                                         log_error!(logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
10333                                         log_error!(logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
10334                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10335                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
10336                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
10337                                         }
10338                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
10339                                                 log_error!(logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
10340                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
10341                                         }
10342                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
10343                                                 log_error!(logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
10344                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
10345                                         }
10346                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
10347                                                 log_error!(logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
10348                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
10349                                         }
10350                                         let mut shutdown_result = channel.context.force_shutdown(true, ClosureReason::OutdatedChannelManager);
10351                                         if shutdown_result.unbroadcasted_batch_funding_txid.is_some() {
10352                                                 return Err(DecodeError::InvalidValue);
10353                                         }
10354                                         if let Some((counterparty_node_id, funding_txo, update)) = shutdown_result.monitor_update {
10355                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10356                                                         counterparty_node_id, funding_txo, update
10357                                                 });
10358                                         }
10359                                         failed_htlcs.append(&mut shutdown_result.dropped_outbound_htlcs);
10360                                         channel_closures.push_back((events::Event::ChannelClosed {
10361                                                 channel_id: channel.context.channel_id(),
10362                                                 user_channel_id: channel.context.get_user_id(),
10363                                                 reason: ClosureReason::OutdatedChannelManager,
10364                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10365                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10366                                                 channel_funding_txo: channel.context.get_funding_txo(),
10367                                         }, None));
10368                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
10369                                                 let mut found_htlc = false;
10370                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
10371                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
10372                                                 }
10373                                                 if !found_htlc {
10374                                                         // If we have some HTLCs in the channel which are not present in the newer
10375                                                         // ChannelMonitor, they have been removed and should be failed back to
10376                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
10377                                                         // were actually claimed we'd have generated and ensured the previous-hop
10378                                                         // claim update ChannelMonitor updates were persisted prior to persising
10379                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
10380                                                         // backwards leg of the HTLC will simply be rejected.
10381                                                         log_info!(logger,
10382                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
10383                                                                 &channel.context.channel_id(), &payment_hash);
10384                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10385                                                 }
10386                                         }
10387                                 } else {
10388                                         log_info!(logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
10389                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
10390                                                 monitor.get_latest_update_id());
10391                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
10392                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10393                                         }
10394                                         if let Some(funding_txo) = channel.context.get_funding_txo() {
10395                                                 outpoint_to_peer.insert(funding_txo, channel.context.get_counterparty_node_id());
10396                                         }
10397                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
10398                                                 hash_map::Entry::Occupied(mut entry) => {
10399                                                         let by_id_map = entry.get_mut();
10400                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10401                                                 },
10402                                                 hash_map::Entry::Vacant(entry) => {
10403                                                         let mut by_id_map = HashMap::new();
10404                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10405                                                         entry.insert(by_id_map);
10406                                                 }
10407                                         }
10408                                 }
10409                         } else if channel.is_awaiting_initial_mon_persist() {
10410                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
10411                                 // was in-progress, we never broadcasted the funding transaction and can still
10412                                 // safely discard the channel.
10413                                 let _ = channel.context.force_shutdown(false, ClosureReason::DisconnectedPeer);
10414                                 channel_closures.push_back((events::Event::ChannelClosed {
10415                                         channel_id: channel.context.channel_id(),
10416                                         user_channel_id: channel.context.get_user_id(),
10417                                         reason: ClosureReason::DisconnectedPeer,
10418                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10419                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10420                                         channel_funding_txo: channel.context.get_funding_txo(),
10421                                 }, None));
10422                         } else {
10423                                 log_error!(logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
10424                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10425                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10426                                 log_error!(logger, " Without the ChannelMonitor we cannot continue without risking funds.");
10427                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10428                                 return Err(DecodeError::InvalidValue);
10429                         }
10430                 }
10431
10432                 for (funding_txo, monitor) in args.channel_monitors.iter() {
10433                         if !funding_txo_set.contains(funding_txo) {
10434                                 let logger = WithChannelMonitor::from(&args.logger, monitor);
10435                                 log_info!(logger, "Queueing monitor update to ensure missing channel {} is force closed",
10436                                         &funding_txo.to_channel_id());
10437                                 let monitor_update = ChannelMonitorUpdate {
10438                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
10439                                         counterparty_node_id: None,
10440                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
10441                                 };
10442                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
10443                         }
10444                 }
10445
10446                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
10447                 let forward_htlcs_count: u64 = Readable::read(reader)?;
10448                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
10449                 for _ in 0..forward_htlcs_count {
10450                         let short_channel_id = Readable::read(reader)?;
10451                         let pending_forwards_count: u64 = Readable::read(reader)?;
10452                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
10453                         for _ in 0..pending_forwards_count {
10454                                 pending_forwards.push(Readable::read(reader)?);
10455                         }
10456                         forward_htlcs.insert(short_channel_id, pending_forwards);
10457                 }
10458
10459                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
10460                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
10461                 for _ in 0..claimable_htlcs_count {
10462                         let payment_hash = Readable::read(reader)?;
10463                         let previous_hops_len: u64 = Readable::read(reader)?;
10464                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
10465                         for _ in 0..previous_hops_len {
10466                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
10467                         }
10468                         claimable_htlcs_list.push((payment_hash, previous_hops));
10469                 }
10470
10471                 let peer_state_from_chans = |channel_by_id| {
10472                         PeerState {
10473                                 channel_by_id,
10474                                 inbound_channel_request_by_id: HashMap::new(),
10475                                 latest_features: InitFeatures::empty(),
10476                                 pending_msg_events: Vec::new(),
10477                                 in_flight_monitor_updates: BTreeMap::new(),
10478                                 monitor_update_blocked_actions: BTreeMap::new(),
10479                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
10480                                 is_connected: false,
10481                         }
10482                 };
10483
10484                 let peer_count: u64 = Readable::read(reader)?;
10485                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
10486                 for _ in 0..peer_count {
10487                         let peer_pubkey = Readable::read(reader)?;
10488                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
10489                         let mut peer_state = peer_state_from_chans(peer_chans);
10490                         peer_state.latest_features = Readable::read(reader)?;
10491                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
10492                 }
10493
10494                 let event_count: u64 = Readable::read(reader)?;
10495                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
10496                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
10497                 for _ in 0..event_count {
10498                         match MaybeReadable::read(reader)? {
10499                                 Some(event) => pending_events_read.push_back((event, None)),
10500                                 None => continue,
10501                         }
10502                 }
10503
10504                 let background_event_count: u64 = Readable::read(reader)?;
10505                 for _ in 0..background_event_count {
10506                         match <u8 as Readable>::read(reader)? {
10507                                 0 => {
10508                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
10509                                         // however we really don't (and never did) need them - we regenerate all
10510                                         // on-startup monitor updates.
10511                                         let _: OutPoint = Readable::read(reader)?;
10512                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
10513                                 }
10514                                 _ => return Err(DecodeError::InvalidValue),
10515                         }
10516                 }
10517
10518                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
10519                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
10520
10521                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
10522                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
10523                 for _ in 0..pending_inbound_payment_count {
10524                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
10525                                 return Err(DecodeError::InvalidValue);
10526                         }
10527                 }
10528
10529                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
10530                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
10531                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
10532                 for _ in 0..pending_outbound_payments_count_compat {
10533                         let session_priv = Readable::read(reader)?;
10534                         let payment = PendingOutboundPayment::Legacy {
10535                                 session_privs: [session_priv].iter().cloned().collect()
10536                         };
10537                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
10538                                 return Err(DecodeError::InvalidValue)
10539                         };
10540                 }
10541
10542                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
10543                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
10544                 let mut pending_outbound_payments = None;
10545                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
10546                 let mut received_network_pubkey: Option<PublicKey> = None;
10547                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
10548                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
10549                 let mut claimable_htlc_purposes = None;
10550                 let mut claimable_htlc_onion_fields = None;
10551                 let mut pending_claiming_payments = Some(HashMap::new());
10552                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
10553                 let mut events_override = None;
10554                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
10555                 read_tlv_fields!(reader, {
10556                         (1, pending_outbound_payments_no_retry, option),
10557                         (2, pending_intercepted_htlcs, option),
10558                         (3, pending_outbound_payments, option),
10559                         (4, pending_claiming_payments, option),
10560                         (5, received_network_pubkey, option),
10561                         (6, monitor_update_blocked_actions_per_peer, option),
10562                         (7, fake_scid_rand_bytes, option),
10563                         (8, events_override, option),
10564                         (9, claimable_htlc_purposes, optional_vec),
10565                         (10, in_flight_monitor_updates, option),
10566                         (11, probing_cookie_secret, option),
10567                         (13, claimable_htlc_onion_fields, optional_vec),
10568                 });
10569                 if fake_scid_rand_bytes.is_none() {
10570                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
10571                 }
10572
10573                 if probing_cookie_secret.is_none() {
10574                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
10575                 }
10576
10577                 if let Some(events) = events_override {
10578                         pending_events_read = events;
10579                 }
10580
10581                 if !channel_closures.is_empty() {
10582                         pending_events_read.append(&mut channel_closures);
10583                 }
10584
10585                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
10586                         pending_outbound_payments = Some(pending_outbound_payments_compat);
10587                 } else if pending_outbound_payments.is_none() {
10588                         let mut outbounds = HashMap::new();
10589                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
10590                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
10591                         }
10592                         pending_outbound_payments = Some(outbounds);
10593                 }
10594                 let pending_outbounds = OutboundPayments {
10595                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
10596                         retry_lock: Mutex::new(())
10597                 };
10598
10599                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
10600                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
10601                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
10602                 // replayed, and for each monitor update we have to replay we have to ensure there's a
10603                 // `ChannelMonitor` for it.
10604                 //
10605                 // In order to do so we first walk all of our live channels (so that we can check their
10606                 // state immediately after doing the update replays, when we have the `update_id`s
10607                 // available) and then walk any remaining in-flight updates.
10608                 //
10609                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10610                 let mut pending_background_events = Vec::new();
10611                 macro_rules! handle_in_flight_updates {
10612                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10613                          $monitor: expr, $peer_state: expr, $logger: expr, $channel_info_log: expr
10614                         ) => { {
10615                                 let mut max_in_flight_update_id = 0;
10616                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10617                                 for update in $chan_in_flight_upds.iter() {
10618                                         log_trace!($logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10619                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
10620                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10621                                         pending_background_events.push(
10622                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10623                                                         counterparty_node_id: $counterparty_node_id,
10624                                                         funding_txo: $funding_txo,
10625                                                         update: update.clone(),
10626                                                 });
10627                                 }
10628                                 if $chan_in_flight_upds.is_empty() {
10629                                         // We had some updates to apply, but it turns out they had completed before we
10630                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10631                                         // the completion actions for any monitor updates, but otherwise are done.
10632                                         pending_background_events.push(
10633                                                 BackgroundEvent::MonitorUpdatesComplete {
10634                                                         counterparty_node_id: $counterparty_node_id,
10635                                                         channel_id: $funding_txo.to_channel_id(),
10636                                                 });
10637                                 }
10638                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10639                                         log_error!($logger, "Duplicate in-flight monitor update set for the same channel!");
10640                                         return Err(DecodeError::InvalidValue);
10641                                 }
10642                                 max_in_flight_update_id
10643                         } }
10644                 }
10645
10646                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10647                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10648                         let peer_state = &mut *peer_state_lock;
10649                         for phase in peer_state.channel_by_id.values() {
10650                                 if let ChannelPhase::Funded(chan) = phase {
10651                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10652
10653                                         // Channels that were persisted have to be funded, otherwise they should have been
10654                                         // discarded.
10655                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10656                                         let monitor = args.channel_monitors.get(&funding_txo)
10657                                                 .expect("We already checked for monitor presence when loading channels");
10658                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10659                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10660                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10661                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10662                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10663                                                                         funding_txo, monitor, peer_state, logger, ""));
10664                                                 }
10665                                         }
10666                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10667                                                 // If the channel is ahead of the monitor, return InvalidValue:
10668                                                 log_error!(logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10669                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10670                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10671                                                 log_error!(logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10672                                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10673                                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10674                                                 log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10675                                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10676                                                 return Err(DecodeError::InvalidValue);
10677                                         }
10678                                 } else {
10679                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10680                                         // created in this `channel_by_id` map.
10681                                         debug_assert!(false);
10682                                         return Err(DecodeError::InvalidValue);
10683                                 }
10684                         }
10685                 }
10686
10687                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10688                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10689                                 let logger = WithContext::from(&args.logger, Some(counterparty_id), Some(funding_txo.to_channel_id()));
10690                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10691                                         // Now that we've removed all the in-flight monitor updates for channels that are
10692                                         // still open, we need to replay any monitor updates that are for closed channels,
10693                                         // creating the neccessary peer_state entries as we go.
10694                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10695                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
10696                                         });
10697                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10698                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10699                                                 funding_txo, monitor, peer_state, logger, "closed ");
10700                                 } else {
10701                                         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!");
10702                                         log_error!(logger, " The ChannelMonitor for channel {} is missing.",
10703                                                 &funding_txo.to_channel_id());
10704                                         log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10705                                         log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10706                                         log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10707                                         log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10708                                         return Err(DecodeError::InvalidValue);
10709                                 }
10710                         }
10711                 }
10712
10713                 // Note that we have to do the above replays before we push new monitor updates.
10714                 pending_background_events.append(&mut close_background_events);
10715
10716                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10717                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10718                 // have a fully-constructed `ChannelManager` at the end.
10719                 let mut pending_claims_to_replay = Vec::new();
10720
10721                 {
10722                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10723                         // ChannelMonitor data for any channels for which we do not have authorative state
10724                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10725                         // corresponding `Channel` at all).
10726                         // This avoids several edge-cases where we would otherwise "forget" about pending
10727                         // payments which are still in-flight via their on-chain state.
10728                         // We only rebuild the pending payments map if we were most recently serialized by
10729                         // 0.0.102+
10730                         for (_, monitor) in args.channel_monitors.iter() {
10731                                 let counterparty_opt = outpoint_to_peer.get(&monitor.get_funding_txo().0);
10732                                 if counterparty_opt.is_none() {
10733                                         let logger = WithChannelMonitor::from(&args.logger, monitor);
10734                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10735                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10736                                                         if path.hops.is_empty() {
10737                                                                 log_error!(logger, "Got an empty path for a pending payment");
10738                                                                 return Err(DecodeError::InvalidValue);
10739                                                         }
10740
10741                                                         let path_amt = path.final_value_msat();
10742                                                         let mut session_priv_bytes = [0; 32];
10743                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10744                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10745                                                                 hash_map::Entry::Occupied(mut entry) => {
10746                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10747                                                                         log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10748                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), htlc.payment_hash);
10749                                                                 },
10750                                                                 hash_map::Entry::Vacant(entry) => {
10751                                                                         let path_fee = path.fee_msat();
10752                                                                         entry.insert(PendingOutboundPayment::Retryable {
10753                                                                                 retry_strategy: None,
10754                                                                                 attempts: PaymentAttempts::new(),
10755                                                                                 payment_params: None,
10756                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
10757                                                                                 payment_hash: htlc.payment_hash,
10758                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10759                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10760                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10761                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10762                                                                                 pending_amt_msat: path_amt,
10763                                                                                 pending_fee_msat: Some(path_fee),
10764                                                                                 total_msat: path_amt,
10765                                                                                 starting_block_height: best_block_height,
10766                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10767                                                                         });
10768                                                                         log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10769                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10770                                                                 }
10771                                                         }
10772                                                 }
10773                                         }
10774                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10775                                                 match htlc_source {
10776                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10777                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10778                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10779                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10780                                                                 };
10781                                                                 // The ChannelMonitor is now responsible for this HTLC's
10782                                                                 // failure/success and will let us know what its outcome is. If we
10783                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10784                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10785                                                                 // the monitor was when forwarding the payment.
10786                                                                 forward_htlcs.retain(|_, forwards| {
10787                                                                         forwards.retain(|forward| {
10788                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10789                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10790                                                                                                 log_info!(logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10791                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10792                                                                                                 false
10793                                                                                         } else { true }
10794                                                                                 } else { true }
10795                                                                         });
10796                                                                         !forwards.is_empty()
10797                                                                 });
10798                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10799                                                                         if pending_forward_matches_htlc(&htlc_info) {
10800                                                                                 log_info!(logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10801                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10802                                                                                 pending_events_read.retain(|(event, _)| {
10803                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10804                                                                                                 intercepted_id != ev_id
10805                                                                                         } else { true }
10806                                                                                 });
10807                                                                                 false
10808                                                                         } else { true }
10809                                                                 });
10810                                                         },
10811                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10812                                                                 if let Some(preimage) = preimage_opt {
10813                                                                         let pending_events = Mutex::new(pending_events_read);
10814                                                                         // Note that we set `from_onchain` to "false" here,
10815                                                                         // deliberately keeping the pending payment around forever.
10816                                                                         // Given it should only occur when we have a channel we're
10817                                                                         // force-closing for being stale that's okay.
10818                                                                         // The alternative would be to wipe the state when claiming,
10819                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10820                                                                         // it and the `PaymentSent` on every restart until the
10821                                                                         // `ChannelMonitor` is removed.
10822                                                                         let compl_action =
10823                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10824                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10825                                                                                         counterparty_node_id: path.hops[0].pubkey,
10826                                                                                 };
10827                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10828                                                                                 path, false, compl_action, &pending_events, &&logger);
10829                                                                         pending_events_read = pending_events.into_inner().unwrap();
10830                                                                 }
10831                                                         },
10832                                                 }
10833                                         }
10834                                 }
10835
10836                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10837                                 // preimages from it which may be needed in upstream channels for forwarded
10838                                 // payments.
10839                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10840                                         .into_iter()
10841                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10842                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10843                                                         if let Some(payment_preimage) = preimage_opt {
10844                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10845                                                                         // Check if `counterparty_opt.is_none()` to see if the
10846                                                                         // downstream chan is closed (because we don't have a
10847                                                                         // channel_id -> peer map entry).
10848                                                                         counterparty_opt.is_none(),
10849                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10850                                                                         monitor.get_funding_txo().0))
10851                                                         } else { None }
10852                                                 } else {
10853                                                         // If it was an outbound payment, we've handled it above - if a preimage
10854                                                         // came in and we persisted the `ChannelManager` we either handled it and
10855                                                         // are good to go or the channel force-closed - we don't have to handle the
10856                                                         // channel still live case here.
10857                                                         None
10858                                                 }
10859                                         });
10860                                 for tuple in outbound_claimed_htlcs_iter {
10861                                         pending_claims_to_replay.push(tuple);
10862                                 }
10863                         }
10864                 }
10865
10866                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10867                         // If we have pending HTLCs to forward, assume we either dropped a
10868                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10869                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10870                         // constant as enough time has likely passed that we should simply handle the forwards
10871                         // now, or at least after the user gets a chance to reconnect to our peers.
10872                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10873                                 time_forwardable: Duration::from_secs(2),
10874                         }, None));
10875                 }
10876
10877                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10878                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10879
10880                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10881                 if let Some(purposes) = claimable_htlc_purposes {
10882                         if purposes.len() != claimable_htlcs_list.len() {
10883                                 return Err(DecodeError::InvalidValue);
10884                         }
10885                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10886                                 if onion_fields.len() != claimable_htlcs_list.len() {
10887                                         return Err(DecodeError::InvalidValue);
10888                                 }
10889                                 for (purpose, (onion, (payment_hash, htlcs))) in
10890                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10891                                 {
10892                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10893                                                 purpose, htlcs, onion_fields: onion,
10894                                         });
10895                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10896                                 }
10897                         } else {
10898                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10899                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10900                                                 purpose, htlcs, onion_fields: None,
10901                                         });
10902                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10903                                 }
10904                         }
10905                 } else {
10906                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10907                         // include a `_legacy_hop_data` in the `OnionPayload`.
10908                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10909                                 if htlcs.is_empty() {
10910                                         return Err(DecodeError::InvalidValue);
10911                                 }
10912                                 let purpose = match &htlcs[0].onion_payload {
10913                                         OnionPayload::Invoice { _legacy_hop_data } => {
10914                                                 if let Some(hop_data) = _legacy_hop_data {
10915                                                         events::PaymentPurpose::InvoicePayment {
10916                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10917                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10918                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10919                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10920                                                                                 Err(()) => {
10921                                                                                         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);
10922                                                                                         return Err(DecodeError::InvalidValue);
10923                                                                                 }
10924                                                                         }
10925                                                                 },
10926                                                                 payment_secret: hop_data.payment_secret,
10927                                                         }
10928                                                 } else { return Err(DecodeError::InvalidValue); }
10929                                         },
10930                                         OnionPayload::Spontaneous(payment_preimage) =>
10931                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10932                                 };
10933                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10934                                         purpose, htlcs, onion_fields: None,
10935                                 });
10936                         }
10937                 }
10938
10939                 let mut secp_ctx = Secp256k1::new();
10940                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10941
10942                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10943                         Ok(key) => key,
10944                         Err(()) => return Err(DecodeError::InvalidValue)
10945                 };
10946                 if let Some(network_pubkey) = received_network_pubkey {
10947                         if network_pubkey != our_network_pubkey {
10948                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10949                                 return Err(DecodeError::InvalidValue);
10950                         }
10951                 }
10952
10953                 let mut outbound_scid_aliases = HashSet::new();
10954                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10955                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10956                         let peer_state = &mut *peer_state_lock;
10957                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10958                                 if let ChannelPhase::Funded(chan) = phase {
10959                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10960                                         if chan.context.outbound_scid_alias() == 0 {
10961                                                 let mut outbound_scid_alias;
10962                                                 loop {
10963                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10964                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10965                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10966                                                 }
10967                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10968                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10969                                                 // Note that in rare cases its possible to hit this while reading an older
10970                                                 // channel if we just happened to pick a colliding outbound alias above.
10971                                                 log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10972                                                 return Err(DecodeError::InvalidValue);
10973                                         }
10974                                         if chan.context.is_usable() {
10975                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10976                                                         // Note that in rare cases its possible to hit this while reading an older
10977                                                         // channel if we just happened to pick a colliding outbound alias above.
10978                                                         log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10979                                                         return Err(DecodeError::InvalidValue);
10980                                                 }
10981                                         }
10982                                 } else {
10983                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10984                                         // created in this `channel_by_id` map.
10985                                         debug_assert!(false);
10986                                         return Err(DecodeError::InvalidValue);
10987                                 }
10988                         }
10989                 }
10990
10991                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10992
10993                 for (_, monitor) in args.channel_monitors.iter() {
10994                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10995                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10996                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10997                                         let mut claimable_amt_msat = 0;
10998                                         let mut receiver_node_id = Some(our_network_pubkey);
10999                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
11000                                         if phantom_shared_secret.is_some() {
11001                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
11002                                                         .expect("Failed to get node_id for phantom node recipient");
11003                                                 receiver_node_id = Some(phantom_pubkey)
11004                                         }
11005                                         for claimable_htlc in &payment.htlcs {
11006                                                 claimable_amt_msat += claimable_htlc.value;
11007
11008                                                 // Add a holding-cell claim of the payment to the Channel, which should be
11009                                                 // applied ~immediately on peer reconnection. Because it won't generate a
11010                                                 // new commitment transaction we can just provide the payment preimage to
11011                                                 // the corresponding ChannelMonitor and nothing else.
11012                                                 //
11013                                                 // We do so directly instead of via the normal ChannelMonitor update
11014                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
11015                                                 // we're not allowed to call it directly yet. Further, we do the update
11016                                                 // without incrementing the ChannelMonitor update ID as there isn't any
11017                                                 // reason to.
11018                                                 // If we were to generate a new ChannelMonitor update ID here and then
11019                                                 // crash before the user finishes block connect we'd end up force-closing
11020                                                 // this channel as well. On the flip side, there's no harm in restarting
11021                                                 // without the new monitor persisted - we'll end up right back here on
11022                                                 // restart.
11023                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
11024                                                 if let Some(peer_node_id) = outpoint_to_peer.get(&claimable_htlc.prev_hop.outpoint) {
11025                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
11026                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
11027                                                         let peer_state = &mut *peer_state_lock;
11028                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
11029                                                                 let logger = WithChannelContext::from(&args.logger, &channel.context);
11030                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &&logger);
11031                                                         }
11032                                                 }
11033                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
11034                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
11035                                                 }
11036                                         }
11037                                         pending_events_read.push_back((events::Event::PaymentClaimed {
11038                                                 receiver_node_id,
11039                                                 payment_hash,
11040                                                 purpose: payment.purpose,
11041                                                 amount_msat: claimable_amt_msat,
11042                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
11043                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
11044                                         }, None));
11045                                 }
11046                         }
11047                 }
11048
11049                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
11050                         if let Some(peer_state) = per_peer_state.get(&node_id) {
11051                                 for (channel_id, actions) in monitor_update_blocked_actions.iter() {
11052                                         let logger = WithContext::from(&args.logger, Some(node_id), Some(*channel_id));
11053                                         for action in actions.iter() {
11054                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
11055                                                         downstream_counterparty_and_funding_outpoint:
11056                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
11057                                                 } = action {
11058                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
11059                                                                 log_trace!(logger,
11060                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
11061                                                                         blocked_channel_outpoint.to_channel_id());
11062                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
11063                                                                         .entry(blocked_channel_outpoint.to_channel_id())
11064                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
11065                                                         } else {
11066                                                                 // If the channel we were blocking has closed, we don't need to
11067                                                                 // worry about it - the blocked monitor update should never have
11068                                                                 // been released from the `Channel` object so it can't have
11069                                                                 // completed, and if the channel closed there's no reason to bother
11070                                                                 // anymore.
11071                                                         }
11072                                                 }
11073                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
11074                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
11075                                                 }
11076                                         }
11077                                 }
11078                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
11079                         } else {
11080                                 log_error!(WithContext::from(&args.logger, Some(node_id), None), "Got blocked actions without a per-peer-state for {}", node_id);
11081                                 return Err(DecodeError::InvalidValue);
11082                         }
11083                 }
11084
11085                 let channel_manager = ChannelManager {
11086                         chain_hash,
11087                         fee_estimator: bounded_fee_estimator,
11088                         chain_monitor: args.chain_monitor,
11089                         tx_broadcaster: args.tx_broadcaster,
11090                         router: args.router,
11091
11092                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
11093
11094                         inbound_payment_key: expanded_inbound_key,
11095                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
11096                         pending_outbound_payments: pending_outbounds,
11097                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
11098
11099                         forward_htlcs: Mutex::new(forward_htlcs),
11100                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
11101                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
11102                         outpoint_to_peer: Mutex::new(outpoint_to_peer),
11103                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
11104                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
11105
11106                         probing_cookie_secret: probing_cookie_secret.unwrap(),
11107
11108                         our_network_pubkey,
11109                         secp_ctx,
11110
11111                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
11112
11113                         per_peer_state: FairRwLock::new(per_peer_state),
11114
11115                         pending_events: Mutex::new(pending_events_read),
11116                         pending_events_processor: AtomicBool::new(false),
11117                         pending_background_events: Mutex::new(pending_background_events),
11118                         total_consistency_lock: RwLock::new(()),
11119                         background_events_processed_since_startup: AtomicBool::new(false),
11120
11121                         event_persist_notifier: Notifier::new(),
11122                         needs_persist_flag: AtomicBool::new(false),
11123
11124                         funding_batch_states: Mutex::new(BTreeMap::new()),
11125
11126                         pending_offers_messages: Mutex::new(Vec::new()),
11127
11128                         entropy_source: args.entropy_source,
11129                         node_signer: args.node_signer,
11130                         signer_provider: args.signer_provider,
11131
11132                         logger: args.logger,
11133                         default_configuration: args.default_config,
11134                 };
11135
11136                 for htlc_source in failed_htlcs.drain(..) {
11137                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
11138                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
11139                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
11140                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
11141                 }
11142
11143                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
11144                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
11145                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
11146                         // channel is closed we just assume that it probably came from an on-chain claim.
11147                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
11148                                 downstream_closed, true, downstream_node_id, downstream_funding);
11149                 }
11150
11151                 //TODO: Broadcast channel update for closed channels, but only after we've made a
11152                 //connection or two.
11153
11154                 Ok((best_block_hash.clone(), channel_manager))
11155         }
11156 }
11157
11158 #[cfg(test)]
11159 mod tests {
11160         use bitcoin::hashes::Hash;
11161         use bitcoin::hashes::sha256::Hash as Sha256;
11162         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
11163         use core::sync::atomic::Ordering;
11164         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
11165         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
11166         use crate::ln::ChannelId;
11167         use crate::ln::channelmanager::{create_recv_pending_htlc_info, HTLCForwardInfo, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
11168         use crate::ln::functional_test_utils::*;
11169         use crate::ln::msgs::{self, ErrorAction};
11170         use crate::ln::msgs::ChannelMessageHandler;
11171         use crate::prelude::*;
11172         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
11173         use crate::util::errors::APIError;
11174         use crate::util::ser::Writeable;
11175         use crate::util::test_utils;
11176         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
11177         use crate::sign::EntropySource;
11178
11179         #[test]
11180         fn test_notify_limits() {
11181                 // Check that a few cases which don't require the persistence of a new ChannelManager,
11182                 // indeed, do not cause the persistence of a new ChannelManager.
11183                 let chanmon_cfgs = create_chanmon_cfgs(3);
11184                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11185                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
11186                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11187
11188                 // All nodes start with a persistable update pending as `create_network` connects each node
11189                 // with all other nodes to make most tests simpler.
11190                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11191                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11192                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11193
11194                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11195
11196                 // We check that the channel info nodes have doesn't change too early, even though we try
11197                 // to connect messages with new values
11198                 chan.0.contents.fee_base_msat *= 2;
11199                 chan.1.contents.fee_base_msat *= 2;
11200                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
11201                         &nodes[1].node.get_our_node_id()).pop().unwrap();
11202                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
11203                         &nodes[0].node.get_our_node_id()).pop().unwrap();
11204
11205                 // The first two nodes (which opened a channel) should now require fresh persistence
11206                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11207                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11208                 // ... but the last node should not.
11209                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11210                 // After persisting the first two nodes they should no longer need fresh persistence.
11211                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11212                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11213
11214                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
11215                 // about the channel.
11216                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
11217                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
11218                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11219
11220                 // The nodes which are a party to the channel should also ignore messages from unrelated
11221                 // parties.
11222                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11223                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11224                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11225                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11226                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11227                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11228
11229                 // At this point the channel info given by peers should still be the same.
11230                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11231                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11232
11233                 // An earlier version of handle_channel_update didn't check the directionality of the
11234                 // update message and would always update the local fee info, even if our peer was
11235                 // (spuriously) forwarding us our own channel_update.
11236                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
11237                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
11238                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
11239
11240                 // First deliver each peers' own message, checking that the node doesn't need to be
11241                 // persisted and that its channel info remains the same.
11242                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
11243                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
11244                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11245                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11246                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11247                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11248
11249                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
11250                 // the channel info has updated.
11251                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
11252                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
11253                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11254                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11255                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
11256                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
11257         }
11258
11259         #[test]
11260         fn test_keysend_dup_hash_partial_mpp() {
11261                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
11262                 // expected.
11263                 let chanmon_cfgs = create_chanmon_cfgs(2);
11264                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11265                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11266                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11267                 create_announced_chan_between_nodes(&nodes, 0, 1);
11268
11269                 // First, send a partial MPP payment.
11270                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
11271                 let mut mpp_route = route.clone();
11272                 mpp_route.paths.push(mpp_route.paths[0].clone());
11273
11274                 let payment_id = PaymentId([42; 32]);
11275                 // Use the utility function send_payment_along_path to send the payment with MPP data which
11276                 // indicates there are more HTLCs coming.
11277                 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.
11278                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
11279                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
11280                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
11281                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
11282                 check_added_monitors!(nodes[0], 1);
11283                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11284                 assert_eq!(events.len(), 1);
11285                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
11286
11287                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
11288                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11289                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11290                 check_added_monitors!(nodes[0], 1);
11291                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11292                 assert_eq!(events.len(), 1);
11293                 let ev = events.drain(..).next().unwrap();
11294                 let payment_event = SendEvent::from_event(ev);
11295                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11296                 check_added_monitors!(nodes[1], 0);
11297                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11298                 expect_pending_htlcs_forwardable!(nodes[1]);
11299                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
11300                 check_added_monitors!(nodes[1], 1);
11301                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11302                 assert!(updates.update_add_htlcs.is_empty());
11303                 assert!(updates.update_fulfill_htlcs.is_empty());
11304                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11305                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11306                 assert!(updates.update_fee.is_none());
11307                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11308                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11309                 expect_payment_failed!(nodes[0], our_payment_hash, true);
11310
11311                 // Send the second half of the original MPP payment.
11312                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
11313                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
11314                 check_added_monitors!(nodes[0], 1);
11315                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11316                 assert_eq!(events.len(), 1);
11317                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
11318
11319                 // Claim the full MPP payment. Note that we can't use a test utility like
11320                 // claim_funds_along_route because the ordering of the messages causes the second half of the
11321                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
11322                 // lightning messages manually.
11323                 nodes[1].node.claim_funds(payment_preimage);
11324                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
11325                 check_added_monitors!(nodes[1], 2);
11326
11327                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11328                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
11329                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
11330                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
11331                 check_added_monitors!(nodes[0], 1);
11332                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11333                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
11334                 check_added_monitors!(nodes[1], 1);
11335                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11336                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
11337                 check_added_monitors!(nodes[1], 1);
11338                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11339                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
11340                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
11341                 check_added_monitors!(nodes[0], 1);
11342                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
11343                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
11344                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11345                 check_added_monitors!(nodes[0], 1);
11346                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
11347                 check_added_monitors!(nodes[1], 1);
11348                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
11349                 check_added_monitors!(nodes[1], 1);
11350                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11351                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
11352                 check_added_monitors!(nodes[0], 1);
11353
11354                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
11355                 // path's success and a PaymentPathSuccessful event for each path's success.
11356                 let events = nodes[0].node.get_and_clear_pending_events();
11357                 assert_eq!(events.len(), 2);
11358                 match events[0] {
11359                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11360                                 assert_eq!(payment_id, *actual_payment_id);
11361                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11362                                 assert_eq!(route.paths[0], *path);
11363                         },
11364                         _ => panic!("Unexpected event"),
11365                 }
11366                 match events[1] {
11367                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11368                                 assert_eq!(payment_id, *actual_payment_id);
11369                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11370                                 assert_eq!(route.paths[0], *path);
11371                         },
11372                         _ => panic!("Unexpected event"),
11373                 }
11374         }
11375
11376         #[test]
11377         fn test_keysend_dup_payment_hash() {
11378                 do_test_keysend_dup_payment_hash(false);
11379                 do_test_keysend_dup_payment_hash(true);
11380         }
11381
11382         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
11383                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
11384                 //      outbound regular payment fails as expected.
11385                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
11386                 //      fails as expected.
11387                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
11388                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
11389                 //      reject MPP keysend payments, since in this case where the payment has no payment
11390                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
11391                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
11392                 //      payment secrets and reject otherwise.
11393                 let chanmon_cfgs = create_chanmon_cfgs(2);
11394                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11395                 let mut mpp_keysend_cfg = test_default_channel_config();
11396                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
11397                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
11398                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11399                 create_announced_chan_between_nodes(&nodes, 0, 1);
11400                 let scorer = test_utils::TestScorer::new();
11401                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11402
11403                 // To start (1), send a regular payment but don't claim it.
11404                 let expected_route = [&nodes[1]];
11405                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
11406
11407                 // Next, attempt a keysend payment and make sure it fails.
11408                 let route_params = RouteParameters::from_payment_params_and_value(
11409                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
11410                         TEST_FINAL_CLTV, false), 100_000);
11411                 let route = find_route(
11412                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11413                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11414                 ).unwrap();
11415                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11416                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11417                 check_added_monitors!(nodes[0], 1);
11418                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11419                 assert_eq!(events.len(), 1);
11420                 let ev = events.drain(..).next().unwrap();
11421                 let payment_event = SendEvent::from_event(ev);
11422                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11423                 check_added_monitors!(nodes[1], 0);
11424                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11425                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
11426                 // fails), the second will process the resulting failure and fail the HTLC backward
11427                 expect_pending_htlcs_forwardable!(nodes[1]);
11428                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11429                 check_added_monitors!(nodes[1], 1);
11430                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11431                 assert!(updates.update_add_htlcs.is_empty());
11432                 assert!(updates.update_fulfill_htlcs.is_empty());
11433                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11434                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11435                 assert!(updates.update_fee.is_none());
11436                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11437                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11438                 expect_payment_failed!(nodes[0], payment_hash, true);
11439
11440                 // Finally, claim the original payment.
11441                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11442
11443                 // To start (2), send a keysend payment but don't claim it.
11444                 let payment_preimage = PaymentPreimage([42; 32]);
11445                 let route = find_route(
11446                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11447                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11448                 ).unwrap();
11449                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11450                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11451                 check_added_monitors!(nodes[0], 1);
11452                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11453                 assert_eq!(events.len(), 1);
11454                 let event = events.pop().unwrap();
11455                 let path = vec![&nodes[1]];
11456                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11457
11458                 // Next, attempt a regular payment and make sure it fails.
11459                 let payment_secret = PaymentSecret([43; 32]);
11460                 nodes[0].node.send_payment_with_route(&route, payment_hash,
11461                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
11462                 check_added_monitors!(nodes[0], 1);
11463                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11464                 assert_eq!(events.len(), 1);
11465                 let ev = events.drain(..).next().unwrap();
11466                 let payment_event = SendEvent::from_event(ev);
11467                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11468                 check_added_monitors!(nodes[1], 0);
11469                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11470                 expect_pending_htlcs_forwardable!(nodes[1]);
11471                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11472                 check_added_monitors!(nodes[1], 1);
11473                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11474                 assert!(updates.update_add_htlcs.is_empty());
11475                 assert!(updates.update_fulfill_htlcs.is_empty());
11476                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11477                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11478                 assert!(updates.update_fee.is_none());
11479                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11480                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11481                 expect_payment_failed!(nodes[0], payment_hash, true);
11482
11483                 // Finally, succeed the keysend payment.
11484                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11485
11486                 // To start (3), send a keysend payment but don't claim it.
11487                 let payment_id_1 = PaymentId([44; 32]);
11488                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11489                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
11490                 check_added_monitors!(nodes[0], 1);
11491                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11492                 assert_eq!(events.len(), 1);
11493                 let event = events.pop().unwrap();
11494                 let path = vec![&nodes[1]];
11495                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11496
11497                 // Next, attempt a keysend payment and make sure it fails.
11498                 let route_params = RouteParameters::from_payment_params_and_value(
11499                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
11500                         100_000
11501                 );
11502                 let route = find_route(
11503                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11504                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11505                 ).unwrap();
11506                 let payment_id_2 = PaymentId([45; 32]);
11507                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11508                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
11509                 check_added_monitors!(nodes[0], 1);
11510                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11511                 assert_eq!(events.len(), 1);
11512                 let ev = events.drain(..).next().unwrap();
11513                 let payment_event = SendEvent::from_event(ev);
11514                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11515                 check_added_monitors!(nodes[1], 0);
11516                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11517                 expect_pending_htlcs_forwardable!(nodes[1]);
11518                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11519                 check_added_monitors!(nodes[1], 1);
11520                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11521                 assert!(updates.update_add_htlcs.is_empty());
11522                 assert!(updates.update_fulfill_htlcs.is_empty());
11523                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11524                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11525                 assert!(updates.update_fee.is_none());
11526                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11527                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11528                 expect_payment_failed!(nodes[0], payment_hash, true);
11529
11530                 // Finally, claim the original payment.
11531                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11532         }
11533
11534         #[test]
11535         fn test_keysend_hash_mismatch() {
11536                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
11537                 // preimage doesn't match the msg's payment hash.
11538                 let chanmon_cfgs = create_chanmon_cfgs(2);
11539                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11540                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11541                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11542
11543                 let payer_pubkey = nodes[0].node.get_our_node_id();
11544                 let payee_pubkey = nodes[1].node.get_our_node_id();
11545
11546                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11547                 let route_params = RouteParameters::from_payment_params_and_value(
11548                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11549                 let network_graph = nodes[0].network_graph;
11550                 let first_hops = nodes[0].node.list_usable_channels();
11551                 let scorer = test_utils::TestScorer::new();
11552                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11553                 let route = find_route(
11554                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11555                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11556                 ).unwrap();
11557
11558                 let test_preimage = PaymentPreimage([42; 32]);
11559                 let mismatch_payment_hash = PaymentHash([43; 32]);
11560                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
11561                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
11562                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
11563                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
11564                 check_added_monitors!(nodes[0], 1);
11565
11566                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11567                 assert_eq!(updates.update_add_htlcs.len(), 1);
11568                 assert!(updates.update_fulfill_htlcs.is_empty());
11569                 assert!(updates.update_fail_htlcs.is_empty());
11570                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11571                 assert!(updates.update_fee.is_none());
11572                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11573
11574                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
11575         }
11576
11577         #[test]
11578         fn test_keysend_msg_with_secret_err() {
11579                 // Test that we error as expected if we receive a keysend payment that includes a payment
11580                 // secret when we don't support MPP keysend.
11581                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
11582                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
11583                 let chanmon_cfgs = create_chanmon_cfgs(2);
11584                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11585                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
11586                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11587
11588                 let payer_pubkey = nodes[0].node.get_our_node_id();
11589                 let payee_pubkey = nodes[1].node.get_our_node_id();
11590
11591                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11592                 let route_params = RouteParameters::from_payment_params_and_value(
11593                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11594                 let network_graph = nodes[0].network_graph;
11595                 let first_hops = nodes[0].node.list_usable_channels();
11596                 let scorer = test_utils::TestScorer::new();
11597                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11598                 let route = find_route(
11599                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11600                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11601                 ).unwrap();
11602
11603                 let test_preimage = PaymentPreimage([42; 32]);
11604                 let test_secret = PaymentSecret([43; 32]);
11605                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).to_byte_array());
11606                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
11607                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
11608                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
11609                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
11610                         PaymentId(payment_hash.0), None, session_privs).unwrap();
11611                 check_added_monitors!(nodes[0], 1);
11612
11613                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11614                 assert_eq!(updates.update_add_htlcs.len(), 1);
11615                 assert!(updates.update_fulfill_htlcs.is_empty());
11616                 assert!(updates.update_fail_htlcs.is_empty());
11617                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11618                 assert!(updates.update_fee.is_none());
11619                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11620
11621                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11622         }
11623
11624         #[test]
11625         fn test_multi_hop_missing_secret() {
11626                 let chanmon_cfgs = create_chanmon_cfgs(4);
11627                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11628                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11629                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11630
11631                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11632                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11633                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11634                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11635
11636                 // Marshall an MPP route.
11637                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11638                 let path = route.paths[0].clone();
11639                 route.paths.push(path);
11640                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11641                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11642                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11643                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11644                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11645                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11646
11647                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11648                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11649                 .unwrap_err() {
11650                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11651                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11652                         },
11653                         _ => panic!("unexpected error")
11654                 }
11655         }
11656
11657         #[test]
11658         fn test_drop_disconnected_peers_when_removing_channels() {
11659                 let chanmon_cfgs = create_chanmon_cfgs(2);
11660                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11661                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11662                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11663
11664                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11665
11666                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11667                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11668
11669                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11670                 check_closed_broadcast!(nodes[0], true);
11671                 check_added_monitors!(nodes[0], 1);
11672                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11673
11674                 {
11675                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11676                         // disconnected and the channel between has been force closed.
11677                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11678                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11679                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11680                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11681                 }
11682
11683                 nodes[0].node.timer_tick_occurred();
11684
11685                 {
11686                         // Assert that nodes[1] has now been removed.
11687                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11688                 }
11689         }
11690
11691         #[test]
11692         fn bad_inbound_payment_hash() {
11693                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11694                 let chanmon_cfgs = create_chanmon_cfgs(2);
11695                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11696                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11697                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11698
11699                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11700                 let payment_data = msgs::FinalOnionHopData {
11701                         payment_secret,
11702                         total_msat: 100_000,
11703                 };
11704
11705                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11706                 // payment verification fails as expected.
11707                 let mut bad_payment_hash = payment_hash.clone();
11708                 bad_payment_hash.0[0] += 1;
11709                 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) {
11710                         Ok(_) => panic!("Unexpected ok"),
11711                         Err(()) => {
11712                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11713                         }
11714                 }
11715
11716                 // Check that using the original payment hash succeeds.
11717                 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());
11718         }
11719
11720         #[test]
11721         fn test_outpoint_to_peer_coverage() {
11722                 // Test that the `ChannelManager:outpoint_to_peer` contains channels which have been assigned
11723                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11724                 // the channel is successfully closed.
11725                 let chanmon_cfgs = create_chanmon_cfgs(2);
11726                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11727                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11728                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11729
11730                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
11731                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11732                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11733                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11734                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11735
11736                 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11737                 let channel_id = ChannelId::from_bytes(tx.txid().to_byte_array());
11738                 {
11739                         // Ensure that the `outpoint_to_peer` map is empty until either party has received the
11740                         // funding transaction, and have the real `channel_id`.
11741                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11742                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11743                 }
11744
11745                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11746                 {
11747                         // Assert that `nodes[0]`'s `outpoint_to_peer` map is populated with the channel as soon as
11748                         // as it has the funding transaction.
11749                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11750                         assert_eq!(nodes_0_lock.len(), 1);
11751                         assert!(nodes_0_lock.contains_key(&funding_output));
11752                 }
11753
11754                 assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11755
11756                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11757
11758                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11759                 {
11760                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11761                         assert_eq!(nodes_0_lock.len(), 1);
11762                         assert!(nodes_0_lock.contains_key(&funding_output));
11763                 }
11764                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11765
11766                 {
11767                         // Assert that `nodes[1]`'s `outpoint_to_peer` map is populated with the channel as
11768                         // soon as it has the funding transaction.
11769                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11770                         assert_eq!(nodes_1_lock.len(), 1);
11771                         assert!(nodes_1_lock.contains_key(&funding_output));
11772                 }
11773                 check_added_monitors!(nodes[1], 1);
11774                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11775                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11776                 check_added_monitors!(nodes[0], 1);
11777                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11778                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11779                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11780                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11781
11782                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11783                 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()));
11784                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11785                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11786
11787                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11788                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11789                 {
11790                         // Assert that the channel is kept in the `outpoint_to_peer` map for both nodes until the
11791                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11792                         // fee for the closing transaction has been negotiated and the parties has the other
11793                         // party's signature for the fee negotiated closing transaction.)
11794                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11795                         assert_eq!(nodes_0_lock.len(), 1);
11796                         assert!(nodes_0_lock.contains_key(&funding_output));
11797                 }
11798
11799                 {
11800                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11801                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11802                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11803                         // kept in the `nodes[1]`'s `outpoint_to_peer` map.
11804                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11805                         assert_eq!(nodes_1_lock.len(), 1);
11806                         assert!(nodes_1_lock.contains_key(&funding_output));
11807                 }
11808
11809                 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()));
11810                 {
11811                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11812                         // therefore has all it needs to fully close the channel (both signatures for the
11813                         // closing transaction).
11814                         // Assert that the channel is removed from `nodes[0]`'s `outpoint_to_peer` map as it can be
11815                         // fully closed by `nodes[0]`.
11816                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11817
11818                         // Assert that the channel is still in `nodes[1]`'s  `outpoint_to_peer` map, as `nodes[1]`
11819                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11820                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11821                         assert_eq!(nodes_1_lock.len(), 1);
11822                         assert!(nodes_1_lock.contains_key(&funding_output));
11823                 }
11824
11825                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11826
11827                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11828                 {
11829                         // Assert that the channel has now been removed from both parties `outpoint_to_peer` map once
11830                         // they both have everything required to fully close the channel.
11831                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11832                 }
11833                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11834
11835                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11836                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11837         }
11838
11839         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11840                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11841                 check_api_error_message(expected_message, res_err)
11842         }
11843
11844         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11845                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11846                 check_api_error_message(expected_message, res_err)
11847         }
11848
11849         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11850                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11851                 check_api_error_message(expected_message, res_err)
11852         }
11853
11854         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11855                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11856                 check_api_error_message(expected_message, res_err)
11857         }
11858
11859         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11860                 match res_err {
11861                         Err(APIError::APIMisuseError { err }) => {
11862                                 assert_eq!(err, expected_err_message);
11863                         },
11864                         Err(APIError::ChannelUnavailable { err }) => {
11865                                 assert_eq!(err, expected_err_message);
11866                         },
11867                         Ok(_) => panic!("Unexpected Ok"),
11868                         Err(_) => panic!("Unexpected Error"),
11869                 }
11870         }
11871
11872         #[test]
11873         fn test_api_calls_with_unkown_counterparty_node() {
11874                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11875                 // expected if the `counterparty_node_id` is an unkown peer in the
11876                 // `ChannelManager::per_peer_state` map.
11877                 let chanmon_cfg = create_chanmon_cfgs(2);
11878                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11879                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11880                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11881
11882                 // Dummy values
11883                 let channel_id = ChannelId::from_bytes([4; 32]);
11884                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11885                 let intercept_id = InterceptId([0; 32]);
11886
11887                 // Test the API functions.
11888                 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);
11889
11890                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11891
11892                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11893
11894                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11895
11896                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11897
11898                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11899
11900                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11901         }
11902
11903         #[test]
11904         fn test_api_calls_with_unavailable_channel() {
11905                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11906                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11907                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11908                 // the given `channel_id`.
11909                 let chanmon_cfg = create_chanmon_cfgs(2);
11910                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11911                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11912                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11913
11914                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11915
11916                 // Dummy values
11917                 let channel_id = ChannelId::from_bytes([4; 32]);
11918
11919                 // Test the API functions.
11920                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11921
11922                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11923
11924                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11925
11926                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11927
11928                 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);
11929
11930                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11931         }
11932
11933         #[test]
11934         fn test_connection_limiting() {
11935                 // Test that we limit un-channel'd peers and un-funded channels properly.
11936                 let chanmon_cfgs = create_chanmon_cfgs(2);
11937                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11938                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11939                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11940
11941                 // Note that create_network connects the nodes together for us
11942
11943                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11944                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11945
11946                 let mut funding_tx = None;
11947                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11948                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11949                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11950
11951                         if idx == 0 {
11952                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11953                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11954                                 funding_tx = Some(tx.clone());
11955                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11956                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11957
11958                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11959                                 check_added_monitors!(nodes[1], 1);
11960                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11961
11962                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11963
11964                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11965                                 check_added_monitors!(nodes[0], 1);
11966                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11967                         }
11968                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11969                 }
11970
11971                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11972                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11973                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11974                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11975                         open_channel_msg.temporary_channel_id);
11976
11977                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11978                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11979                 // limit.
11980                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11981                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11982                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11983                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11984                         peer_pks.push(random_pk);
11985                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11986                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11987                         }, true).unwrap();
11988                 }
11989                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11990                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11991                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11992                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11993                 }, true).unwrap_err();
11994
11995                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11996                 // them if we have too many un-channel'd peers.
11997                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11998                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11999                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
12000                 for ev in chan_closed_events {
12001                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
12002                 }
12003                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12004                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12005                 }, true).unwrap();
12006                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12007                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12008                 }, true).unwrap_err();
12009
12010                 // but of course if the connection is outbound its allowed...
12011                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12012                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12013                 }, false).unwrap();
12014                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12015
12016                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
12017                 // Even though we accept one more connection from new peers, we won't actually let them
12018                 // open channels.
12019                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
12020                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12021                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
12022                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
12023                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12024                 }
12025                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12026                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12027                         open_channel_msg.temporary_channel_id);
12028
12029                 // Of course, however, outbound channels are always allowed
12030                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap();
12031                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
12032
12033                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
12034                 // "protected" and can connect again.
12035                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
12036                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12037                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12038                 }, true).unwrap();
12039                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
12040
12041                 // Further, because the first channel was funded, we can open another channel with
12042                 // last_random_pk.
12043                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12044                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12045         }
12046
12047         #[test]
12048         fn test_outbound_chans_unlimited() {
12049                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
12050                 let chanmon_cfgs = create_chanmon_cfgs(2);
12051                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12052                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
12053                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12054
12055                 // Note that create_network connects the nodes together for us
12056
12057                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12058                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12059
12060                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
12061                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12062                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12063                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12064                 }
12065
12066                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
12067                 // rejected.
12068                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12069                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12070                         open_channel_msg.temporary_channel_id);
12071
12072                 // but we can still open an outbound channel.
12073                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12074                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
12075
12076                 // but even with such an outbound channel, additional inbound channels will still fail.
12077                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12078                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12079                         open_channel_msg.temporary_channel_id);
12080         }
12081
12082         #[test]
12083         fn test_0conf_limiting() {
12084                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12085                 // flag set and (sometimes) accept channels as 0conf.
12086                 let chanmon_cfgs = create_chanmon_cfgs(2);
12087                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12088                 let mut settings = test_default_channel_config();
12089                 settings.manually_accept_inbound_channels = true;
12090                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
12091                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12092
12093                 // Note that create_network connects the nodes together for us
12094
12095                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12096                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12097
12098                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
12099                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12100                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12101                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12102                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
12103                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12104                         }, true).unwrap();
12105
12106                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
12107                         let events = nodes[1].node.get_and_clear_pending_events();
12108                         match events[0] {
12109                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
12110                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
12111                                 }
12112                                 _ => panic!("Unexpected event"),
12113                         }
12114                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
12115                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12116                 }
12117
12118                 // If we try to accept a channel from another peer non-0conf it will fail.
12119                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12120                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12121                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12122                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12123                 }, true).unwrap();
12124                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12125                 let events = nodes[1].node.get_and_clear_pending_events();
12126                 match events[0] {
12127                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12128                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
12129                                         Err(APIError::APIMisuseError { err }) =>
12130                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
12131                                         _ => panic!(),
12132                                 }
12133                         }
12134                         _ => panic!("Unexpected event"),
12135                 }
12136                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12137                         open_channel_msg.temporary_channel_id);
12138
12139                 // ...however if we accept the same channel 0conf it should work just fine.
12140                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12141                 let events = nodes[1].node.get_and_clear_pending_events();
12142                 match events[0] {
12143                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12144                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
12145                         }
12146                         _ => panic!("Unexpected event"),
12147                 }
12148                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12149         }
12150
12151         #[test]
12152         fn reject_excessively_underpaying_htlcs() {
12153                 let chanmon_cfg = create_chanmon_cfgs(1);
12154                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12155                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12156                 let node = create_network(1, &node_cfg, &node_chanmgr);
12157                 let sender_intended_amt_msat = 100;
12158                 let extra_fee_msat = 10;
12159                 let hop_data = msgs::InboundOnionPayload::Receive {
12160                         sender_intended_htlc_amt_msat: 100,
12161                         cltv_expiry_height: 42,
12162                         payment_metadata: None,
12163                         keysend_preimage: None,
12164                         payment_data: Some(msgs::FinalOnionHopData {
12165                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12166                         }),
12167                         custom_tlvs: Vec::new(),
12168                 };
12169                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
12170                 // intended amount, we fail the payment.
12171                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12172                 if let Err(crate::ln::channelmanager::InboundHTLCErr { err_code, .. }) =
12173                         create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12174                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
12175                                 current_height, node[0].node.default_configuration.accept_mpp_keysend)
12176                 {
12177                         assert_eq!(err_code, 19);
12178                 } else { panic!(); }
12179
12180                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
12181                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
12182                         sender_intended_htlc_amt_msat: 100,
12183                         cltv_expiry_height: 42,
12184                         payment_metadata: None,
12185                         keysend_preimage: None,
12186                         payment_data: Some(msgs::FinalOnionHopData {
12187                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12188                         }),
12189                         custom_tlvs: Vec::new(),
12190                 };
12191                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12192                 assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12193                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
12194                         current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
12195         }
12196
12197         #[test]
12198         fn test_final_incorrect_cltv(){
12199                 let chanmon_cfg = create_chanmon_cfgs(1);
12200                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12201                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12202                 let node = create_network(1, &node_cfg, &node_chanmgr);
12203
12204                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12205                 let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
12206                         sender_intended_htlc_amt_msat: 100,
12207                         cltv_expiry_height: 22,
12208                         payment_metadata: None,
12209                         keysend_preimage: None,
12210                         payment_data: Some(msgs::FinalOnionHopData {
12211                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
12212                         }),
12213                         custom_tlvs: Vec::new(),
12214                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
12215                         node[0].node.default_configuration.accept_mpp_keysend);
12216
12217                 // Should not return an error as this condition:
12218                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
12219                 // is not satisfied.
12220                 assert!(result.is_ok());
12221         }
12222
12223         #[test]
12224         fn test_inbound_anchors_manual_acceptance() {
12225                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12226                 // flag set and (sometimes) accept channels as 0conf.
12227                 let mut anchors_cfg = test_default_channel_config();
12228                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12229
12230                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
12231                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
12232
12233                 let chanmon_cfgs = create_chanmon_cfgs(3);
12234                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
12235                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
12236                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
12237                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
12238
12239                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12240                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12241
12242                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12243                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12244                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
12245                 match &msg_events[0] {
12246                         MessageSendEvent::HandleError { node_id, action } => {
12247                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
12248                                 match action {
12249                                         ErrorAction::SendErrorMessage { msg } =>
12250                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
12251                                         _ => panic!("Unexpected error action"),
12252                                 }
12253                         }
12254                         _ => panic!("Unexpected event"),
12255                 }
12256
12257                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12258                 let events = nodes[2].node.get_and_clear_pending_events();
12259                 match events[0] {
12260                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
12261                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
12262                         _ => panic!("Unexpected event"),
12263                 }
12264                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12265         }
12266
12267         #[test]
12268         fn test_anchors_zero_fee_htlc_tx_fallback() {
12269                 // Tests that if both nodes support anchors, but the remote node does not want to accept
12270                 // anchor channels at the moment, an error it sent to the local node such that it can retry
12271                 // the channel without the anchors feature.
12272                 let chanmon_cfgs = create_chanmon_cfgs(2);
12273                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12274                 let mut anchors_config = test_default_channel_config();
12275                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12276                 anchors_config.manually_accept_inbound_channels = true;
12277                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
12278                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12279
12280                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None).unwrap();
12281                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12282                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
12283
12284                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12285                 let events = nodes[1].node.get_and_clear_pending_events();
12286                 match events[0] {
12287                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12288                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
12289                         }
12290                         _ => panic!("Unexpected event"),
12291                 }
12292
12293                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
12294                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
12295
12296                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12297                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
12298
12299                 // Since nodes[1] should not have accepted the channel, it should
12300                 // not have generated any events.
12301                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12302         }
12303
12304         #[test]
12305         fn test_update_channel_config() {
12306                 let chanmon_cfg = create_chanmon_cfgs(2);
12307                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12308                 let mut user_config = test_default_channel_config();
12309                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12310                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12311                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
12312                 let channel = &nodes[0].node.list_channels()[0];
12313
12314                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12315                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12316                 assert_eq!(events.len(), 0);
12317
12318                 user_config.channel_config.forwarding_fee_base_msat += 10;
12319                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12320                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
12321                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12322                 assert_eq!(events.len(), 1);
12323                 match &events[0] {
12324                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12325                         _ => panic!("expected BroadcastChannelUpdate event"),
12326                 }
12327
12328                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
12329                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12330                 assert_eq!(events.len(), 0);
12331
12332                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
12333                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12334                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
12335                         ..Default::default()
12336                 }).unwrap();
12337                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12338                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12339                 assert_eq!(events.len(), 1);
12340                 match &events[0] {
12341                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12342                         _ => panic!("expected BroadcastChannelUpdate event"),
12343                 }
12344
12345                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
12346                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12347                         forwarding_fee_proportional_millionths: Some(new_fee),
12348                         ..Default::default()
12349                 }).unwrap();
12350                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12351                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
12352                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12353                 assert_eq!(events.len(), 1);
12354                 match &events[0] {
12355                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12356                         _ => panic!("expected BroadcastChannelUpdate event"),
12357                 }
12358
12359                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
12360                 // should be applied to ensure update atomicity as specified in the API docs.
12361                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
12362                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
12363                 let new_fee = current_fee + 100;
12364                 assert!(
12365                         matches!(
12366                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
12367                                         forwarding_fee_proportional_millionths: Some(new_fee),
12368                                         ..Default::default()
12369                                 }),
12370                                 Err(APIError::ChannelUnavailable { err: _ }),
12371                         )
12372                 );
12373                 // Check that the fee hasn't changed for the channel that exists.
12374                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
12375                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12376                 assert_eq!(events.len(), 0);
12377         }
12378
12379         #[test]
12380         fn test_payment_display() {
12381                 let payment_id = PaymentId([42; 32]);
12382                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12383                 let payment_hash = PaymentHash([42; 32]);
12384                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12385                 let payment_preimage = PaymentPreimage([42; 32]);
12386                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12387         }
12388
12389         #[test]
12390         fn test_trigger_lnd_force_close() {
12391                 let chanmon_cfg = create_chanmon_cfgs(2);
12392                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12393                 let user_config = test_default_channel_config();
12394                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12395                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12396
12397                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
12398                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
12399                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
12400                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12401                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
12402                 check_closed_broadcast(&nodes[0], 1, true);
12403                 check_added_monitors(&nodes[0], 1);
12404                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
12405                 {
12406                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
12407                         assert_eq!(txn.len(), 1);
12408                         check_spends!(txn[0], funding_tx);
12409                 }
12410
12411                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
12412                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
12413                 // their side.
12414                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
12415                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
12416                 }, true).unwrap();
12417                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12418                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12419                 }, false).unwrap();
12420                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
12421                 let channel_reestablish = get_event_msg!(
12422                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
12423                 );
12424                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
12425
12426                 // Alice should respond with an error since the channel isn't known, but a bogus
12427                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
12428                 // close even if it was an lnd node.
12429                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
12430                 assert_eq!(msg_events.len(), 2);
12431                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
12432                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
12433                         assert_eq!(msg.next_local_commitment_number, 0);
12434                         assert_eq!(msg.next_remote_commitment_number, 0);
12435                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
12436                 } else { panic!() };
12437                 check_closed_broadcast(&nodes[1], 1, true);
12438                 check_added_monitors(&nodes[1], 1);
12439                 let expected_close_reason = ClosureReason::ProcessingError {
12440                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
12441                 };
12442                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
12443                 {
12444                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
12445                         assert_eq!(txn.len(), 1);
12446                         check_spends!(txn[0], funding_tx);
12447                 }
12448         }
12449
12450         #[test]
12451         fn test_malformed_forward_htlcs_ser() {
12452                 // Ensure that `HTLCForwardInfo::FailMalformedHTLC`s are (de)serialized properly.
12453                 let chanmon_cfg = create_chanmon_cfgs(1);
12454                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12455                 let persister;
12456                 let chain_monitor;
12457                 let chanmgrs = create_node_chanmgrs(1, &node_cfg, &[None]);
12458                 let deserialized_chanmgr;
12459                 let mut nodes = create_network(1, &node_cfg, &chanmgrs);
12460
12461                 let dummy_failed_htlc = |htlc_id| {
12462                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet: msgs::OnionErrorPacket { data: vec![42] }, }
12463                 };
12464                 let dummy_malformed_htlc = |htlc_id| {
12465                         HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code: 0x4000, sha256_of_onion: [0; 32] }
12466                 };
12467
12468                 let dummy_htlcs_1: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12469                         if htlc_id % 2 == 0 {
12470                                 dummy_failed_htlc(htlc_id)
12471                         } else {
12472                                 dummy_malformed_htlc(htlc_id)
12473                         }
12474                 }).collect();
12475
12476                 let dummy_htlcs_2: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12477                         if htlc_id % 2 == 1 {
12478                                 dummy_failed_htlc(htlc_id)
12479                         } else {
12480                                 dummy_malformed_htlc(htlc_id)
12481                         }
12482                 }).collect();
12483
12484
12485                 let (scid_1, scid_2) = (42, 43);
12486                 let mut forward_htlcs = HashMap::new();
12487                 forward_htlcs.insert(scid_1, dummy_htlcs_1.clone());
12488                 forward_htlcs.insert(scid_2, dummy_htlcs_2.clone());
12489
12490                 let mut chanmgr_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12491                 *chanmgr_fwd_htlcs = forward_htlcs.clone();
12492                 core::mem::drop(chanmgr_fwd_htlcs);
12493
12494                 reload_node!(nodes[0], nodes[0].node.encode(), &[], persister, chain_monitor, deserialized_chanmgr);
12495
12496                 let mut deserialized_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12497                 for scid in [scid_1, scid_2].iter() {
12498                         let deserialized_htlcs = deserialized_fwd_htlcs.remove(scid).unwrap();
12499                         assert_eq!(forward_htlcs.remove(scid).unwrap(), deserialized_htlcs);
12500                 }
12501                 assert!(deserialized_fwd_htlcs.is_empty());
12502                 core::mem::drop(deserialized_fwd_htlcs);
12503
12504                 expect_pending_htlcs_forwardable!(nodes[0]);
12505         }
12506 }
12507
12508 #[cfg(ldk_bench)]
12509 pub mod bench {
12510         use crate::chain::Listen;
12511         use crate::chain::chainmonitor::{ChainMonitor, Persist};
12512         use crate::sign::{KeysManager, InMemorySigner};
12513         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
12514         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
12515         use crate::ln::functional_test_utils::*;
12516         use crate::ln::msgs::{ChannelMessageHandler, Init};
12517         use crate::routing::gossip::NetworkGraph;
12518         use crate::routing::router::{PaymentParameters, RouteParameters};
12519         use crate::util::test_utils;
12520         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
12521
12522         use bitcoin::blockdata::locktime::absolute::LockTime;
12523         use bitcoin::hashes::Hash;
12524         use bitcoin::hashes::sha256::Hash as Sha256;
12525         use bitcoin::{Transaction, TxOut};
12526
12527         use crate::sync::{Arc, Mutex, RwLock};
12528
12529         use criterion::Criterion;
12530
12531         type Manager<'a, P> = ChannelManager<
12532                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
12533                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
12534                         &'a test_utils::TestLogger, &'a P>,
12535                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
12536                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
12537                 &'a test_utils::TestLogger>;
12538
12539         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
12540                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
12541         }
12542         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
12543                 type CM = Manager<'chan_mon_cfg, P>;
12544                 #[inline]
12545                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
12546                 #[inline]
12547                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
12548         }
12549
12550         pub fn bench_sends(bench: &mut Criterion) {
12551                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
12552         }
12553
12554         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
12555                 // Do a simple benchmark of sending a payment back and forth between two nodes.
12556                 // Note that this is unrealistic as each payment send will require at least two fsync
12557                 // calls per node.
12558                 let network = bitcoin::Network::Testnet;
12559                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
12560
12561                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
12562                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
12563                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
12564                 let scorer = RwLock::new(test_utils::TestScorer::new());
12565                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &logger_a, &scorer);
12566
12567                 let mut config: UserConfig = Default::default();
12568                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
12569                 config.channel_handshake_config.minimum_depth = 1;
12570
12571                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
12572                 let seed_a = [1u8; 32];
12573                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
12574                 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 {
12575                         network,
12576                         best_block: BestBlock::from_network(network),
12577                 }, genesis_block.header.time);
12578                 let node_a_holder = ANodeHolder { node: &node_a };
12579
12580                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
12581                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
12582                 let seed_b = [2u8; 32];
12583                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
12584                 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 {
12585                         network,
12586                         best_block: BestBlock::from_network(network),
12587                 }, genesis_block.header.time);
12588                 let node_b_holder = ANodeHolder { node: &node_b };
12589
12590                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
12591                         features: node_b.init_features(), networks: None, remote_network_address: None
12592                 }, true).unwrap();
12593                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
12594                         features: node_a.init_features(), networks: None, remote_network_address: None
12595                 }, false).unwrap();
12596                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None, None).unwrap();
12597                 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()));
12598                 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()));
12599
12600                 let tx;
12601                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
12602                         tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12603                                 value: 8_000_000, script_pubkey: output_script,
12604                         }]};
12605                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
12606                 } else { panic!(); }
12607
12608                 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()));
12609                 let events_b = node_b.get_and_clear_pending_events();
12610                 assert_eq!(events_b.len(), 1);
12611                 match events_b[0] {
12612                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12613                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12614                         },
12615                         _ => panic!("Unexpected event"),
12616                 }
12617
12618                 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()));
12619                 let events_a = node_a.get_and_clear_pending_events();
12620                 assert_eq!(events_a.len(), 1);
12621                 match events_a[0] {
12622                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12623                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12624                         },
12625                         _ => panic!("Unexpected event"),
12626                 }
12627
12628                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
12629
12630                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
12631                 Listen::block_connected(&node_a, &block, 1);
12632                 Listen::block_connected(&node_b, &block, 1);
12633
12634                 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()));
12635                 let msg_events = node_a.get_and_clear_pending_msg_events();
12636                 assert_eq!(msg_events.len(), 2);
12637                 match msg_events[0] {
12638                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
12639                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
12640                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
12641                         },
12642                         _ => panic!(),
12643                 }
12644                 match msg_events[1] {
12645                         MessageSendEvent::SendChannelUpdate { .. } => {},
12646                         _ => panic!(),
12647                 }
12648
12649                 let events_a = node_a.get_and_clear_pending_events();
12650                 assert_eq!(events_a.len(), 1);
12651                 match events_a[0] {
12652                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12653                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12654                         },
12655                         _ => panic!("Unexpected event"),
12656                 }
12657
12658                 let events_b = node_b.get_and_clear_pending_events();
12659                 assert_eq!(events_b.len(), 1);
12660                 match events_b[0] {
12661                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12662                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12663                         },
12664                         _ => panic!("Unexpected event"),
12665                 }
12666
12667                 let mut payment_count: u64 = 0;
12668                 macro_rules! send_payment {
12669                         ($node_a: expr, $node_b: expr) => {
12670                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
12671                                         .with_bolt11_features($node_b.bolt11_invoice_features()).unwrap();
12672                                 let mut payment_preimage = PaymentPreimage([0; 32]);
12673                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
12674                                 payment_count += 1;
12675                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
12676                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
12677
12678                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
12679                                         PaymentId(payment_hash.0),
12680                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12681                                         Retry::Attempts(0)).unwrap();
12682                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12683                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12684                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12685                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12686                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12687                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12688                                 $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()));
12689
12690                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12691                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12692                                 $node_b.claim_funds(payment_preimage);
12693                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12694
12695                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12696                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12697                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12698                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12699                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12700                                         },
12701                                         _ => panic!("Failed to generate claim event"),
12702                                 }
12703
12704                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12705                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12706                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12707                                 $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()));
12708
12709                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12710                         }
12711                 }
12712
12713                 bench.bench_function(bench_name, |b| b.iter(|| {
12714                         send_payment!(node_a, node_b);
12715                         send_payment!(node_b, node_a);
12716                 }));
12717         }
12718 }