Add c_bindings version of RefundBuilder
[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         crate::offers::refund::RefundMaybeWithDerivedMetadataBuilder,
89 };
90
91 use alloc::collections::{btree_map, BTreeMap};
92
93 use crate::io;
94 use crate::prelude::*;
95 use core::{cmp, mem};
96 use core::cell::RefCell;
97 use crate::io::Read;
98 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
99 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
100 use core::time::Duration;
101 use core::ops::Deref;
102
103 // Re-export this for use in the public API.
104 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
105 use crate::ln::script::ShutdownScript;
106
107 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
108 //
109 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
110 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
111 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
112 //
113 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
114 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
115 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
116 // before we forward it.
117 //
118 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
119 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
120 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
121 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
122 // our payment, which we can use to decode errors or inform the user that the payment was sent.
123
124 /// Information about where a received HTLC('s onion) has indicated the HTLC should go.
125 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
126 #[cfg_attr(test, derive(Debug, PartialEq))]
127 pub enum PendingHTLCRouting {
128         /// An HTLC which should be forwarded on to another node.
129         Forward {
130                 /// The onion which should be included in the forwarded HTLC, telling the next hop what to
131                 /// do with the HTLC.
132                 onion_packet: msgs::OnionPacket,
133                 /// The short channel ID of the channel which we were instructed to forward this HTLC to.
134                 ///
135                 /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning
136                 /// to the receiving node, such as one returned from
137                 /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`].
138                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
139                 /// Set if this HTLC is being forwarded within a blinded path.
140                 blinded: Option<BlindedForward>,
141         },
142         /// The onion indicates that this is a payment for an invoice (supposedly) generated by us.
143         ///
144         /// Note that at this point, we have not checked that the invoice being paid was actually
145         /// generated by us, but rather it's claiming to pay an invoice of ours.
146         Receive {
147                 /// Information about the amount the sender intended to pay and (potential) proof that this
148                 /// is a payment for an invoice we generated. This proof of payment is is also used for
149                 /// linking MPP parts of a larger payment.
150                 payment_data: msgs::FinalOnionHopData,
151                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
152                 ///
153                 /// For HTLCs received by LDK, this will ultimately be exposed in
154                 /// [`Event::PaymentClaimable::onion_fields`] as
155                 /// [`RecipientOnionFields::payment_metadata`].
156                 payment_metadata: Option<Vec<u8>>,
157                 /// CLTV expiry of the received HTLC.
158                 ///
159                 /// Used to track when we should expire pending HTLCs that go unclaimed.
160                 incoming_cltv_expiry: u32,
161                 /// If the onion had forwarding instructions to one of our phantom node SCIDs, this will
162                 /// provide the onion shared secret used to decrypt the next level of forwarding
163                 /// instructions.
164                 phantom_shared_secret: Option<[u8; 32]>,
165                 /// Custom TLVs which were set by the sender.
166                 ///
167                 /// For HTLCs received by LDK, this will ultimately be exposed in
168                 /// [`Event::PaymentClaimable::onion_fields`] as
169                 /// [`RecipientOnionFields::custom_tlvs`].
170                 custom_tlvs: Vec<(u64, Vec<u8>)>,
171                 /// Set if this HTLC is the final hop in a multi-hop blinded path.
172                 requires_blinded_error: bool,
173         },
174         /// The onion indicates that this is for payment to us but which contains the preimage for
175         /// claiming included, and is unrelated to any invoice we'd previously generated (aka a
176         /// "keysend" or "spontaneous" payment).
177         ReceiveKeysend {
178                 /// Information about the amount the sender intended to pay and possibly a token to
179                 /// associate MPP parts of a larger payment.
180                 ///
181                 /// This will only be filled in if receiving MPP keysend payments is enabled, and it being
182                 /// present will cause deserialization to fail on versions of LDK prior to 0.0.116.
183                 payment_data: Option<msgs::FinalOnionHopData>,
184                 /// Preimage for this onion payment. This preimage is provided by the sender and will be
185                 /// used to settle the spontaneous payment.
186                 payment_preimage: PaymentPreimage,
187                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
188                 ///
189                 /// For HTLCs received by LDK, this will ultimately bubble back up as
190                 /// [`RecipientOnionFields::payment_metadata`].
191                 payment_metadata: Option<Vec<u8>>,
192                 /// CLTV expiry of the received HTLC.
193                 ///
194                 /// Used to track when we should expire pending HTLCs that go unclaimed.
195                 incoming_cltv_expiry: u32,
196                 /// Custom TLVs which were set by the sender.
197                 ///
198                 /// For HTLCs received by LDK, these will ultimately bubble back up as
199                 /// [`RecipientOnionFields::custom_tlvs`].
200                 custom_tlvs: Vec<(u64, Vec<u8>)>,
201         },
202 }
203
204 /// Information used to forward or fail this HTLC that is being forwarded within a blinded path.
205 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
206 pub struct BlindedForward {
207         /// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound
208         /// onion payload if we're the introduction node. Useful for calculating the next hop's
209         /// [`msgs::UpdateAddHTLC::blinding_point`].
210         pub inbound_blinding_point: PublicKey,
211         /// If needed, this determines how this HTLC should be failed backwards, based on whether we are
212         /// the introduction node.
213         pub failure: BlindedFailure,
214 }
215
216 impl PendingHTLCRouting {
217         // Used to override the onion failure code and data if the HTLC is blinded.
218         fn blinded_failure(&self) -> Option<BlindedFailure> {
219                 match self {
220                         Self::Forward { blinded: Some(BlindedForward { failure, .. }), .. } => Some(*failure),
221                         Self::Receive { requires_blinded_error: true, .. } => Some(BlindedFailure::FromBlindedNode),
222                         _ => None,
223                 }
224         }
225 }
226
227 /// Information about an incoming HTLC, including the [`PendingHTLCRouting`] describing where it
228 /// should go next.
229 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
230 #[cfg_attr(test, derive(Debug, PartialEq))]
231 pub struct PendingHTLCInfo {
232         /// Further routing details based on whether the HTLC is being forwarded or received.
233         pub routing: PendingHTLCRouting,
234         /// The onion shared secret we build with the sender used to decrypt the onion.
235         ///
236         /// This is later used to encrypt failure packets in the event that the HTLC is failed.
237         pub incoming_shared_secret: [u8; 32],
238         /// Hash of the payment preimage, to lock the payment until the receiver releases the preimage.
239         pub payment_hash: PaymentHash,
240         /// Amount received in the incoming HTLC.
241         ///
242         /// This field was added in LDK 0.0.113 and will be `None` for objects written by prior
243         /// versions.
244         pub incoming_amt_msat: Option<u64>,
245         /// The amount the sender indicated should be forwarded on to the next hop or amount the sender
246         /// intended for us to receive for received payments.
247         ///
248         /// If the received amount is less than this for received payments, an intermediary hop has
249         /// attempted to steal some of our funds and we should fail the HTLC (the sender should retry
250         /// it along another path).
251         ///
252         /// Because nodes can take less than their required fees, and because senders may wish to
253         /// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for
254         /// received payments. In such cases, recipients must handle this HTLC as if it had received
255         /// [`Self::outgoing_amt_msat`].
256         pub outgoing_amt_msat: u64,
257         /// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated
258         /// should have been set on the received HTLC for received payments).
259         pub outgoing_cltv_value: u32,
260         /// The fee taken for this HTLC in addition to the standard protocol HTLC fees.
261         ///
262         /// If this is a payment for forwarding, this is the fee we are taking before forwarding the
263         /// HTLC.
264         ///
265         /// If this is a received payment, this is the fee that our counterparty took.
266         ///
267         /// This is used to allow LSPs to take fees as a part of payments, without the sender having to
268         /// shoulder them.
269         pub skimmed_fee_msat: Option<u64>,
270 }
271
272 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
273 pub(super) enum HTLCFailureMsg {
274         Relay(msgs::UpdateFailHTLC),
275         Malformed(msgs::UpdateFailMalformedHTLC),
276 }
277
278 /// Stores whether we can't forward an HTLC or relevant forwarding info
279 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
280 pub(super) enum PendingHTLCStatus {
281         Forward(PendingHTLCInfo),
282         Fail(HTLCFailureMsg),
283 }
284
285 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
286 pub(super) struct PendingAddHTLCInfo {
287         pub(super) forward_info: PendingHTLCInfo,
288
289         // These fields are produced in `forward_htlcs()` and consumed in
290         // `process_pending_htlc_forwards()` for constructing the
291         // `HTLCSource::PreviousHopData` for failed and forwarded
292         // HTLCs.
293         //
294         // Note that this may be an outbound SCID alias for the associated channel.
295         prev_short_channel_id: u64,
296         prev_htlc_id: u64,
297         prev_funding_outpoint: OutPoint,
298         prev_user_channel_id: u128,
299 }
300
301 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
302 pub(super) enum HTLCForwardInfo {
303         AddHTLC(PendingAddHTLCInfo),
304         FailHTLC {
305                 htlc_id: u64,
306                 err_packet: msgs::OnionErrorPacket,
307         },
308         FailMalformedHTLC {
309                 htlc_id: u64,
310                 failure_code: u16,
311                 sha256_of_onion: [u8; 32],
312         },
313 }
314
315 /// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node,
316 /// which determines the failure message that should be used.
317 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
318 pub enum BlindedFailure {
319         /// This HTLC is being failed backwards by the introduction node, and thus should be failed with
320         /// [`msgs::UpdateFailHTLC`] and error code `0x8000|0x4000|24`.
321         FromIntroductionNode,
322         /// This HTLC is being failed backwards by a blinded node within the path, and thus should be
323         /// failed with [`msgs::UpdateFailMalformedHTLC`] and error code `0x8000|0x4000|24`.
324         FromBlindedNode,
325 }
326
327 /// Tracks the inbound corresponding to an outbound HTLC
328 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
329 pub(crate) struct HTLCPreviousHopData {
330         // Note that this may be an outbound SCID alias for the associated channel.
331         short_channel_id: u64,
332         user_channel_id: Option<u128>,
333         htlc_id: u64,
334         incoming_packet_shared_secret: [u8; 32],
335         phantom_shared_secret: Option<[u8; 32]>,
336         blinded_failure: Option<BlindedFailure>,
337
338         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
339         // channel with a preimage provided by the forward channel.
340         outpoint: OutPoint,
341 }
342
343 enum OnionPayload {
344         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
345         Invoice {
346                 /// This is only here for backwards-compatibility in serialization, in the future it can be
347                 /// removed, breaking clients running 0.0.106 and earlier.
348                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
349         },
350         /// Contains the payer-provided preimage.
351         Spontaneous(PaymentPreimage),
352 }
353
354 /// HTLCs that are to us and can be failed/claimed by the user
355 struct ClaimableHTLC {
356         prev_hop: HTLCPreviousHopData,
357         cltv_expiry: u32,
358         /// The amount (in msats) of this MPP part
359         value: u64,
360         /// The amount (in msats) that the sender intended to be sent in this MPP
361         /// part (used for validating total MPP amount)
362         sender_intended_value: u64,
363         onion_payload: OnionPayload,
364         timer_ticks: u8,
365         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
366         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
367         total_value_received: Option<u64>,
368         /// The sender intended sum total of all MPP parts specified in the onion
369         total_msat: u64,
370         /// The extra fee our counterparty skimmed off the top of this HTLC.
371         counterparty_skimmed_fee_msat: Option<u64>,
372 }
373
374 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
375         fn from(val: &ClaimableHTLC) -> Self {
376                 events::ClaimedHTLC {
377                         channel_id: val.prev_hop.outpoint.to_channel_id(),
378                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
379                         cltv_expiry: val.cltv_expiry,
380                         value_msat: val.value,
381                         counterparty_skimmed_fee_msat: val.counterparty_skimmed_fee_msat.unwrap_or(0),
382                 }
383         }
384 }
385
386 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
387 /// a payment and ensure idempotency in LDK.
388 ///
389 /// This is not exported to bindings users as we just use [u8; 32] directly
390 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
391 pub struct PaymentId(pub [u8; Self::LENGTH]);
392
393 impl PaymentId {
394         /// Number of bytes in the id.
395         pub const LENGTH: usize = 32;
396 }
397
398 impl Writeable for PaymentId {
399         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
400                 self.0.write(w)
401         }
402 }
403
404 impl Readable for PaymentId {
405         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
406                 let buf: [u8; 32] = Readable::read(r)?;
407                 Ok(PaymentId(buf))
408         }
409 }
410
411 impl core::fmt::Display for PaymentId {
412         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
413                 crate::util::logger::DebugBytes(&self.0).fmt(f)
414         }
415 }
416
417 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
418 ///
419 /// This is not exported to bindings users as we just use [u8; 32] directly
420 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
421 pub struct InterceptId(pub [u8; 32]);
422
423 impl Writeable for InterceptId {
424         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
425                 self.0.write(w)
426         }
427 }
428
429 impl Readable for InterceptId {
430         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
431                 let buf: [u8; 32] = Readable::read(r)?;
432                 Ok(InterceptId(buf))
433         }
434 }
435
436 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
437 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
438 pub(crate) enum SentHTLCId {
439         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
440         OutboundRoute { session_priv: [u8; SECRET_KEY_SIZE] },
441 }
442 impl SentHTLCId {
443         pub(crate) fn from_source(source: &HTLCSource) -> Self {
444                 match source {
445                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
446                                 short_channel_id: hop_data.short_channel_id,
447                                 htlc_id: hop_data.htlc_id,
448                         },
449                         HTLCSource::OutboundRoute { session_priv, .. } =>
450                                 Self::OutboundRoute { session_priv: session_priv.secret_bytes() },
451                 }
452         }
453 }
454 impl_writeable_tlv_based_enum!(SentHTLCId,
455         (0, PreviousHopData) => {
456                 (0, short_channel_id, required),
457                 (2, htlc_id, required),
458         },
459         (2, OutboundRoute) => {
460                 (0, session_priv, required),
461         };
462 );
463
464
465 /// Tracks the inbound corresponding to an outbound HTLC
466 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
467 #[derive(Clone, Debug, PartialEq, Eq)]
468 pub(crate) enum HTLCSource {
469         PreviousHopData(HTLCPreviousHopData),
470         OutboundRoute {
471                 path: Path,
472                 session_priv: SecretKey,
473                 /// Technically we can recalculate this from the route, but we cache it here to avoid
474                 /// doing a double-pass on route when we get a failure back
475                 first_hop_htlc_msat: u64,
476                 payment_id: PaymentId,
477         },
478 }
479 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
480 impl core::hash::Hash for HTLCSource {
481         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
482                 match self {
483                         HTLCSource::PreviousHopData(prev_hop_data) => {
484                                 0u8.hash(hasher);
485                                 prev_hop_data.hash(hasher);
486                         },
487                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
488                                 1u8.hash(hasher);
489                                 path.hash(hasher);
490                                 session_priv[..].hash(hasher);
491                                 payment_id.hash(hasher);
492                                 first_hop_htlc_msat.hash(hasher);
493                         },
494                 }
495         }
496 }
497 impl HTLCSource {
498         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
499         #[cfg(test)]
500         pub fn dummy() -> Self {
501                 HTLCSource::OutboundRoute {
502                         path: Path { hops: Vec::new(), blinded_tail: None },
503                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
504                         first_hop_htlc_msat: 0,
505                         payment_id: PaymentId([2; 32]),
506                 }
507         }
508
509         #[cfg(debug_assertions)]
510         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
511         /// transaction. Useful to ensure different datastructures match up.
512         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
513                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
514                         *first_hop_htlc_msat == htlc.amount_msat
515                 } else {
516                         // There's nothing we can check for forwarded HTLCs
517                         true
518                 }
519         }
520 }
521
522 /// This enum is used to specify which error data to send to peers when failing back an HTLC
523 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
524 ///
525 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
526 #[derive(Clone, Copy)]
527 pub enum FailureCode {
528         /// We had a temporary error processing the payment. Useful if no other error codes fit
529         /// and you want to indicate that the payer may want to retry.
530         TemporaryNodeFailure,
531         /// We have a required feature which was not in this onion. For example, you may require
532         /// some additional metadata that was not provided with this payment.
533         RequiredNodeFeatureMissing,
534         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
535         /// the HTLC is too close to the current block height for safe handling.
536         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
537         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
538         IncorrectOrUnknownPaymentDetails,
539         /// We failed to process the payload after the onion was decrypted. You may wish to
540         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
541         ///
542         /// If available, the tuple data may include the type number and byte offset in the
543         /// decrypted byte stream where the failure occurred.
544         InvalidOnionPayload(Option<(u64, u16)>),
545 }
546
547 impl Into<u16> for FailureCode {
548     fn into(self) -> u16 {
549                 match self {
550                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
551                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
552                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
553                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
554                 }
555         }
556 }
557
558 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
559 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
560 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
561 /// peer_state lock. We then return the set of things that need to be done outside the lock in
562 /// this struct and call handle_error!() on it.
563
564 struct MsgHandleErrInternal {
565         err: msgs::LightningError,
566         closes_channel: bool,
567         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
568 }
569 impl MsgHandleErrInternal {
570         #[inline]
571         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
572                 Self {
573                         err: LightningError {
574                                 err: err.clone(),
575                                 action: msgs::ErrorAction::SendErrorMessage {
576                                         msg: msgs::ErrorMessage {
577                                                 channel_id,
578                                                 data: err
579                                         },
580                                 },
581                         },
582                         closes_channel: false,
583                         shutdown_finish: None,
584                 }
585         }
586         #[inline]
587         fn from_no_close(err: msgs::LightningError) -> Self {
588                 Self { err, closes_channel: false, shutdown_finish: None }
589         }
590         #[inline]
591         fn from_finish_shutdown(err: String, channel_id: ChannelId, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
592                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
593                 let action = if shutdown_res.monitor_update.is_some() {
594                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
595                         // should disconnect our peer such that we force them to broadcast their latest
596                         // commitment upon reconnecting.
597                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
598                 } else {
599                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
600                 };
601                 Self {
602                         err: LightningError { err, action },
603                         closes_channel: true,
604                         shutdown_finish: Some((shutdown_res, channel_update)),
605                 }
606         }
607         #[inline]
608         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
609                 Self {
610                         err: match err {
611                                 ChannelError::Warn(msg) =>  LightningError {
612                                         err: msg.clone(),
613                                         action: msgs::ErrorAction::SendWarningMessage {
614                                                 msg: msgs::WarningMessage {
615                                                         channel_id,
616                                                         data: msg
617                                                 },
618                                                 log_level: Level::Warn,
619                                         },
620                                 },
621                                 ChannelError::Ignore(msg) => LightningError {
622                                         err: msg,
623                                         action: msgs::ErrorAction::IgnoreError,
624                                 },
625                                 ChannelError::Close(msg) => LightningError {
626                                         err: msg.clone(),
627                                         action: msgs::ErrorAction::SendErrorMessage {
628                                                 msg: msgs::ErrorMessage {
629                                                         channel_id,
630                                                         data: msg
631                                                 },
632                                         },
633                                 },
634                         },
635                         closes_channel: false,
636                         shutdown_finish: None,
637                 }
638         }
639
640         fn closes_channel(&self) -> bool {
641                 self.closes_channel
642         }
643 }
644
645 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
646 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
647 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
648 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
649 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
650
651 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
652 /// be sent in the order they appear in the return value, however sometimes the order needs to be
653 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
654 /// they were originally sent). In those cases, this enum is also returned.
655 #[derive(Clone, PartialEq)]
656 pub(super) enum RAACommitmentOrder {
657         /// Send the CommitmentUpdate messages first
658         CommitmentFirst,
659         /// Send the RevokeAndACK message first
660         RevokeAndACKFirst,
661 }
662
663 /// Information about a payment which is currently being claimed.
664 struct ClaimingPayment {
665         amount_msat: u64,
666         payment_purpose: events::PaymentPurpose,
667         receiver_node_id: PublicKey,
668         htlcs: Vec<events::ClaimedHTLC>,
669         sender_intended_value: Option<u64>,
670 }
671 impl_writeable_tlv_based!(ClaimingPayment, {
672         (0, amount_msat, required),
673         (2, payment_purpose, required),
674         (4, receiver_node_id, required),
675         (5, htlcs, optional_vec),
676         (7, sender_intended_value, option),
677 });
678
679 struct ClaimablePayment {
680         purpose: events::PaymentPurpose,
681         onion_fields: Option<RecipientOnionFields>,
682         htlcs: Vec<ClaimableHTLC>,
683 }
684
685 /// Information about claimable or being-claimed payments
686 struct ClaimablePayments {
687         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
688         /// failed/claimed by the user.
689         ///
690         /// Note that, no consistency guarantees are made about the channels given here actually
691         /// existing anymore by the time you go to read them!
692         ///
693         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
694         /// we don't get a duplicate payment.
695         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
696
697         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
698         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
699         /// as an [`events::Event::PaymentClaimed`].
700         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
701 }
702
703 /// Events which we process internally but cannot be processed immediately at the generation site
704 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
705 /// running normally, and specifically must be processed before any other non-background
706 /// [`ChannelMonitorUpdate`]s are applied.
707 #[derive(Debug)]
708 enum BackgroundEvent {
709         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
710         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
711         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
712         /// channel has been force-closed we do not need the counterparty node_id.
713         ///
714         /// Note that any such events are lost on shutdown, so in general they must be updates which
715         /// are regenerated on startup.
716         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
717         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
718         /// channel to continue normal operation.
719         ///
720         /// In general this should be used rather than
721         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
722         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
723         /// error the other variant is acceptable.
724         ///
725         /// Note that any such events are lost on shutdown, so in general they must be updates which
726         /// are regenerated on startup.
727         MonitorUpdateRegeneratedOnStartup {
728                 counterparty_node_id: PublicKey,
729                 funding_txo: OutPoint,
730                 update: ChannelMonitorUpdate
731         },
732         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
733         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
734         /// on a channel.
735         MonitorUpdatesComplete {
736                 counterparty_node_id: PublicKey,
737                 channel_id: ChannelId,
738         },
739 }
740
741 #[derive(Debug)]
742 pub(crate) enum MonitorUpdateCompletionAction {
743         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
744         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
745         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
746         /// event can be generated.
747         PaymentClaimed { payment_hash: PaymentHash },
748         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
749         /// operation of another channel.
750         ///
751         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
752         /// from completing a monitor update which removes the payment preimage until the inbound edge
753         /// completes a monitor update containing the payment preimage. In that case, after the inbound
754         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
755         /// outbound edge.
756         EmitEventAndFreeOtherChannel {
757                 event: events::Event,
758                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
759         },
760         /// Indicates we should immediately resume the operation of another channel, unless there is
761         /// some other reason why the channel is blocked. In practice this simply means immediately
762         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
763         ///
764         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
765         /// from completing a monitor update which removes the payment preimage until the inbound edge
766         /// completes a monitor update containing the payment preimage. However, we use this variant
767         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
768         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
769         ///
770         /// This variant should thus never be written to disk, as it is processed inline rather than
771         /// stored for later processing.
772         FreeOtherChannelImmediately {
773                 downstream_counterparty_node_id: PublicKey,
774                 downstream_funding_outpoint: OutPoint,
775                 blocking_action: RAAMonitorUpdateBlockingAction,
776         },
777 }
778
779 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
780         (0, PaymentClaimed) => { (0, payment_hash, required) },
781         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
782         // *immediately*. However, for simplicity we implement read/write here.
783         (1, FreeOtherChannelImmediately) => {
784                 (0, downstream_counterparty_node_id, required),
785                 (2, downstream_funding_outpoint, required),
786                 (4, blocking_action, required),
787         },
788         (2, EmitEventAndFreeOtherChannel) => {
789                 (0, event, upgradable_required),
790                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
791                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
792                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
793                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
794                 // downgrades to prior versions.
795                 (1, downstream_counterparty_and_funding_outpoint, option),
796         },
797 );
798
799 #[derive(Clone, Debug, PartialEq, Eq)]
800 pub(crate) enum EventCompletionAction {
801         ReleaseRAAChannelMonitorUpdate {
802                 counterparty_node_id: PublicKey,
803                 channel_funding_outpoint: OutPoint,
804         },
805 }
806 impl_writeable_tlv_based_enum!(EventCompletionAction,
807         (0, ReleaseRAAChannelMonitorUpdate) => {
808                 (0, channel_funding_outpoint, required),
809                 (2, counterparty_node_id, required),
810         };
811 );
812
813 #[derive(Clone, PartialEq, Eq, Debug)]
814 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
815 /// the blocked action here. See enum variants for more info.
816 pub(crate) enum RAAMonitorUpdateBlockingAction {
817         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
818         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
819         /// durably to disk.
820         ForwardedPaymentInboundClaim {
821                 /// The upstream channel ID (i.e. the inbound edge).
822                 channel_id: ChannelId,
823                 /// The HTLC ID on the inbound edge.
824                 htlc_id: u64,
825         },
826 }
827
828 impl RAAMonitorUpdateBlockingAction {
829         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
830                 Self::ForwardedPaymentInboundClaim {
831                         channel_id: prev_hop.outpoint.to_channel_id(),
832                         htlc_id: prev_hop.htlc_id,
833                 }
834         }
835 }
836
837 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
838         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
839 ;);
840
841
842 /// State we hold per-peer.
843 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
844         /// `channel_id` -> `ChannelPhase`
845         ///
846         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
847         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
848         /// `temporary_channel_id` -> `InboundChannelRequest`.
849         ///
850         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
851         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
852         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
853         /// the channel is rejected, then the entry is simply removed.
854         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
855         /// The latest `InitFeatures` we heard from the peer.
856         latest_features: InitFeatures,
857         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
858         /// for broadcast messages, where ordering isn't as strict).
859         pub(super) pending_msg_events: Vec<MessageSendEvent>,
860         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
861         /// user but which have not yet completed.
862         ///
863         /// Note that the channel may no longer exist. For example if the channel was closed but we
864         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
865         /// for a missing channel.
866         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
867         /// Map from a specific channel to some action(s) that should be taken when all pending
868         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
869         ///
870         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
871         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
872         /// channels with a peer this will just be one allocation and will amount to a linear list of
873         /// channels to walk, avoiding the whole hashing rigmarole.
874         ///
875         /// Note that the channel may no longer exist. For example, if a channel was closed but we
876         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
877         /// for a missing channel. While a malicious peer could construct a second channel with the
878         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
879         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
880         /// duplicates do not occur, so such channels should fail without a monitor update completing.
881         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
882         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
883         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
884         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
885         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
886         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
887         /// The peer is currently connected (i.e. we've seen a
888         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
889         /// [`ChannelMessageHandler::peer_disconnected`].
890         is_connected: bool,
891 }
892
893 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
894         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
895         /// If true is passed for `require_disconnected`, the function will return false if we haven't
896         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
897         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
898                 if require_disconnected && self.is_connected {
899                         return false
900                 }
901                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
902                         && self.monitor_update_blocked_actions.is_empty()
903                         && self.in_flight_monitor_updates.is_empty()
904         }
905
906         // Returns a count of all channels we have with this peer, including unfunded channels.
907         fn total_channel_count(&self) -> usize {
908                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
909         }
910
911         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
912         fn has_channel(&self, channel_id: &ChannelId) -> bool {
913                 self.channel_by_id.contains_key(channel_id) ||
914                         self.inbound_channel_request_by_id.contains_key(channel_id)
915         }
916 }
917
918 /// A not-yet-accepted inbound (from counterparty) channel. Once
919 /// accepted, the parameters will be used to construct a channel.
920 pub(super) struct InboundChannelRequest {
921         /// The original OpenChannel message.
922         pub open_channel_msg: msgs::OpenChannel,
923         /// The number of ticks remaining before the request expires.
924         pub ticks_remaining: i32,
925 }
926
927 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
928 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
929 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
930
931 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
932 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
933 ///
934 /// For users who don't want to bother doing their own payment preimage storage, we also store that
935 /// here.
936 ///
937 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
938 /// and instead encoding it in the payment secret.
939 struct PendingInboundPayment {
940         /// The payment secret that the sender must use for us to accept this payment
941         payment_secret: PaymentSecret,
942         /// Time at which this HTLC expires - blocks with a header time above this value will result in
943         /// this payment being removed.
944         expiry_time: u64,
945         /// Arbitrary identifier the user specifies (or not)
946         user_payment_id: u64,
947         // Other required attributes of the payment, optionally enforced:
948         payment_preimage: Option<PaymentPreimage>,
949         min_value_msat: Option<u64>,
950 }
951
952 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
953 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
954 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
955 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
956 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
957 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
958 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
959 /// of [`KeysManager`] and [`DefaultRouter`].
960 ///
961 /// This is not exported to bindings users as type aliases aren't supported in most languages.
962 #[cfg(not(c_bindings))]
963 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
964         Arc<M>,
965         Arc<T>,
966         Arc<KeysManager>,
967         Arc<KeysManager>,
968         Arc<KeysManager>,
969         Arc<F>,
970         Arc<DefaultRouter<
971                 Arc<NetworkGraph<Arc<L>>>,
972                 Arc<L>,
973                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
974                 ProbabilisticScoringFeeParameters,
975                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
976         >>,
977         Arc<L>
978 >;
979
980 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
981 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
982 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
983 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
984 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
985 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
986 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
987 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
988 /// of [`KeysManager`] and [`DefaultRouter`].
989 ///
990 /// This is not exported to bindings users as type aliases aren't supported in most languages.
991 #[cfg(not(c_bindings))]
992 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
993         ChannelManager<
994                 &'a M,
995                 &'b T,
996                 &'c KeysManager,
997                 &'c KeysManager,
998                 &'c KeysManager,
999                 &'d F,
1000                 &'e DefaultRouter<
1001                         &'f NetworkGraph<&'g L>,
1002                         &'g L,
1003                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
1004                         ProbabilisticScoringFeeParameters,
1005                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
1006                 >,
1007                 &'g L
1008         >;
1009
1010 /// A trivial trait which describes any [`ChannelManager`].
1011 ///
1012 /// This is not exported to bindings users as general cover traits aren't useful in other
1013 /// languages.
1014 pub trait AChannelManager {
1015         /// A type implementing [`chain::Watch`].
1016         type Watch: chain::Watch<Self::Signer> + ?Sized;
1017         /// A type that may be dereferenced to [`Self::Watch`].
1018         type M: Deref<Target = Self::Watch>;
1019         /// A type implementing [`BroadcasterInterface`].
1020         type Broadcaster: BroadcasterInterface + ?Sized;
1021         /// A type that may be dereferenced to [`Self::Broadcaster`].
1022         type T: Deref<Target = Self::Broadcaster>;
1023         /// A type implementing [`EntropySource`].
1024         type EntropySource: EntropySource + ?Sized;
1025         /// A type that may be dereferenced to [`Self::EntropySource`].
1026         type ES: Deref<Target = Self::EntropySource>;
1027         /// A type implementing [`NodeSigner`].
1028         type NodeSigner: NodeSigner + ?Sized;
1029         /// A type that may be dereferenced to [`Self::NodeSigner`].
1030         type NS: Deref<Target = Self::NodeSigner>;
1031         /// A type implementing [`WriteableEcdsaChannelSigner`].
1032         type Signer: WriteableEcdsaChannelSigner + Sized;
1033         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
1034         type SignerProvider: SignerProvider<EcdsaSigner= Self::Signer> + ?Sized;
1035         /// A type that may be dereferenced to [`Self::SignerProvider`].
1036         type SP: Deref<Target = Self::SignerProvider>;
1037         /// A type implementing [`FeeEstimator`].
1038         type FeeEstimator: FeeEstimator + ?Sized;
1039         /// A type that may be dereferenced to [`Self::FeeEstimator`].
1040         type F: Deref<Target = Self::FeeEstimator>;
1041         /// A type implementing [`Router`].
1042         type Router: Router + ?Sized;
1043         /// A type that may be dereferenced to [`Self::Router`].
1044         type R: Deref<Target = Self::Router>;
1045         /// A type implementing [`Logger`].
1046         type Logger: Logger + ?Sized;
1047         /// A type that may be dereferenced to [`Self::Logger`].
1048         type L: Deref<Target = Self::Logger>;
1049         /// Returns a reference to the actual [`ChannelManager`] object.
1050         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
1051 }
1052
1053 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
1054 for ChannelManager<M, T, ES, NS, SP, F, R, L>
1055 where
1056         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1057         T::Target: BroadcasterInterface,
1058         ES::Target: EntropySource,
1059         NS::Target: NodeSigner,
1060         SP::Target: SignerProvider,
1061         F::Target: FeeEstimator,
1062         R::Target: Router,
1063         L::Target: Logger,
1064 {
1065         type Watch = M::Target;
1066         type M = M;
1067         type Broadcaster = T::Target;
1068         type T = T;
1069         type EntropySource = ES::Target;
1070         type ES = ES;
1071         type NodeSigner = NS::Target;
1072         type NS = NS;
1073         type Signer = <SP::Target as SignerProvider>::EcdsaSigner;
1074         type SignerProvider = SP::Target;
1075         type SP = SP;
1076         type FeeEstimator = F::Target;
1077         type F = F;
1078         type Router = R::Target;
1079         type R = R;
1080         type Logger = L::Target;
1081         type L = L;
1082         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
1083 }
1084
1085 /// Manager which keeps track of a number of channels and sends messages to the appropriate
1086 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
1087 ///
1088 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
1089 /// to individual Channels.
1090 ///
1091 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
1092 /// all peers during write/read (though does not modify this instance, only the instance being
1093 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
1094 /// called [`funding_transaction_generated`] for outbound channels) being closed.
1095 ///
1096 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
1097 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
1098 /// [`ChannelMonitorUpdate`] before returning from
1099 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
1100 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
1101 /// `ChannelManager` operations from occurring during the serialization process). If the
1102 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
1103 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
1104 /// will be lost (modulo on-chain transaction fees).
1105 ///
1106 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
1107 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
1108 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
1109 ///
1110 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
1111 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
1112 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
1113 /// offline for a full minute. In order to track this, you must call
1114 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1115 ///
1116 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1117 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1118 /// not have a channel with being unable to connect to us or open new channels with us if we have
1119 /// many peers with unfunded channels.
1120 ///
1121 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1122 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1123 /// never limited. Please ensure you limit the count of such channels yourself.
1124 ///
1125 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1126 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1127 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1128 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1129 /// you're using lightning-net-tokio.
1130 ///
1131 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1132 /// [`funding_created`]: msgs::FundingCreated
1133 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1134 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1135 /// [`update_channel`]: chain::Watch::update_channel
1136 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1137 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1138 /// [`read`]: ReadableArgs::read
1139 //
1140 // Lock order:
1141 // The tree structure below illustrates the lock order requirements for the different locks of the
1142 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1143 // and should then be taken in the order of the lowest to the highest level in the tree.
1144 // Note that locks on different branches shall not be taken at the same time, as doing so will
1145 // create a new lock order for those specific locks in the order they were taken.
1146 //
1147 // Lock order tree:
1148 //
1149 // `pending_offers_messages`
1150 //
1151 // `total_consistency_lock`
1152 //  |
1153 //  |__`forward_htlcs`
1154 //  |   |
1155 //  |   |__`pending_intercepted_htlcs`
1156 //  |
1157 //  |__`per_peer_state`
1158 //      |
1159 //      |__`pending_inbound_payments`
1160 //          |
1161 //          |__`claimable_payments`
1162 //          |
1163 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1164 //              |
1165 //              |__`peer_state`
1166 //                  |
1167 //                  |__`outpoint_to_peer`
1168 //                  |
1169 //                  |__`short_to_chan_info`
1170 //                  |
1171 //                  |__`outbound_scid_aliases`
1172 //                  |
1173 //                  |__`best_block`
1174 //                  |
1175 //                  |__`pending_events`
1176 //                      |
1177 //                      |__`pending_background_events`
1178 //
1179 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1180 where
1181         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1182         T::Target: BroadcasterInterface,
1183         ES::Target: EntropySource,
1184         NS::Target: NodeSigner,
1185         SP::Target: SignerProvider,
1186         F::Target: FeeEstimator,
1187         R::Target: Router,
1188         L::Target: Logger,
1189 {
1190         default_configuration: UserConfig,
1191         chain_hash: ChainHash,
1192         fee_estimator: LowerBoundedFeeEstimator<F>,
1193         chain_monitor: M,
1194         tx_broadcaster: T,
1195         #[allow(unused)]
1196         router: R,
1197
1198         /// See `ChannelManager` struct-level documentation for lock order requirements.
1199         #[cfg(test)]
1200         pub(super) best_block: RwLock<BestBlock>,
1201         #[cfg(not(test))]
1202         best_block: RwLock<BestBlock>,
1203         secp_ctx: Secp256k1<secp256k1::All>,
1204
1205         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1206         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1207         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1208         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1209         ///
1210         /// See `ChannelManager` struct-level documentation for lock order requirements.
1211         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1212
1213         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1214         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1215         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1216         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1217         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1218         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1219         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1220         /// after reloading from disk while replaying blocks against ChannelMonitors.
1221         ///
1222         /// See `PendingOutboundPayment` documentation for more info.
1223         ///
1224         /// See `ChannelManager` struct-level documentation for lock order requirements.
1225         pending_outbound_payments: OutboundPayments,
1226
1227         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1228         ///
1229         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1230         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1231         /// and via the classic SCID.
1232         ///
1233         /// Note that no consistency guarantees are made about the existence of a channel with the
1234         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1235         ///
1236         /// See `ChannelManager` struct-level documentation for lock order requirements.
1237         #[cfg(test)]
1238         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1239         #[cfg(not(test))]
1240         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1241         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1242         /// until the user tells us what we should do with them.
1243         ///
1244         /// See `ChannelManager` struct-level documentation for lock order requirements.
1245         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1246
1247         /// The sets of payments which are claimable or currently being claimed. See
1248         /// [`ClaimablePayments`]' individual field docs for more info.
1249         ///
1250         /// See `ChannelManager` struct-level documentation for lock order requirements.
1251         claimable_payments: Mutex<ClaimablePayments>,
1252
1253         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1254         /// and some closed channels which reached a usable state prior to being closed. This is used
1255         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1256         /// active channel list on load.
1257         ///
1258         /// See `ChannelManager` struct-level documentation for lock order requirements.
1259         outbound_scid_aliases: Mutex<HashSet<u64>>,
1260
1261         /// Channel funding outpoint -> `counterparty_node_id`.
1262         ///
1263         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1264         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1265         /// the handling of the events.
1266         ///
1267         /// Note that no consistency guarantees are made about the existence of a peer with the
1268         /// `counterparty_node_id` in our other maps.
1269         ///
1270         /// TODO:
1271         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1272         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1273         /// would break backwards compatability.
1274         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1275         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1276         /// required to access the channel with the `counterparty_node_id`.
1277         ///
1278         /// See `ChannelManager` struct-level documentation for lock order requirements.
1279         #[cfg(not(test))]
1280         outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1281         #[cfg(test)]
1282         pub(crate) outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1283
1284         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1285         ///
1286         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1287         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1288         /// confirmation depth.
1289         ///
1290         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1291         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1292         /// channel with the `channel_id` in our other maps.
1293         ///
1294         /// See `ChannelManager` struct-level documentation for lock order requirements.
1295         #[cfg(test)]
1296         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1297         #[cfg(not(test))]
1298         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1299
1300         our_network_pubkey: PublicKey,
1301
1302         inbound_payment_key: inbound_payment::ExpandedKey,
1303
1304         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1305         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1306         /// we encrypt the namespace identifier using these bytes.
1307         ///
1308         /// [fake scids]: crate::util::scid_utils::fake_scid
1309         fake_scid_rand_bytes: [u8; 32],
1310
1311         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1312         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1313         /// keeping additional state.
1314         probing_cookie_secret: [u8; 32],
1315
1316         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1317         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1318         /// very far in the past, and can only ever be up to two hours in the future.
1319         highest_seen_timestamp: AtomicUsize,
1320
1321         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1322         /// basis, as well as the peer's latest features.
1323         ///
1324         /// If we are connected to a peer we always at least have an entry here, even if no channels
1325         /// are currently open with that peer.
1326         ///
1327         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1328         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1329         /// channels.
1330         ///
1331         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1332         ///
1333         /// See `ChannelManager` struct-level documentation for lock order requirements.
1334         #[cfg(not(any(test, feature = "_test_utils")))]
1335         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1336         #[cfg(any(test, feature = "_test_utils"))]
1337         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1338
1339         /// The set of events which we need to give to the user to handle. In some cases an event may
1340         /// require some further action after the user handles it (currently only blocking a monitor
1341         /// update from being handed to the user to ensure the included changes to the channel state
1342         /// are handled by the user before they're persisted durably to disk). In that case, the second
1343         /// element in the tuple is set to `Some` with further details of the action.
1344         ///
1345         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1346         /// could be in the middle of being processed without the direct mutex held.
1347         ///
1348         /// See `ChannelManager` struct-level documentation for lock order requirements.
1349         #[cfg(not(any(test, feature = "_test_utils")))]
1350         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1351         #[cfg(any(test, feature = "_test_utils"))]
1352         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1353
1354         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1355         pending_events_processor: AtomicBool,
1356
1357         /// If we are running during init (either directly during the deserialization method or in
1358         /// block connection methods which run after deserialization but before normal operation) we
1359         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1360         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1361         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1362         ///
1363         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1364         ///
1365         /// See `ChannelManager` struct-level documentation for lock order requirements.
1366         ///
1367         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1368         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1369         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1370         /// Essentially just when we're serializing ourselves out.
1371         /// Taken first everywhere where we are making changes before any other locks.
1372         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1373         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1374         /// Notifier the lock contains sends out a notification when the lock is released.
1375         total_consistency_lock: RwLock<()>,
1376         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1377         /// received and the monitor has been persisted.
1378         ///
1379         /// This information does not need to be persisted as funding nodes can forget
1380         /// unfunded channels upon disconnection.
1381         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1382
1383         background_events_processed_since_startup: AtomicBool,
1384
1385         event_persist_notifier: Notifier,
1386         needs_persist_flag: AtomicBool,
1387
1388         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1389
1390         entropy_source: ES,
1391         node_signer: NS,
1392         signer_provider: SP,
1393
1394         logger: L,
1395 }
1396
1397 /// Chain-related parameters used to construct a new `ChannelManager`.
1398 ///
1399 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1400 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1401 /// are not needed when deserializing a previously constructed `ChannelManager`.
1402 #[derive(Clone, Copy, PartialEq)]
1403 pub struct ChainParameters {
1404         /// The network for determining the `chain_hash` in Lightning messages.
1405         pub network: Network,
1406
1407         /// The hash and height of the latest block successfully connected.
1408         ///
1409         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1410         pub best_block: BestBlock,
1411 }
1412
1413 #[derive(Copy, Clone, PartialEq)]
1414 #[must_use]
1415 enum NotifyOption {
1416         DoPersist,
1417         SkipPersistHandleEvents,
1418         SkipPersistNoEvents,
1419 }
1420
1421 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1422 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1423 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1424 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1425 /// sending the aforementioned notification (since the lock being released indicates that the
1426 /// updates are ready for persistence).
1427 ///
1428 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1429 /// notify or not based on whether relevant changes have been made, providing a closure to
1430 /// `optionally_notify` which returns a `NotifyOption`.
1431 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1432         event_persist_notifier: &'a Notifier,
1433         needs_persist_flag: &'a AtomicBool,
1434         should_persist: F,
1435         // We hold onto this result so the lock doesn't get released immediately.
1436         _read_guard: RwLockReadGuard<'a, ()>,
1437 }
1438
1439 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1440         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1441         /// events to handle.
1442         ///
1443         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1444         /// other cases where losing the changes on restart may result in a force-close or otherwise
1445         /// isn't ideal.
1446         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1447                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1448         }
1449
1450         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1451         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1452                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1453                 let force_notify = cm.get_cm().process_background_events();
1454
1455                 PersistenceNotifierGuard {
1456                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1457                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1458                         should_persist: move || {
1459                                 // Pick the "most" action between `persist_check` and the background events
1460                                 // processing and return that.
1461                                 let notify = persist_check();
1462                                 match (notify, force_notify) {
1463                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1464                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1465                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1466                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1467                                         _ => NotifyOption::SkipPersistNoEvents,
1468                                 }
1469                         },
1470                         _read_guard: read_guard,
1471                 }
1472         }
1473
1474         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1475         /// [`ChannelManager::process_background_events`] MUST be called first (or
1476         /// [`Self::optionally_notify`] used).
1477         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1478         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1479                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1480
1481                 PersistenceNotifierGuard {
1482                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1483                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1484                         should_persist: persist_check,
1485                         _read_guard: read_guard,
1486                 }
1487         }
1488 }
1489
1490 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1491         fn drop(&mut self) {
1492                 match (self.should_persist)() {
1493                         NotifyOption::DoPersist => {
1494                                 self.needs_persist_flag.store(true, Ordering::Release);
1495                                 self.event_persist_notifier.notify()
1496                         },
1497                         NotifyOption::SkipPersistHandleEvents =>
1498                                 self.event_persist_notifier.notify(),
1499                         NotifyOption::SkipPersistNoEvents => {},
1500                 }
1501         }
1502 }
1503
1504 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1505 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1506 ///
1507 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1508 ///
1509 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1510 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1511 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1512 /// the maximum required amount in lnd as of March 2021.
1513 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1514
1515 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1516 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1517 ///
1518 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1519 ///
1520 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1521 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1522 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1523 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1524 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1525 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1526 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1527 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1528 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1529 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1530 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1531 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1532 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1533
1534 /// Minimum CLTV difference between the current block height and received inbound payments.
1535 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1536 /// this value.
1537 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1538 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1539 // a payment was being routed, so we add an extra block to be safe.
1540 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1541
1542 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1543 // ie that if the next-hop peer fails the HTLC within
1544 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1545 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1546 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1547 // LATENCY_GRACE_PERIOD_BLOCKS.
1548 #[allow(dead_code)]
1549 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;
1550
1551 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1552 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1553 #[allow(dead_code)]
1554 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1555
1556 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1557 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1558
1559 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1560 /// until we mark the channel disabled and gossip the update.
1561 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1562
1563 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1564 /// we mark the channel enabled and gossip the update.
1565 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1566
1567 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1568 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1569 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1570 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1571
1572 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1573 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1574 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1575
1576 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1577 /// many peers we reject new (inbound) connections.
1578 const MAX_NO_CHANNEL_PEERS: usize = 250;
1579
1580 /// Information needed for constructing an invoice route hint for this channel.
1581 #[derive(Clone, Debug, PartialEq)]
1582 pub struct CounterpartyForwardingInfo {
1583         /// Base routing fee in millisatoshis.
1584         pub fee_base_msat: u32,
1585         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1586         pub fee_proportional_millionths: u32,
1587         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1588         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1589         /// `cltv_expiry_delta` for more details.
1590         pub cltv_expiry_delta: u16,
1591 }
1592
1593 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1594 /// to better separate parameters.
1595 #[derive(Clone, Debug, PartialEq)]
1596 pub struct ChannelCounterparty {
1597         /// The node_id of our counterparty
1598         pub node_id: PublicKey,
1599         /// The Features the channel counterparty provided upon last connection.
1600         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1601         /// many routing-relevant features are present in the init context.
1602         pub features: InitFeatures,
1603         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1604         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1605         /// claiming at least this value on chain.
1606         ///
1607         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1608         ///
1609         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1610         pub unspendable_punishment_reserve: u64,
1611         /// Information on the fees and requirements that the counterparty requires when forwarding
1612         /// payments to us through this channel.
1613         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1614         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1615         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1616         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1617         pub outbound_htlc_minimum_msat: Option<u64>,
1618         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1619         pub outbound_htlc_maximum_msat: Option<u64>,
1620 }
1621
1622 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1623 #[derive(Clone, Debug, PartialEq)]
1624 pub struct ChannelDetails {
1625         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1626         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1627         /// Note that this means this value is *not* persistent - it can change once during the
1628         /// lifetime of the channel.
1629         pub channel_id: ChannelId,
1630         /// Parameters which apply to our counterparty. See individual fields for more information.
1631         pub counterparty: ChannelCounterparty,
1632         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1633         /// our counterparty already.
1634         ///
1635         /// Note that, if this has been set, `channel_id` will be equivalent to
1636         /// `funding_txo.unwrap().to_channel_id()`.
1637         pub funding_txo: Option<OutPoint>,
1638         /// The features which this channel operates with. See individual features for more info.
1639         ///
1640         /// `None` until negotiation completes and the channel type is finalized.
1641         pub channel_type: Option<ChannelTypeFeatures>,
1642         /// The position of the funding transaction in the chain. None if the funding transaction has
1643         /// not yet been confirmed and the channel fully opened.
1644         ///
1645         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1646         /// payments instead of this. See [`get_inbound_payment_scid`].
1647         ///
1648         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1649         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1650         ///
1651         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1652         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1653         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1654         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1655         /// [`confirmations_required`]: Self::confirmations_required
1656         pub short_channel_id: Option<u64>,
1657         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1658         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1659         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1660         /// `Some(0)`).
1661         ///
1662         /// This will be `None` as long as the channel is not available for routing outbound payments.
1663         ///
1664         /// [`short_channel_id`]: Self::short_channel_id
1665         /// [`confirmations_required`]: Self::confirmations_required
1666         pub outbound_scid_alias: Option<u64>,
1667         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1668         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1669         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1670         /// when they see a payment to be routed to us.
1671         ///
1672         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1673         /// previous values for inbound payment forwarding.
1674         ///
1675         /// [`short_channel_id`]: Self::short_channel_id
1676         pub inbound_scid_alias: Option<u64>,
1677         /// The value, in satoshis, of this channel as appears in the funding output
1678         pub channel_value_satoshis: u64,
1679         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1680         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1681         /// this value on chain.
1682         ///
1683         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1684         ///
1685         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1686         ///
1687         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1688         pub unspendable_punishment_reserve: Option<u64>,
1689         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1690         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1691         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1692         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1693         /// serialized with LDK versions prior to 0.0.113.
1694         ///
1695         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1696         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1697         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1698         pub user_channel_id: u128,
1699         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1700         /// which is applied to commitment and HTLC transactions.
1701         ///
1702         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1703         pub feerate_sat_per_1000_weight: Option<u32>,
1704         /// Our total balance.  This is the amount we would get if we close the channel.
1705         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1706         /// amount is not likely to be recoverable on close.
1707         ///
1708         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1709         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1710         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1711         /// This does not consider any on-chain fees.
1712         ///
1713         /// See also [`ChannelDetails::outbound_capacity_msat`]
1714         pub balance_msat: u64,
1715         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1716         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1717         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1718         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1719         ///
1720         /// See also [`ChannelDetails::balance_msat`]
1721         ///
1722         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1723         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1724         /// should be able to spend nearly this amount.
1725         pub outbound_capacity_msat: u64,
1726         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1727         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1728         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1729         /// to use a limit as close as possible to the HTLC limit we can currently send.
1730         ///
1731         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1732         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1733         pub next_outbound_htlc_limit_msat: u64,
1734         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1735         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1736         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1737         /// route which is valid.
1738         pub next_outbound_htlc_minimum_msat: u64,
1739         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1740         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1741         /// available for inclusion in new inbound HTLCs).
1742         /// Note that there are some corner cases not fully handled here, so the actual available
1743         /// inbound capacity may be slightly higher than this.
1744         ///
1745         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1746         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1747         /// However, our counterparty should be able to spend nearly this amount.
1748         pub inbound_capacity_msat: u64,
1749         /// The number of required confirmations on the funding transaction before the funding will be
1750         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1751         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1752         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1753         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1754         ///
1755         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1756         ///
1757         /// [`is_outbound`]: ChannelDetails::is_outbound
1758         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1759         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1760         pub confirmations_required: Option<u32>,
1761         /// The current number of confirmations on the funding transaction.
1762         ///
1763         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1764         pub confirmations: Option<u32>,
1765         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1766         /// until we can claim our funds after we force-close the channel. During this time our
1767         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1768         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1769         /// time to claim our non-HTLC-encumbered funds.
1770         ///
1771         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1772         pub force_close_spend_delay: Option<u16>,
1773         /// True if the channel was initiated (and thus funded) by us.
1774         pub is_outbound: bool,
1775         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1776         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1777         /// required confirmation count has been reached (and we were connected to the peer at some
1778         /// point after the funding transaction received enough confirmations). The required
1779         /// confirmation count is provided in [`confirmations_required`].
1780         ///
1781         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1782         pub is_channel_ready: bool,
1783         /// The stage of the channel's shutdown.
1784         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1785         pub channel_shutdown_state: Option<ChannelShutdownState>,
1786         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1787         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1788         ///
1789         /// This is a strict superset of `is_channel_ready`.
1790         pub is_usable: bool,
1791         /// True if this channel is (or will be) publicly-announced.
1792         pub is_public: bool,
1793         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1794         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1795         pub inbound_htlc_minimum_msat: Option<u64>,
1796         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1797         pub inbound_htlc_maximum_msat: Option<u64>,
1798         /// Set of configurable parameters that affect channel operation.
1799         ///
1800         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1801         pub config: Option<ChannelConfig>,
1802 }
1803
1804 impl ChannelDetails {
1805         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1806         /// This should be used for providing invoice hints or in any other context where our
1807         /// counterparty will forward a payment to us.
1808         ///
1809         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1810         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1811         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1812                 self.inbound_scid_alias.or(self.short_channel_id)
1813         }
1814
1815         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1816         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1817         /// we're sending or forwarding a payment outbound over this channel.
1818         ///
1819         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1820         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1821         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1822                 self.short_channel_id.or(self.outbound_scid_alias)
1823         }
1824
1825         fn from_channel_context<SP: Deref, F: Deref>(
1826                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1827                 fee_estimator: &LowerBoundedFeeEstimator<F>
1828         ) -> Self
1829         where
1830                 SP::Target: SignerProvider,
1831                 F::Target: FeeEstimator
1832         {
1833                 let balance = context.get_available_balances(fee_estimator);
1834                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1835                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1836                 ChannelDetails {
1837                         channel_id: context.channel_id(),
1838                         counterparty: ChannelCounterparty {
1839                                 node_id: context.get_counterparty_node_id(),
1840                                 features: latest_features,
1841                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1842                                 forwarding_info: context.counterparty_forwarding_info(),
1843                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1844                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1845                                 // message (as they are always the first message from the counterparty).
1846                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1847                                 // default `0` value set by `Channel::new_outbound`.
1848                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1849                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1850                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1851                         },
1852                         funding_txo: context.get_funding_txo(),
1853                         // Note that accept_channel (or open_channel) is always the first message, so
1854                         // `have_received_message` indicates that type negotiation has completed.
1855                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1856                         short_channel_id: context.get_short_channel_id(),
1857                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1858                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1859                         channel_value_satoshis: context.get_value_satoshis(),
1860                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1861                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1862                         balance_msat: balance.balance_msat,
1863                         inbound_capacity_msat: balance.inbound_capacity_msat,
1864                         outbound_capacity_msat: balance.outbound_capacity_msat,
1865                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1866                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1867                         user_channel_id: context.get_user_id(),
1868                         confirmations_required: context.minimum_depth(),
1869                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1870                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1871                         is_outbound: context.is_outbound(),
1872                         is_channel_ready: context.is_usable(),
1873                         is_usable: context.is_live(),
1874                         is_public: context.should_announce(),
1875                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1876                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1877                         config: Some(context.config()),
1878                         channel_shutdown_state: Some(context.shutdown_state()),
1879                 }
1880         }
1881 }
1882
1883 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1884 /// Further information on the details of the channel shutdown.
1885 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1886 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1887 /// the channel will be removed shortly.
1888 /// Also note, that in normal operation, peers could disconnect at any of these states
1889 /// and require peer re-connection before making progress onto other states
1890 pub enum ChannelShutdownState {
1891         /// Channel has not sent or received a shutdown message.
1892         NotShuttingDown,
1893         /// Local node has sent a shutdown message for this channel.
1894         ShutdownInitiated,
1895         /// Shutdown message exchanges have concluded and the channels are in the midst of
1896         /// resolving all existing open HTLCs before closing can continue.
1897         ResolvingHTLCs,
1898         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1899         NegotiatingClosingFee,
1900         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1901         /// to drop the channel.
1902         ShutdownComplete,
1903 }
1904
1905 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1906 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1907 #[derive(Debug, PartialEq)]
1908 pub enum RecentPaymentDetails {
1909         /// When an invoice was requested and thus a payment has not yet been sent.
1910         AwaitingInvoice {
1911                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1912                 /// a payment and ensure idempotency in LDK.
1913                 payment_id: PaymentId,
1914         },
1915         /// When a payment is still being sent and awaiting successful delivery.
1916         Pending {
1917                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1918                 /// a payment and ensure idempotency in LDK.
1919                 payment_id: PaymentId,
1920                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1921                 /// abandoned.
1922                 payment_hash: PaymentHash,
1923                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1924                 /// not just the amount currently inflight.
1925                 total_msat: u64,
1926         },
1927         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1928         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1929         /// payment is removed from tracking.
1930         Fulfilled {
1931                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1932                 /// a payment and ensure idempotency in LDK.
1933                 payment_id: PaymentId,
1934                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1935                 /// made before LDK version 0.0.104.
1936                 payment_hash: Option<PaymentHash>,
1937         },
1938         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1939         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1940         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1941         Abandoned {
1942                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1943                 /// a payment and ensure idempotency in LDK.
1944                 payment_id: PaymentId,
1945                 /// Hash of the payment that we have given up trying to send.
1946                 payment_hash: PaymentHash,
1947         },
1948 }
1949
1950 /// Route hints used in constructing invoices for [phantom node payents].
1951 ///
1952 /// [phantom node payments]: crate::sign::PhantomKeysManager
1953 #[derive(Clone)]
1954 pub struct PhantomRouteHints {
1955         /// The list of channels to be included in the invoice route hints.
1956         pub channels: Vec<ChannelDetails>,
1957         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1958         /// route hints.
1959         pub phantom_scid: u64,
1960         /// The pubkey of the real backing node that would ultimately receive the payment.
1961         pub real_node_pubkey: PublicKey,
1962 }
1963
1964 macro_rules! handle_error {
1965         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1966                 // In testing, ensure there are no deadlocks where the lock is already held upon
1967                 // entering the macro.
1968                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1969                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1970
1971                 match $internal {
1972                         Ok(msg) => Ok(msg),
1973                         Err(MsgHandleErrInternal { err, shutdown_finish, .. }) => {
1974                                 let mut msg_events = Vec::with_capacity(2);
1975
1976                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1977                                         let counterparty_node_id = shutdown_res.counterparty_node_id;
1978                                         let channel_id = shutdown_res.channel_id;
1979                                         let logger = WithContext::from(
1980                                                 &$self.logger, Some(counterparty_node_id), Some(channel_id),
1981                                         );
1982                                         log_error!(logger, "Force-closing channel: {}", err.err);
1983
1984                                         $self.finish_close_channel(shutdown_res);
1985                                         if let Some(update) = update_option {
1986                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1987                                                         msg: update
1988                                                 });
1989                                         }
1990                                 } else {
1991                                         log_error!($self.logger, "Got non-closing error: {}", err.err);
1992                                 }
1993
1994                                 if let msgs::ErrorAction::IgnoreError = err.action {
1995                                 } else {
1996                                         msg_events.push(events::MessageSendEvent::HandleError {
1997                                                 node_id: $counterparty_node_id,
1998                                                 action: err.action.clone()
1999                                         });
2000                                 }
2001
2002                                 if !msg_events.is_empty() {
2003                                         let per_peer_state = $self.per_peer_state.read().unwrap();
2004                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
2005                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2006                                                 peer_state.pending_msg_events.append(&mut msg_events);
2007                                         }
2008                                 }
2009
2010                                 // Return error in case higher-API need one
2011                                 Err(err)
2012                         },
2013                 }
2014         } };
2015 }
2016
2017 macro_rules! update_maps_on_chan_removal {
2018         ($self: expr, $channel_context: expr) => {{
2019                 if let Some(outpoint) = $channel_context.get_funding_txo() {
2020                         $self.outpoint_to_peer.lock().unwrap().remove(&outpoint);
2021                 }
2022                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2023                 if let Some(short_id) = $channel_context.get_short_channel_id() {
2024                         short_to_chan_info.remove(&short_id);
2025                 } else {
2026                         // If the channel was never confirmed on-chain prior to its closure, remove the
2027                         // outbound SCID alias we used for it from the collision-prevention set. While we
2028                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
2029                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
2030                         // opening a million channels with us which are closed before we ever reach the funding
2031                         // stage.
2032                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
2033                         debug_assert!(alias_removed);
2034                 }
2035                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
2036         }}
2037 }
2038
2039 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
2040 macro_rules! convert_chan_phase_err {
2041         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
2042                 match $err {
2043                         ChannelError::Warn(msg) => {
2044                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
2045                         },
2046                         ChannelError::Ignore(msg) => {
2047                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
2048                         },
2049                         ChannelError::Close(msg) => {
2050                                 let logger = WithChannelContext::from(&$self.logger, &$channel.context);
2051                                 log_error!(logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
2052                                 update_maps_on_chan_removal!($self, $channel.context);
2053                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
2054                                 let shutdown_res = $channel.context.force_shutdown(true, reason);
2055                                 let err =
2056                                         MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $channel_update);
2057                                 (true, err)
2058                         },
2059                 }
2060         };
2061         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
2062                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
2063         };
2064         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
2065                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
2066         };
2067         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
2068                 match $channel_phase {
2069                         ChannelPhase::Funded(channel) => {
2070                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
2071                         },
2072                         ChannelPhase::UnfundedOutboundV1(channel) => {
2073                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2074                         },
2075                         ChannelPhase::UnfundedInboundV1(channel) => {
2076                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2077                         },
2078                 }
2079         };
2080 }
2081
2082 macro_rules! break_chan_phase_entry {
2083         ($self: ident, $res: expr, $entry: expr) => {
2084                 match $res {
2085                         Ok(res) => res,
2086                         Err(e) => {
2087                                 let key = *$entry.key();
2088                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2089                                 if drop {
2090                                         $entry.remove_entry();
2091                                 }
2092                                 break Err(res);
2093                         }
2094                 }
2095         }
2096 }
2097
2098 macro_rules! try_chan_phase_entry {
2099         ($self: ident, $res: expr, $entry: expr) => {
2100                 match $res {
2101                         Ok(res) => res,
2102                         Err(e) => {
2103                                 let key = *$entry.key();
2104                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2105                                 if drop {
2106                                         $entry.remove_entry();
2107                                 }
2108                                 return Err(res);
2109                         }
2110                 }
2111         }
2112 }
2113
2114 macro_rules! remove_channel_phase {
2115         ($self: expr, $entry: expr) => {
2116                 {
2117                         let channel = $entry.remove_entry().1;
2118                         update_maps_on_chan_removal!($self, &channel.context());
2119                         channel
2120                 }
2121         }
2122 }
2123
2124 macro_rules! send_channel_ready {
2125         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2126                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2127                         node_id: $channel.context.get_counterparty_node_id(),
2128                         msg: $channel_ready_msg,
2129                 });
2130                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2131                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2132                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2133                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2134                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2135                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2136                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2137                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2138                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2139                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2140                 }
2141         }}
2142 }
2143
2144 macro_rules! emit_channel_pending_event {
2145         ($locked_events: expr, $channel: expr) => {
2146                 if $channel.context.should_emit_channel_pending_event() {
2147                         $locked_events.push_back((events::Event::ChannelPending {
2148                                 channel_id: $channel.context.channel_id(),
2149                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2150                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2151                                 user_channel_id: $channel.context.get_user_id(),
2152                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2153                         }, None));
2154                         $channel.context.set_channel_pending_event_emitted();
2155                 }
2156         }
2157 }
2158
2159 macro_rules! emit_channel_ready_event {
2160         ($locked_events: expr, $channel: expr) => {
2161                 if $channel.context.should_emit_channel_ready_event() {
2162                         debug_assert!($channel.context.channel_pending_event_emitted());
2163                         $locked_events.push_back((events::Event::ChannelReady {
2164                                 channel_id: $channel.context.channel_id(),
2165                                 user_channel_id: $channel.context.get_user_id(),
2166                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2167                                 channel_type: $channel.context.get_channel_type().clone(),
2168                         }, None));
2169                         $channel.context.set_channel_ready_event_emitted();
2170                 }
2171         }
2172 }
2173
2174 macro_rules! handle_monitor_update_completion {
2175         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2176                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2177                 let mut updates = $chan.monitor_updating_restored(&&logger,
2178                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2179                         $self.best_block.read().unwrap().height());
2180                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2181                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2182                         // We only send a channel_update in the case where we are just now sending a
2183                         // channel_ready and the channel is in a usable state. We may re-send a
2184                         // channel_update later through the announcement_signatures process for public
2185                         // channels, but there's no reason not to just inform our counterparty of our fees
2186                         // now.
2187                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2188                                 Some(events::MessageSendEvent::SendChannelUpdate {
2189                                         node_id: counterparty_node_id,
2190                                         msg,
2191                                 })
2192                         } else { None }
2193                 } else { None };
2194
2195                 let update_actions = $peer_state.monitor_update_blocked_actions
2196                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2197
2198                 let htlc_forwards = $self.handle_channel_resumption(
2199                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2200                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2201                         updates.funding_broadcastable, updates.channel_ready,
2202                         updates.announcement_sigs);
2203                 if let Some(upd) = channel_update {
2204                         $peer_state.pending_msg_events.push(upd);
2205                 }
2206
2207                 let channel_id = $chan.context.channel_id();
2208                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2209                 core::mem::drop($peer_state_lock);
2210                 core::mem::drop($per_peer_state_lock);
2211
2212                 // If the channel belongs to a batch funding transaction, the progress of the batch
2213                 // should be updated as we have received funding_signed and persisted the monitor.
2214                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2215                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2216                         let mut batch_completed = false;
2217                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2218                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2219                                         *chan_id == channel_id &&
2220                                         *pubkey == counterparty_node_id
2221                                 ));
2222                                 if let Some(channel_state) = channel_state {
2223                                         channel_state.2 = true;
2224                                 } else {
2225                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2226                                 }
2227                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2228                         } else {
2229                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2230                         }
2231
2232                         // When all channels in a batched funding transaction have become ready, it is not necessary
2233                         // to track the progress of the batch anymore and the state of the channels can be updated.
2234                         if batch_completed {
2235                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2236                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2237                                 let mut batch_funding_tx = None;
2238                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2239                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2240                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2241                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2242                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2243                                                         chan.set_batch_ready();
2244                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2245                                                         emit_channel_pending_event!(pending_events, chan);
2246                                                 }
2247                                         }
2248                                 }
2249                                 if let Some(tx) = batch_funding_tx {
2250                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2251                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2252                                 }
2253                         }
2254                 }
2255
2256                 $self.handle_monitor_update_completion_actions(update_actions);
2257
2258                 if let Some(forwards) = htlc_forwards {
2259                         $self.forward_htlcs(&mut [forwards][..]);
2260                 }
2261                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2262                 for failure in updates.failed_htlcs.drain(..) {
2263                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2264                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2265                 }
2266         } }
2267 }
2268
2269 macro_rules! handle_new_monitor_update {
2270         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2271                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2272                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2273                 match $update_res {
2274                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2275                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2276                                 log_error!(logger, "{}", err_str);
2277                                 panic!("{}", err_str);
2278                         },
2279                         ChannelMonitorUpdateStatus::InProgress => {
2280                                 log_debug!(logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2281                                         &$chan.context.channel_id());
2282                                 false
2283                         },
2284                         ChannelMonitorUpdateStatus::Completed => {
2285                                 $completed;
2286                                 true
2287                         },
2288                 }
2289         } };
2290         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2291                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2292                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2293         };
2294         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2295                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2296                         .or_insert_with(Vec::new);
2297                 // During startup, we push monitor updates as background events through to here in
2298                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2299                 // filter for uniqueness here.
2300                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2301                         .unwrap_or_else(|| {
2302                                 in_flight_updates.push($update);
2303                                 in_flight_updates.len() - 1
2304                         });
2305                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2306                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2307                         {
2308                                 let _ = in_flight_updates.remove(idx);
2309                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2310                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2311                                 }
2312                         })
2313         } };
2314 }
2315
2316 macro_rules! process_events_body {
2317         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2318                 let mut processed_all_events = false;
2319                 while !processed_all_events {
2320                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2321                                 return;
2322                         }
2323
2324                         let mut result;
2325
2326                         {
2327                                 // We'll acquire our total consistency lock so that we can be sure no other
2328                                 // persists happen while processing monitor events.
2329                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2330
2331                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2332                                 // ensure any startup-generated background events are handled first.
2333                                 result = $self.process_background_events();
2334
2335                                 // TODO: This behavior should be documented. It's unintuitive that we query
2336                                 // ChannelMonitors when clearing other events.
2337                                 if $self.process_pending_monitor_events() {
2338                                         result = NotifyOption::DoPersist;
2339                                 }
2340                         }
2341
2342                         let pending_events = $self.pending_events.lock().unwrap().clone();
2343                         let num_events = pending_events.len();
2344                         if !pending_events.is_empty() {
2345                                 result = NotifyOption::DoPersist;
2346                         }
2347
2348                         let mut post_event_actions = Vec::new();
2349
2350                         for (event, action_opt) in pending_events {
2351                                 $event_to_handle = event;
2352                                 $handle_event;
2353                                 if let Some(action) = action_opt {
2354                                         post_event_actions.push(action);
2355                                 }
2356                         }
2357
2358                         {
2359                                 let mut pending_events = $self.pending_events.lock().unwrap();
2360                                 pending_events.drain(..num_events);
2361                                 processed_all_events = pending_events.is_empty();
2362                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2363                                 // updated here with the `pending_events` lock acquired.
2364                                 $self.pending_events_processor.store(false, Ordering::Release);
2365                         }
2366
2367                         if !post_event_actions.is_empty() {
2368                                 $self.handle_post_event_actions(post_event_actions);
2369                                 // If we had some actions, go around again as we may have more events now
2370                                 processed_all_events = false;
2371                         }
2372
2373                         match result {
2374                                 NotifyOption::DoPersist => {
2375                                         $self.needs_persist_flag.store(true, Ordering::Release);
2376                                         $self.event_persist_notifier.notify();
2377                                 },
2378                                 NotifyOption::SkipPersistHandleEvents =>
2379                                         $self.event_persist_notifier.notify(),
2380                                 NotifyOption::SkipPersistNoEvents => {},
2381                         }
2382                 }
2383         }
2384 }
2385
2386 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>
2387 where
2388         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
2389         T::Target: BroadcasterInterface,
2390         ES::Target: EntropySource,
2391         NS::Target: NodeSigner,
2392         SP::Target: SignerProvider,
2393         F::Target: FeeEstimator,
2394         R::Target: Router,
2395         L::Target: Logger,
2396 {
2397         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2398         ///
2399         /// The current time or latest block header time can be provided as the `current_timestamp`.
2400         ///
2401         /// This is the main "logic hub" for all channel-related actions, and implements
2402         /// [`ChannelMessageHandler`].
2403         ///
2404         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2405         ///
2406         /// Users need to notify the new `ChannelManager` when a new block is connected or
2407         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2408         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2409         /// more details.
2410         ///
2411         /// [`block_connected`]: chain::Listen::block_connected
2412         /// [`block_disconnected`]: chain::Listen::block_disconnected
2413         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2414         pub fn new(
2415                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2416                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2417                 current_timestamp: u32,
2418         ) -> Self {
2419                 let mut secp_ctx = Secp256k1::new();
2420                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2421                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2422                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2423                 ChannelManager {
2424                         default_configuration: config.clone(),
2425                         chain_hash: ChainHash::using_genesis_block(params.network),
2426                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2427                         chain_monitor,
2428                         tx_broadcaster,
2429                         router,
2430
2431                         best_block: RwLock::new(params.best_block),
2432
2433                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2434                         pending_inbound_payments: Mutex::new(HashMap::new()),
2435                         pending_outbound_payments: OutboundPayments::new(),
2436                         forward_htlcs: Mutex::new(HashMap::new()),
2437                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2438                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2439                         outpoint_to_peer: Mutex::new(HashMap::new()),
2440                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2441
2442                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2443                         secp_ctx,
2444
2445                         inbound_payment_key: expanded_inbound_key,
2446                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2447
2448                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2449
2450                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2451
2452                         per_peer_state: FairRwLock::new(HashMap::new()),
2453
2454                         pending_events: Mutex::new(VecDeque::new()),
2455                         pending_events_processor: AtomicBool::new(false),
2456                         pending_background_events: Mutex::new(Vec::new()),
2457                         total_consistency_lock: RwLock::new(()),
2458                         background_events_processed_since_startup: AtomicBool::new(false),
2459                         event_persist_notifier: Notifier::new(),
2460                         needs_persist_flag: AtomicBool::new(false),
2461                         funding_batch_states: Mutex::new(BTreeMap::new()),
2462
2463                         pending_offers_messages: Mutex::new(Vec::new()),
2464
2465                         entropy_source,
2466                         node_signer,
2467                         signer_provider,
2468
2469                         logger,
2470                 }
2471         }
2472
2473         /// Gets the current configuration applied to all new channels.
2474         pub fn get_current_default_configuration(&self) -> &UserConfig {
2475                 &self.default_configuration
2476         }
2477
2478         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2479                 let height = self.best_block.read().unwrap().height();
2480                 let mut outbound_scid_alias = 0;
2481                 let mut i = 0;
2482                 loop {
2483                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2484                                 outbound_scid_alias += 1;
2485                         } else {
2486                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2487                         }
2488                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2489                                 break;
2490                         }
2491                         i += 1;
2492                         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"); }
2493                 }
2494                 outbound_scid_alias
2495         }
2496
2497         /// Creates a new outbound channel to the given remote node and with the given value.
2498         ///
2499         /// `user_channel_id` will be provided back as in
2500         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2501         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2502         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2503         /// is simply copied to events and otherwise ignored.
2504         ///
2505         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2506         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2507         ///
2508         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2509         /// generate a shutdown scriptpubkey or destination script set by
2510         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2511         ///
2512         /// Note that we do not check if you are currently connected to the given peer. If no
2513         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2514         /// the channel eventually being silently forgotten (dropped on reload).
2515         ///
2516         /// If `temporary_channel_id` is specified, it will be used as the temporary channel ID of the
2517         /// channel. Otherwise, a random one will be generated for you.
2518         ///
2519         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2520         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2521         /// [`ChannelDetails::channel_id`] until after
2522         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2523         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2524         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2525         ///
2526         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2527         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2528         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2529         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> {
2530                 if channel_value_satoshis < 1000 {
2531                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2532                 }
2533
2534                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2535                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2536                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2537
2538                 let per_peer_state = self.per_peer_state.read().unwrap();
2539
2540                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2541                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2542
2543                 let mut peer_state = peer_state_mutex.lock().unwrap();
2544
2545                 if let Some(temporary_channel_id) = temporary_channel_id {
2546                         if peer_state.channel_by_id.contains_key(&temporary_channel_id) {
2547                                 return Err(APIError::APIMisuseError{ err: format!("Channel with temporary channel ID {} already exists!", temporary_channel_id)});
2548                         }
2549                 }
2550
2551                 let channel = {
2552                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2553                         let their_features = &peer_state.latest_features;
2554                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2555                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2556                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2557                                 self.best_block.read().unwrap().height(), outbound_scid_alias, temporary_channel_id)
2558                         {
2559                                 Ok(res) => res,
2560                                 Err(e) => {
2561                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2562                                         return Err(e);
2563                                 },
2564                         }
2565                 };
2566                 let res = channel.get_open_channel(self.chain_hash);
2567
2568                 let temporary_channel_id = channel.context.channel_id();
2569                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2570                         hash_map::Entry::Occupied(_) => {
2571                                 if cfg!(fuzzing) {
2572                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2573                                 } else {
2574                                         panic!("RNG is bad???");
2575                                 }
2576                         },
2577                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2578                 }
2579
2580                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2581                         node_id: their_network_key,
2582                         msg: res,
2583                 });
2584                 Ok(temporary_channel_id)
2585         }
2586
2587         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2588                 // Allocate our best estimate of the number of channels we have in the `res`
2589                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2590                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2591                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2592                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2593                 // the same channel.
2594                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2595                 {
2596                         let best_block_height = self.best_block.read().unwrap().height();
2597                         let per_peer_state = self.per_peer_state.read().unwrap();
2598                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2599                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2600                                 let peer_state = &mut *peer_state_lock;
2601                                 res.extend(peer_state.channel_by_id.iter()
2602                                         .filter_map(|(chan_id, phase)| match phase {
2603                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2604                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2605                                                 _ => None,
2606                                         })
2607                                         .filter(f)
2608                                         .map(|(_channel_id, channel)| {
2609                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2610                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2611                                         })
2612                                 );
2613                         }
2614                 }
2615                 res
2616         }
2617
2618         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2619         /// more information.
2620         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2621                 // Allocate our best estimate of the number of channels we have in the `res`
2622                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2623                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2624                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2625                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2626                 // the same channel.
2627                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2628                 {
2629                         let best_block_height = self.best_block.read().unwrap().height();
2630                         let per_peer_state = self.per_peer_state.read().unwrap();
2631                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2632                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2633                                 let peer_state = &mut *peer_state_lock;
2634                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2635                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2636                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2637                                         res.push(details);
2638                                 }
2639                         }
2640                 }
2641                 res
2642         }
2643
2644         /// Gets the list of usable channels, in random order. Useful as an argument to
2645         /// [`Router::find_route`] to ensure non-announced channels are used.
2646         ///
2647         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2648         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2649         /// are.
2650         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2651                 // Note we use is_live here instead of usable which leads to somewhat confused
2652                 // internal/external nomenclature, but that's ok cause that's probably what the user
2653                 // really wanted anyway.
2654                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2655         }
2656
2657         /// Gets the list of channels we have with a given counterparty, in random order.
2658         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2659                 let best_block_height = self.best_block.read().unwrap().height();
2660                 let per_peer_state = self.per_peer_state.read().unwrap();
2661
2662                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2663                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2664                         let peer_state = &mut *peer_state_lock;
2665                         let features = &peer_state.latest_features;
2666                         let context_to_details = |context| {
2667                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2668                         };
2669                         return peer_state.channel_by_id
2670                                 .iter()
2671                                 .map(|(_, phase)| phase.context())
2672                                 .map(context_to_details)
2673                                 .collect();
2674                 }
2675                 vec![]
2676         }
2677
2678         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2679         /// successful path, or have unresolved HTLCs.
2680         ///
2681         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2682         /// result of a crash. If such a payment exists, is not listed here, and an
2683         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2684         ///
2685         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2686         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2687                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2688                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2689                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2690                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2691                                 },
2692                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2693                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2694                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2695                                 },
2696                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2697                                         Some(RecentPaymentDetails::Pending {
2698                                                 payment_id: *payment_id,
2699                                                 payment_hash: *payment_hash,
2700                                                 total_msat: *total_msat,
2701                                         })
2702                                 },
2703                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2704                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2705                                 },
2706                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2707                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2708                                 },
2709                                 PendingOutboundPayment::Legacy { .. } => None
2710                         })
2711                         .collect()
2712         }
2713
2714         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> {
2715                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2716
2717                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
2718                 let mut shutdown_result = None;
2719
2720                 {
2721                         let per_peer_state = self.per_peer_state.read().unwrap();
2722
2723                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2724                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2725
2726                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2727                         let peer_state = &mut *peer_state_lock;
2728
2729                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2730                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2731                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2732                                                 let funding_txo_opt = chan.context.get_funding_txo();
2733                                                 let their_features = &peer_state.latest_features;
2734                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2735                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2736                                                 failed_htlcs = htlcs;
2737
2738                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2739                                                 // here as we don't need the monitor update to complete until we send a
2740                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2741                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2742                                                         node_id: *counterparty_node_id,
2743                                                         msg: shutdown_msg,
2744                                                 });
2745
2746                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2747                                                         "We can't both complete shutdown and generate a monitor update");
2748
2749                                                 // Update the monitor with the shutdown script if necessary.
2750                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2751                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2752                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2753                                                 }
2754                                         } else {
2755                                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2756                                                 shutdown_result = Some(chan_phase.context_mut().force_shutdown(false, ClosureReason::HolderForceClosed));
2757                                         }
2758                                 },
2759                                 hash_map::Entry::Vacant(_) => {
2760                                         return Err(APIError::ChannelUnavailable {
2761                                                 err: format!(
2762                                                         "Channel with id {} not found for the passed counterparty node_id {}",
2763                                                         channel_id, counterparty_node_id,
2764                                                 )
2765                                         });
2766                                 },
2767                         }
2768                 }
2769
2770                 for htlc_source in failed_htlcs.drain(..) {
2771                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2772                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2773                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2774                 }
2775
2776                 if let Some(shutdown_result) = shutdown_result {
2777                         self.finish_close_channel(shutdown_result);
2778                 }
2779
2780                 Ok(())
2781         }
2782
2783         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2784         /// will be accepted on the given channel, and after additional timeout/the closing of all
2785         /// pending HTLCs, the channel will be closed on chain.
2786         ///
2787         ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2788         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2789         ///    fee estimate.
2790         ///  * If our counterparty is the channel initiator, we will require a channel closing
2791         ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2792         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2793         ///    counterparty to pay as much fee as they'd like, however.
2794         ///
2795         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2796         ///
2797         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2798         /// generate a shutdown scriptpubkey or destination script set by
2799         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2800         /// channel.
2801         ///
2802         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2803         /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2804         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2805         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2806         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2807                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2808         }
2809
2810         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2811         /// will be accepted on the given channel, and after additional timeout/the closing of all
2812         /// pending HTLCs, the channel will be closed on chain.
2813         ///
2814         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2815         /// the channel being closed or not:
2816         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2817         ///    transaction. The upper-bound is set by
2818         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2819         ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2820         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2821         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2822         ///    will appear on a force-closure transaction, whichever is lower).
2823         ///
2824         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2825         /// Will fail if a shutdown script has already been set for this channel by
2826         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2827         /// also be compatible with our and the counterparty's features.
2828         ///
2829         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2830         ///
2831         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2832         /// generate a shutdown scriptpubkey or destination script set by
2833         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2834         /// channel.
2835         ///
2836         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2837         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2838         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2839         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> {
2840                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2841         }
2842
2843         fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) {
2844                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2845                 #[cfg(debug_assertions)]
2846                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2847                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2848                 }
2849
2850                 let logger = WithContext::from(
2851                         &self.logger, Some(shutdown_res.counterparty_node_id), Some(shutdown_res.channel_id),
2852                 );
2853
2854                 log_debug!(logger, "Finishing closure of channel due to {} with {} HTLCs to fail",
2855                         shutdown_res.closure_reason, shutdown_res.dropped_outbound_htlcs.len());
2856                 for htlc_source in shutdown_res.dropped_outbound_htlcs.drain(..) {
2857                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2858                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2859                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2860                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2861                 }
2862                 if let Some((_, funding_txo, monitor_update)) = shutdown_res.monitor_update {
2863                         // There isn't anything we can do if we get an update failure - we're already
2864                         // force-closing. The monitor update on the required in-memory copy should broadcast
2865                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2866                         // ignore the result here.
2867                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2868                 }
2869                 let mut shutdown_results = Vec::new();
2870                 if let Some(txid) = shutdown_res.unbroadcasted_batch_funding_txid {
2871                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2872                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2873                         let per_peer_state = self.per_peer_state.read().unwrap();
2874                         let mut has_uncompleted_channel = None;
2875                         for (channel_id, counterparty_node_id, state) in affected_channels {
2876                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2877                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2878                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2879                                                 update_maps_on_chan_removal!(self, &chan.context());
2880                                                 shutdown_results.push(chan.context_mut().force_shutdown(false, ClosureReason::FundingBatchClosure));
2881                                         }
2882                                 }
2883                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2884                         }
2885                         debug_assert!(
2886                                 has_uncompleted_channel.unwrap_or(true),
2887                                 "Closing a batch where all channels have completed initial monitor update",
2888                         );
2889                 }
2890
2891                 {
2892                         let mut pending_events = self.pending_events.lock().unwrap();
2893                         pending_events.push_back((events::Event::ChannelClosed {
2894                                 channel_id: shutdown_res.channel_id,
2895                                 user_channel_id: shutdown_res.user_channel_id,
2896                                 reason: shutdown_res.closure_reason,
2897                                 counterparty_node_id: Some(shutdown_res.counterparty_node_id),
2898                                 channel_capacity_sats: Some(shutdown_res.channel_capacity_satoshis),
2899                                 channel_funding_txo: shutdown_res.channel_funding_txo,
2900                         }, None));
2901
2902                         if let Some(transaction) = shutdown_res.unbroadcasted_funding_tx {
2903                                 pending_events.push_back((events::Event::DiscardFunding {
2904                                         channel_id: shutdown_res.channel_id, transaction
2905                                 }, None));
2906                         }
2907                 }
2908                 for shutdown_result in shutdown_results.drain(..) {
2909                         self.finish_close_channel(shutdown_result);
2910                 }
2911         }
2912
2913         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2914         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2915         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2916         -> Result<PublicKey, APIError> {
2917                 let per_peer_state = self.per_peer_state.read().unwrap();
2918                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2919                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2920                 let (update_opt, counterparty_node_id) = {
2921                         let mut peer_state = peer_state_mutex.lock().unwrap();
2922                         let closure_reason = if let Some(peer_msg) = peer_msg {
2923                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2924                         } else {
2925                                 ClosureReason::HolderForceClosed
2926                         };
2927                         let logger = WithContext::from(&self.logger, Some(*peer_node_id), Some(*channel_id));
2928                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2929                                 log_error!(logger, "Force-closing channel {}", channel_id);
2930                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2931                                 mem::drop(peer_state);
2932                                 mem::drop(per_peer_state);
2933                                 match chan_phase {
2934                                         ChannelPhase::Funded(mut chan) => {
2935                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast, closure_reason));
2936                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2937                                         },
2938                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2939                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false, closure_reason));
2940                                                 // Unfunded channel has no update
2941                                                 (None, chan_phase.context().get_counterparty_node_id())
2942                                         },
2943                                 }
2944                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2945                                 log_error!(logger, "Force-closing channel {}", &channel_id);
2946                                 // N.B. that we don't send any channel close event here: we
2947                                 // don't have a user_channel_id, and we never sent any opening
2948                                 // events anyway.
2949                                 (None, *peer_node_id)
2950                         } else {
2951                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2952                         }
2953                 };
2954                 if let Some(update) = update_opt {
2955                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2956                         // not try to broadcast it via whatever peer we have.
2957                         let per_peer_state = self.per_peer_state.read().unwrap();
2958                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2959                                 .ok_or(per_peer_state.values().next());
2960                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2961                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2962                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2963                                         msg: update
2964                                 });
2965                         }
2966                 }
2967
2968                 Ok(counterparty_node_id)
2969         }
2970
2971         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2972                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2973                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2974                         Ok(counterparty_node_id) => {
2975                                 let per_peer_state = self.per_peer_state.read().unwrap();
2976                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2977                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2978                                         peer_state.pending_msg_events.push(
2979                                                 events::MessageSendEvent::HandleError {
2980                                                         node_id: counterparty_node_id,
2981                                                         action: msgs::ErrorAction::DisconnectPeer {
2982                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2983                                                         },
2984                                                 }
2985                                         );
2986                                 }
2987                                 Ok(())
2988                         },
2989                         Err(e) => Err(e)
2990                 }
2991         }
2992
2993         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2994         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2995         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2996         /// channel.
2997         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2998         -> Result<(), APIError> {
2999                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
3000         }
3001
3002         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
3003         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
3004         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
3005         ///
3006         /// You can always get the latest local transaction(s) to broadcast from
3007         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
3008         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
3009         -> Result<(), APIError> {
3010                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
3011         }
3012
3013         /// Force close all channels, immediately broadcasting the latest local commitment transaction
3014         /// for each to the chain and rejecting new HTLCs on each.
3015         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
3016                 for chan in self.list_channels() {
3017                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
3018                 }
3019         }
3020
3021         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
3022         /// local transaction(s).
3023         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
3024                 for chan in self.list_channels() {
3025                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
3026                 }
3027         }
3028
3029         fn decode_update_add_htlc_onion(
3030                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey,
3031         ) -> Result<
3032                 (onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg
3033         > {
3034                 let (next_hop, shared_secret, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(
3035                         msg, &self.node_signer, &self.logger, &self.secp_ctx
3036                 )?;
3037
3038                 let is_intro_node_forward = match next_hop {
3039                         onion_utils::Hop::Forward {
3040                                 next_hop_data: msgs::InboundOnionPayload::BlindedForward {
3041                                         intro_node_blinding_point: Some(_), ..
3042                                 }, ..
3043                         } => true,
3044                         _ => false,
3045                 };
3046
3047                 macro_rules! return_err {
3048                         ($msg: expr, $err_code: expr, $data: expr) => {
3049                                 {
3050                                         log_info!(
3051                                                 WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id)),
3052                                                 "Failed to accept/forward incoming HTLC: {}", $msg
3053                                         );
3054                                         // If `msg.blinding_point` is set, we must always fail with malformed.
3055                                         if msg.blinding_point.is_some() {
3056                                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3057                                                         channel_id: msg.channel_id,
3058                                                         htlc_id: msg.htlc_id,
3059                                                         sha256_of_onion: [0; 32],
3060                                                         failure_code: INVALID_ONION_BLINDING,
3061                                                 }));
3062                                         }
3063
3064                                         let (err_code, err_data) = if is_intro_node_forward {
3065                                                 (INVALID_ONION_BLINDING, &[0; 32][..])
3066                                         } else { ($err_code, $data) };
3067                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3068                                                 channel_id: msg.channel_id,
3069                                                 htlc_id: msg.htlc_id,
3070                                                 reason: HTLCFailReason::reason(err_code, err_data.to_vec())
3071                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3072                                         }));
3073                                 }
3074                         }
3075                 }
3076
3077                 let NextPacketDetails {
3078                         next_packet_pubkey, outgoing_amt_msat, outgoing_scid, outgoing_cltv_value
3079                 } = match next_packet_details_opt {
3080                         Some(next_packet_details) => next_packet_details,
3081                         // it is a receive, so no need for outbound checks
3082                         None => return Ok((next_hop, shared_secret, None)),
3083                 };
3084
3085                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3086                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3087                 if let Some((err, mut code, chan_update)) = loop {
3088                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3089                         let forwarding_chan_info_opt = match id_option {
3090                                 None => { // unknown_next_peer
3091                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3092                                         // phantom or an intercept.
3093                                         if (self.default_configuration.accept_intercept_htlcs &&
3094                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3095                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3096                                         {
3097                                                 None
3098                                         } else {
3099                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3100                                         }
3101                                 },
3102                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3103                         };
3104                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3105                                 let per_peer_state = self.per_peer_state.read().unwrap();
3106                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3107                                 if peer_state_mutex_opt.is_none() {
3108                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3109                                 }
3110                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3111                                 let peer_state = &mut *peer_state_lock;
3112                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3113                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3114                                 ).flatten() {
3115                                         None => {
3116                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3117                                                 // have no consistency guarantees.
3118                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3119                                         },
3120                                         Some(chan) => chan
3121                                 };
3122                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3123                                         // Note that the behavior here should be identical to the above block - we
3124                                         // should NOT reveal the existence or non-existence of a private channel if
3125                                         // we don't allow forwards outbound over them.
3126                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3127                                 }
3128                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3129                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3130                                         // "refuse to forward unless the SCID alias was used", so we pretend
3131                                         // we don't have the channel here.
3132                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3133                                 }
3134                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3135
3136                                 // Note that we could technically not return an error yet here and just hope
3137                                 // that the connection is reestablished or monitor updated by the time we get
3138                                 // around to doing the actual forward, but better to fail early if we can and
3139                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3140                                 // on a small/per-node/per-channel scale.
3141                                 if !chan.context.is_live() { // channel_disabled
3142                                         // If the channel_update we're going to return is disabled (i.e. the
3143                                         // peer has been disabled for some time), return `channel_disabled`,
3144                                         // otherwise return `temporary_channel_failure`.
3145                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3146                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3147                                         } else {
3148                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3149                                         }
3150                                 }
3151                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3152                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3153                                 }
3154                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3155                                         break Some((err, code, chan_update_opt));
3156                                 }
3157                                 chan_update_opt
3158                         } else {
3159                                 None
3160                         };
3161
3162                         let cur_height = self.best_block.read().unwrap().height() + 1;
3163
3164                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
3165                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
3166                         ) {
3167                                 if code & 0x1000 != 0 && chan_update_opt.is_none() {
3168                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3169                                         // forwarding over a real channel we can't generate a channel_update
3170                                         // for it. Instead we just return a generic temporary_node_failure.
3171                                         break Some((err_msg, 0x2000 | 2, None))
3172                                 }
3173                                 let chan_update_opt = if code & 0x1000 != 0 { chan_update_opt } else { None };
3174                                 break Some((err_msg, code, chan_update_opt));
3175                         }
3176
3177                         break None;
3178                 }
3179                 {
3180                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3181                         if let Some(chan_update) = chan_update {
3182                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3183                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3184                                 }
3185                                 else if code == 0x1000 | 13 {
3186                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3187                                 }
3188                                 else if code == 0x1000 | 20 {
3189                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3190                                         0u16.write(&mut res).expect("Writes cannot fail");
3191                                 }
3192                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3193                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3194                                 chan_update.write(&mut res).expect("Writes cannot fail");
3195                         } else if code & 0x1000 == 0x1000 {
3196                                 // If we're trying to return an error that requires a `channel_update` but
3197                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3198                                 // generate an update), just use the generic "temporary_node_failure"
3199                                 // instead.
3200                                 code = 0x2000 | 2;
3201                         }
3202                         return_err!(err, code, &res.0[..]);
3203                 }
3204                 Ok((next_hop, shared_secret, Some(next_packet_pubkey)))
3205         }
3206
3207         fn construct_pending_htlc_status<'a>(
3208                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, shared_secret: [u8; 32],
3209                 decoded_hop: onion_utils::Hop, allow_underpay: bool,
3210                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>,
3211         ) -> PendingHTLCStatus {
3212                 macro_rules! return_err {
3213                         ($msg: expr, $err_code: expr, $data: expr) => {
3214                                 {
3215                                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
3216                                         log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3217                                         if msg.blinding_point.is_some() {
3218                                                 return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
3219                                                         msgs::UpdateFailMalformedHTLC {
3220                                                                 channel_id: msg.channel_id,
3221                                                                 htlc_id: msg.htlc_id,
3222                                                                 sha256_of_onion: [0; 32],
3223                                                                 failure_code: INVALID_ONION_BLINDING,
3224                                                         }
3225                                                 ))
3226                                         }
3227                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3228                                                 channel_id: msg.channel_id,
3229                                                 htlc_id: msg.htlc_id,
3230                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3231                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3232                                         }));
3233                                 }
3234                         }
3235                 }
3236                 match decoded_hop {
3237                         onion_utils::Hop::Receive(next_hop_data) => {
3238                                 // OUR PAYMENT!
3239                                 let current_height: u32 = self.best_block.read().unwrap().height();
3240                                 match create_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3241                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat,
3242                                         current_height, self.default_configuration.accept_mpp_keysend)
3243                                 {
3244                                         Ok(info) => {
3245                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3246                                                 // message, however that would leak that we are the recipient of this payment, so
3247                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3248                                                 // delay) once they've send us a commitment_signed!
3249                                                 PendingHTLCStatus::Forward(info)
3250                                         },
3251                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3252                                 }
3253                         },
3254                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3255                                 match create_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3256                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3257                                         Ok(info) => PendingHTLCStatus::Forward(info),
3258                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3259                                 }
3260                         }
3261                 }
3262         }
3263
3264         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3265         /// public, and thus should be called whenever the result is going to be passed out in a
3266         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3267         ///
3268         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3269         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3270         /// storage and the `peer_state` lock has been dropped.
3271         ///
3272         /// [`channel_update`]: msgs::ChannelUpdate
3273         /// [`internal_closing_signed`]: Self::internal_closing_signed
3274         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3275                 if !chan.context.should_announce() {
3276                         return Err(LightningError {
3277                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3278                                 action: msgs::ErrorAction::IgnoreError
3279                         });
3280                 }
3281                 if chan.context.get_short_channel_id().is_none() {
3282                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3283                 }
3284                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3285                 log_trace!(logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3286                 self.get_channel_update_for_unicast(chan)
3287         }
3288
3289         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3290         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3291         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3292         /// provided evidence that they know about the existence of the channel.
3293         ///
3294         /// Note that through [`internal_closing_signed`], this function is called without the
3295         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3296         /// removed from the storage and the `peer_state` lock has been dropped.
3297         ///
3298         /// [`channel_update`]: msgs::ChannelUpdate
3299         /// [`internal_closing_signed`]: Self::internal_closing_signed
3300         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3301                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3302                 log_trace!(logger, "Attempting to generate channel update for channel {}", chan.context.channel_id());
3303                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3304                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3305                         Some(id) => id,
3306                 };
3307
3308                 self.get_channel_update_for_onion(short_channel_id, chan)
3309         }
3310
3311         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3312                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3313                 log_trace!(logger, "Generating channel update for channel {}", chan.context.channel_id());
3314                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3315
3316                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3317                         ChannelUpdateStatus::Enabled => true,
3318                         ChannelUpdateStatus::DisabledStaged(_) => true,
3319                         ChannelUpdateStatus::Disabled => false,
3320                         ChannelUpdateStatus::EnabledStaged(_) => false,
3321                 };
3322
3323                 let unsigned = msgs::UnsignedChannelUpdate {
3324                         chain_hash: self.chain_hash,
3325                         short_channel_id,
3326                         timestamp: chan.context.get_update_time_counter(),
3327                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3328                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3329                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3330                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3331                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3332                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3333                         excess_data: Vec::new(),
3334                 };
3335                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3336                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3337                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3338                 // channel.
3339                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3340
3341                 Ok(msgs::ChannelUpdate {
3342                         signature: sig,
3343                         contents: unsigned
3344                 })
3345         }
3346
3347         #[cfg(test)]
3348         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> {
3349                 let _lck = self.total_consistency_lock.read().unwrap();
3350                 self.send_payment_along_path(SendAlongPathArgs {
3351                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3352                         session_priv_bytes
3353                 })
3354         }
3355
3356         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3357                 let SendAlongPathArgs {
3358                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3359                         session_priv_bytes
3360                 } = args;
3361                 // The top-level caller should hold the total_consistency_lock read lock.
3362                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3363                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3364                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3365
3366                 let (onion_packet, htlc_msat, htlc_cltv) = onion_utils::create_payment_onion(
3367                         &self.secp_ctx, &path, &session_priv, total_value, recipient_onion, cur_height,
3368                         payment_hash, keysend_preimage, prng_seed
3369                 ).map_err(|e| {
3370                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3371                         log_error!(logger, "Failed to build an onion for path for payment hash {}", payment_hash);
3372                         e
3373                 })?;
3374
3375                 let err: Result<(), _> = loop {
3376                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3377                                 None => {
3378                                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3379                                         log_error!(logger, "Failed to find first-hop for payment hash {}", payment_hash);
3380                                         return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()})
3381                                 },
3382                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3383                         };
3384
3385                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(id));
3386                         log_trace!(logger,
3387                                 "Attempting to send payment with payment hash {} along path with next hop {}",
3388                                 payment_hash, path.hops.first().unwrap().short_channel_id);
3389
3390                         let per_peer_state = self.per_peer_state.read().unwrap();
3391                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3392                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3393                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3394                         let peer_state = &mut *peer_state_lock;
3395                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3396                                 match chan_phase_entry.get_mut() {
3397                                         ChannelPhase::Funded(chan) => {
3398                                                 if !chan.context.is_live() {
3399                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3400                                                 }
3401                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3402                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3403                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3404                                                         htlc_cltv, HTLCSource::OutboundRoute {
3405                                                                 path: path.clone(),
3406                                                                 session_priv: session_priv.clone(),
3407                                                                 first_hop_htlc_msat: htlc_msat,
3408                                                                 payment_id,
3409                                                         }, onion_packet, None, &self.fee_estimator, &&logger);
3410                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3411                                                         Some(monitor_update) => {
3412                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3413                                                                         false => {
3414                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3415                                                                                 // docs) that we will resend the commitment update once monitor
3416                                                                                 // updating completes. Therefore, we must return an error
3417                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3418                                                                                 // which we do in the send_payment check for
3419                                                                                 // MonitorUpdateInProgress, below.
3420                                                                                 return Err(APIError::MonitorUpdateInProgress);
3421                                                                         },
3422                                                                         true => {},
3423                                                                 }
3424                                                         },
3425                                                         None => {},
3426                                                 }
3427                                         },
3428                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3429                                 };
3430                         } else {
3431                                 // The channel was likely removed after we fetched the id from the
3432                                 // `short_to_chan_info` map, but before we successfully locked the
3433                                 // `channel_by_id` map.
3434                                 // This can occur as no consistency guarantees exists between the two maps.
3435                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3436                         }
3437                         return Ok(());
3438                 };
3439                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3440                         Ok(_) => unreachable!(),
3441                         Err(e) => {
3442                                 Err(APIError::ChannelUnavailable { err: e.err })
3443                         },
3444                 }
3445         }
3446
3447         /// Sends a payment along a given route.
3448         ///
3449         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3450         /// fields for more info.
3451         ///
3452         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3453         /// [`PeerManager::process_events`]).
3454         ///
3455         /// # Avoiding Duplicate Payments
3456         ///
3457         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3458         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3459         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3460         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3461         /// second payment with the same [`PaymentId`].
3462         ///
3463         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3464         /// tracking of payments, including state to indicate once a payment has completed. Because you
3465         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3466         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3467         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3468         ///
3469         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3470         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3471         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3472         /// [`ChannelManager::list_recent_payments`] for more information.
3473         ///
3474         /// # Possible Error States on [`PaymentSendFailure`]
3475         ///
3476         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3477         /// each entry matching the corresponding-index entry in the route paths, see
3478         /// [`PaymentSendFailure`] for more info.
3479         ///
3480         /// In general, a path may raise:
3481         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3482         ///    node public key) is specified.
3483         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3484         ///    closed, doesn't exist, or the peer is currently disconnected.
3485         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3486         ///    relevant updates.
3487         ///
3488         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3489         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3490         /// different route unless you intend to pay twice!
3491         ///
3492         /// [`RouteHop`]: crate::routing::router::RouteHop
3493         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3494         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3495         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3496         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3497         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3498         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3499                 let best_block_height = self.best_block.read().unwrap().height();
3500                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3501                 self.pending_outbound_payments
3502                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3503                                 &self.entropy_source, &self.node_signer, best_block_height,
3504                                 |args| self.send_payment_along_path(args))
3505         }
3506
3507         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3508         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3509         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3510                 let best_block_height = self.best_block.read().unwrap().height();
3511                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3512                 self.pending_outbound_payments
3513                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3514                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3515                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3516                                 &self.pending_events, |args| self.send_payment_along_path(args))
3517         }
3518
3519         #[cfg(test)]
3520         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> {
3521                 let best_block_height = self.best_block.read().unwrap().height();
3522                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3523                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3524                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3525                         best_block_height, |args| self.send_payment_along_path(args))
3526         }
3527
3528         #[cfg(test)]
3529         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> {
3530                 let best_block_height = self.best_block.read().unwrap().height();
3531                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3532         }
3533
3534         #[cfg(test)]
3535         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3536                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3537         }
3538
3539         pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3540                 let best_block_height = self.best_block.read().unwrap().height();
3541                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3542                 self.pending_outbound_payments
3543                         .send_payment_for_bolt12_invoice(
3544                                 invoice, payment_id, &self.router, self.list_usable_channels(),
3545                                 || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3546                                 best_block_height, &self.logger, &self.pending_events,
3547                                 |args| self.send_payment_along_path(args)
3548                         )
3549         }
3550
3551         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3552         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3553         /// retries are exhausted.
3554         ///
3555         /// # Event Generation
3556         ///
3557         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3558         /// as there are no remaining pending HTLCs for this payment.
3559         ///
3560         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3561         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3562         /// determine the ultimate status of a payment.
3563         ///
3564         /// # Requested Invoices
3565         ///
3566         /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
3567         /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
3568         /// and prevent any attempts at paying it once received. The other events may only be generated
3569         /// once the invoice has been received.
3570         ///
3571         /// # Restart Behavior
3572         ///
3573         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3574         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
3575         /// [`Event::InvoiceRequestFailed`].
3576         ///
3577         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3578         pub fn abandon_payment(&self, payment_id: PaymentId) {
3579                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3580                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3581         }
3582
3583         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3584         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3585         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3586         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3587         /// never reach the recipient.
3588         ///
3589         /// See [`send_payment`] documentation for more details on the return value of this function
3590         /// and idempotency guarantees provided by the [`PaymentId`] key.
3591         ///
3592         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3593         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3594         ///
3595         /// [`send_payment`]: Self::send_payment
3596         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3597                 let best_block_height = self.best_block.read().unwrap().height();
3598                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3599                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3600                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3601                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3602         }
3603
3604         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3605         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3606         ///
3607         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3608         /// payments.
3609         ///
3610         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3611         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> {
3612                 let best_block_height = self.best_block.read().unwrap().height();
3613                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3614                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3615                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3616                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3617                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3618         }
3619
3620         /// Send a payment that is probing the given route for liquidity. We calculate the
3621         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3622         /// us to easily discern them from real payments.
3623         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3624                 let best_block_height = self.best_block.read().unwrap().height();
3625                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3626                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3627                         &self.entropy_source, &self.node_signer, best_block_height,
3628                         |args| self.send_payment_along_path(args))
3629         }
3630
3631         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3632         /// payment probe.
3633         #[cfg(test)]
3634         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3635                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3636         }
3637
3638         /// Sends payment probes over all paths of a route that would be used to pay the given
3639         /// amount to the given `node_id`.
3640         ///
3641         /// See [`ChannelManager::send_preflight_probes`] for more information.
3642         pub fn send_spontaneous_preflight_probes(
3643                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3644                 liquidity_limit_multiplier: Option<u64>,
3645         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3646                 let payment_params =
3647                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3648
3649                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3650
3651                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3652         }
3653
3654         /// Sends payment probes over all paths of a route that would be used to pay a route found
3655         /// according to the given [`RouteParameters`].
3656         ///
3657         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3658         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3659         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3660         /// confirmation in a wallet UI.
3661         ///
3662         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3663         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3664         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3665         /// payment. To mitigate this issue, channels with available liquidity less than the required
3666         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3667         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3668         pub fn send_preflight_probes(
3669                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3670         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3671                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3672
3673                 let payer = self.get_our_node_id();
3674                 let usable_channels = self.list_usable_channels();
3675                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3676                 let inflight_htlcs = self.compute_inflight_htlcs();
3677
3678                 let route = self
3679                         .router
3680                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3681                         .map_err(|e| {
3682                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3683                                 ProbeSendFailure::RouteNotFound
3684                         })?;
3685
3686                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3687
3688                 let mut res = Vec::new();
3689
3690                 for mut path in route.paths {
3691                         // If the last hop is probably an unannounced channel we refrain from probing all the
3692                         // way through to the end and instead probe up to the second-to-last channel.
3693                         while let Some(last_path_hop) = path.hops.last() {
3694                                 if last_path_hop.maybe_announced_channel {
3695                                         // We found a potentially announced last hop.
3696                                         break;
3697                                 } else {
3698                                         // Drop the last hop, as it's likely unannounced.
3699                                         log_debug!(
3700                                                 self.logger,
3701                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3702                                                 last_path_hop.short_channel_id
3703                                         );
3704                                         let final_value_msat = path.final_value_msat();
3705                                         path.hops.pop();
3706                                         if let Some(new_last) = path.hops.last_mut() {
3707                                                 new_last.fee_msat += final_value_msat;
3708                                         }
3709                                 }
3710                         }
3711
3712                         if path.hops.len() < 2 {
3713                                 log_debug!(
3714                                         self.logger,
3715                                         "Skipped sending payment probe over path with less than two hops."
3716                                 );
3717                                 continue;
3718                         }
3719
3720                         if let Some(first_path_hop) = path.hops.first() {
3721                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3722                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3723                                 }) {
3724                                         let path_value = path.final_value_msat() + path.fee_msat();
3725                                         let used_liquidity =
3726                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3727
3728                                         if first_hop.next_outbound_htlc_limit_msat
3729                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3730                                         {
3731                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3732                                                 continue;
3733                                         } else {
3734                                                 *used_liquidity += path_value;
3735                                         }
3736                                 }
3737                         }
3738
3739                         res.push(self.send_probe(path).map_err(|e| {
3740                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3741                                 ProbeSendFailure::SendingFailed(e)
3742                         })?);
3743                 }
3744
3745                 Ok(res)
3746         }
3747
3748         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3749         /// which checks the correctness of the funding transaction given the associated channel.
3750         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3751                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3752                 mut find_funding_output: FundingOutput,
3753         ) -> Result<(), APIError> {
3754                 let per_peer_state = self.per_peer_state.read().unwrap();
3755                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3756                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3757
3758                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3759                 let peer_state = &mut *peer_state_lock;
3760                 let funding_txo;
3761                 let (mut chan, msg_opt) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3762                         Some(ChannelPhase::UnfundedOutboundV1(mut chan)) => {
3763                                 funding_txo = find_funding_output(&chan, &funding_transaction)?;
3764
3765                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3766                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &&logger)
3767                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3768                                                 let channel_id = chan.context.channel_id();
3769                                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
3770                                                 let shutdown_res = chan.context.force_shutdown(false, reason);
3771                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, None))
3772                                         } else { unreachable!(); });
3773                                 match funding_res {
3774                                         Ok(funding_msg) => (chan, funding_msg),
3775                                         Err((chan, err)) => {
3776                                                 mem::drop(peer_state_lock);
3777                                                 mem::drop(per_peer_state);
3778                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3779                                                 return Err(APIError::ChannelUnavailable {
3780                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3781                                                 });
3782                                         },
3783                                 }
3784                         },
3785                         Some(phase) => {
3786                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3787                                 return Err(APIError::APIMisuseError {
3788                                         err: format!(
3789                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3790                                                 temporary_channel_id, counterparty_node_id),
3791                                 })
3792                         },
3793                         None => return Err(APIError::ChannelUnavailable {err: format!(
3794                                 "Channel with id {} not found for the passed counterparty node_id {}",
3795                                 temporary_channel_id, counterparty_node_id),
3796                                 }),
3797                 };
3798
3799                 if let Some(msg) = msg_opt {
3800                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3801                                 node_id: chan.context.get_counterparty_node_id(),
3802                                 msg,
3803                         });
3804                 }
3805                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3806                         hash_map::Entry::Occupied(_) => {
3807                                 panic!("Generated duplicate funding txid?");
3808                         },
3809                         hash_map::Entry::Vacant(e) => {
3810                                 let mut outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
3811                                 match outpoint_to_peer.entry(funding_txo) {
3812                                         hash_map::Entry::Vacant(e) => { e.insert(chan.context.get_counterparty_node_id()); },
3813                                         hash_map::Entry::Occupied(o) => {
3814                                                 let err = format!(
3815                                                         "An existing channel using outpoint {} is open with peer {}",
3816                                                         funding_txo, o.get()
3817                                                 );
3818                                                 mem::drop(outpoint_to_peer);
3819                                                 mem::drop(peer_state_lock);
3820                                                 mem::drop(per_peer_state);
3821                                                 let reason = ClosureReason::ProcessingError { err: err.clone() };
3822                                                 self.finish_close_channel(chan.context.force_shutdown(true, reason));
3823                                                 return Err(APIError::ChannelUnavailable { err });
3824                                         }
3825                                 }
3826                                 e.insert(ChannelPhase::UnfundedOutboundV1(chan));
3827                         }
3828                 }
3829                 Ok(())
3830         }
3831
3832         #[cfg(test)]
3833         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3834                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3835                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3836                 })
3837         }
3838
3839         /// Call this upon creation of a funding transaction for the given channel.
3840         ///
3841         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3842         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3843         ///
3844         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3845         /// across the p2p network.
3846         ///
3847         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3848         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3849         ///
3850         /// May panic if the output found in the funding transaction is duplicative with some other
3851         /// channel (note that this should be trivially prevented by using unique funding transaction
3852         /// keys per-channel).
3853         ///
3854         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3855         /// counterparty's signature the funding transaction will automatically be broadcast via the
3856         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3857         ///
3858         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3859         /// not currently support replacing a funding transaction on an existing channel. Instead,
3860         /// create a new channel with a conflicting funding transaction.
3861         ///
3862         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3863         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3864         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3865         /// for more details.
3866         ///
3867         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3868         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3869         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3870                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3871         }
3872
3873         /// Call this upon creation of a batch funding transaction for the given channels.
3874         ///
3875         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3876         /// each individual channel and transaction output.
3877         ///
3878         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3879         /// will only be broadcast when we have safely received and persisted the counterparty's
3880         /// signature for each channel.
3881         ///
3882         /// If there is an error, all channels in the batch are to be considered closed.
3883         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3884                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3885                 let mut result = Ok(());
3886
3887                 if !funding_transaction.is_coin_base() {
3888                         for inp in funding_transaction.input.iter() {
3889                                 if inp.witness.is_empty() {
3890                                         result = result.and(Err(APIError::APIMisuseError {
3891                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3892                                         }));
3893                                 }
3894                         }
3895                 }
3896                 if funding_transaction.output.len() > u16::max_value() as usize {
3897                         result = result.and(Err(APIError::APIMisuseError {
3898                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3899                         }));
3900                 }
3901                 {
3902                         let height = self.best_block.read().unwrap().height();
3903                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3904                         // lower than the next block height. However, the modules constituting our Lightning
3905                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3906                         // module is ahead of LDK, only allow one more block of headroom.
3907                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) &&
3908                                 funding_transaction.lock_time.is_block_height() &&
3909                                 funding_transaction.lock_time.to_consensus_u32() > height + 1
3910                         {
3911                                 result = result.and(Err(APIError::APIMisuseError {
3912                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3913                                 }));
3914                         }
3915                 }
3916
3917                 let txid = funding_transaction.txid();
3918                 let is_batch_funding = temporary_channels.len() > 1;
3919                 let mut funding_batch_states = if is_batch_funding {
3920                         Some(self.funding_batch_states.lock().unwrap())
3921                 } else {
3922                         None
3923                 };
3924                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3925                         match states.entry(txid) {
3926                                 btree_map::Entry::Occupied(_) => {
3927                                         result = result.clone().and(Err(APIError::APIMisuseError {
3928                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3929                                         }));
3930                                         None
3931                                 },
3932                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3933                         }
3934                 });
3935                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3936                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3937                                 temporary_channel_id,
3938                                 counterparty_node_id,
3939                                 funding_transaction.clone(),
3940                                 is_batch_funding,
3941                                 |chan, tx| {
3942                                         let mut output_index = None;
3943                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3944                                         for (idx, outp) in tx.output.iter().enumerate() {
3945                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3946                                                         if output_index.is_some() {
3947                                                                 return Err(APIError::APIMisuseError {
3948                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3949                                                                 });
3950                                                         }
3951                                                         output_index = Some(idx as u16);
3952                                                 }
3953                                         }
3954                                         if output_index.is_none() {
3955                                                 return Err(APIError::APIMisuseError {
3956                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3957                                                 });
3958                                         }
3959                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3960                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3961                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3962                                         }
3963                                         Ok(outpoint)
3964                                 })
3965                         );
3966                 }
3967                 if let Err(ref e) = result {
3968                         // Remaining channels need to be removed on any error.
3969                         let e = format!("Error in transaction funding: {:?}", e);
3970                         let mut channels_to_remove = Vec::new();
3971                         channels_to_remove.extend(funding_batch_states.as_mut()
3972                                 .and_then(|states| states.remove(&txid))
3973                                 .into_iter().flatten()
3974                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3975                         );
3976                         channels_to_remove.extend(temporary_channels.iter()
3977                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3978                         );
3979                         let mut shutdown_results = Vec::new();
3980                         {
3981                                 let per_peer_state = self.per_peer_state.read().unwrap();
3982                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3983                                         per_peer_state.get(&counterparty_node_id)
3984                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3985                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3986                                                 .map(|mut chan| {
3987                                                         update_maps_on_chan_removal!(self, &chan.context());
3988                                                         let closure_reason = ClosureReason::ProcessingError { err: e.clone() };
3989                                                         shutdown_results.push(chan.context_mut().force_shutdown(false, closure_reason));
3990                                                 });
3991                                 }
3992                         }
3993                         mem::drop(funding_batch_states);
3994                         for shutdown_result in shutdown_results.drain(..) {
3995                                 self.finish_close_channel(shutdown_result);
3996                         }
3997                 }
3998                 result
3999         }
4000
4001         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
4002         ///
4003         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4004         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4005         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4006         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4007         ///
4008         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4009         /// `counterparty_node_id` is provided.
4010         ///
4011         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4012         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4013         ///
4014         /// If an error is returned, none of the updates should be considered applied.
4015         ///
4016         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4017         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4018         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4019         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4020         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4021         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4022         /// [`APIMisuseError`]: APIError::APIMisuseError
4023         pub fn update_partial_channel_config(
4024                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
4025         ) -> Result<(), APIError> {
4026                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
4027                         return Err(APIError::APIMisuseError {
4028                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
4029                         });
4030                 }
4031
4032                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4033                 let per_peer_state = self.per_peer_state.read().unwrap();
4034                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4035                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4036                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4037                 let peer_state = &mut *peer_state_lock;
4038                 for channel_id in channel_ids {
4039                         if !peer_state.has_channel(channel_id) {
4040                                 return Err(APIError::ChannelUnavailable {
4041                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4042                                 });
4043                         };
4044                 }
4045                 for channel_id in channel_ids {
4046                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4047                                 let mut config = channel_phase.context().config();
4048                                 config.apply(config_update);
4049                                 if !channel_phase.context_mut().update_config(&config) {
4050                                         continue;
4051                                 }
4052                                 if let ChannelPhase::Funded(channel) = channel_phase {
4053                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4054                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4055                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4056                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4057                                                         node_id: channel.context.get_counterparty_node_id(),
4058                                                         msg,
4059                                                 });
4060                                         }
4061                                 }
4062                                 continue;
4063                         } else {
4064                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4065                                 debug_assert!(false);
4066                                 return Err(APIError::ChannelUnavailable {
4067                                         err: format!(
4068                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4069                                                 channel_id, counterparty_node_id),
4070                                 });
4071                         };
4072                 }
4073                 Ok(())
4074         }
4075
4076         /// Atomically updates the [`ChannelConfig`] for the given channels.
4077         ///
4078         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4079         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4080         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4081         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4082         ///
4083         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4084         /// `counterparty_node_id` is provided.
4085         ///
4086         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4087         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4088         ///
4089         /// If an error is returned, none of the updates should be considered applied.
4090         ///
4091         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4092         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4093         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4094         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4095         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4096         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4097         /// [`APIMisuseError`]: APIError::APIMisuseError
4098         pub fn update_channel_config(
4099                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4100         ) -> Result<(), APIError> {
4101                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4102         }
4103
4104         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4105         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4106         ///
4107         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4108         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4109         ///
4110         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4111         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4112         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4113         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4114         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4115         ///
4116         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4117         /// you from forwarding more than you received. See
4118         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4119         /// than expected.
4120         ///
4121         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4122         /// backwards.
4123         ///
4124         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4125         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4126         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4127         // TODO: when we move to deciding the best outbound channel at forward time, only take
4128         // `next_node_id` and not `next_hop_channel_id`
4129         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> {
4130                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4131
4132                 let next_hop_scid = {
4133                         let peer_state_lock = self.per_peer_state.read().unwrap();
4134                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4135                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4136                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4137                         let peer_state = &mut *peer_state_lock;
4138                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4139                                 Some(ChannelPhase::Funded(chan)) => {
4140                                         if !chan.context.is_usable() {
4141                                                 return Err(APIError::ChannelUnavailable {
4142                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4143                                                 })
4144                                         }
4145                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4146                                 },
4147                                 Some(_) => return Err(APIError::ChannelUnavailable {
4148                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4149                                                 next_hop_channel_id, next_node_id)
4150                                 }),
4151                                 None => {
4152                                         let error = format!("Channel with id {} not found for the passed counterparty node_id {}",
4153                                                 next_hop_channel_id, next_node_id);
4154                                         let logger = WithContext::from(&self.logger, Some(next_node_id), Some(*next_hop_channel_id));
4155                                         log_error!(logger, "{} when attempting to forward intercepted HTLC", error);
4156                                         return Err(APIError::ChannelUnavailable {
4157                                                 err: error
4158                                         })
4159                                 }
4160                         }
4161                 };
4162
4163                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4164                         .ok_or_else(|| APIError::APIMisuseError {
4165                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4166                         })?;
4167
4168                 let routing = match payment.forward_info.routing {
4169                         PendingHTLCRouting::Forward { onion_packet, blinded, .. } => {
4170                                 PendingHTLCRouting::Forward {
4171                                         onion_packet, blinded, short_channel_id: next_hop_scid
4172                                 }
4173                         },
4174                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4175                 };
4176                 let skimmed_fee_msat =
4177                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4178                 let pending_htlc_info = PendingHTLCInfo {
4179                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4180                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4181                 };
4182
4183                 let mut per_source_pending_forward = [(
4184                         payment.prev_short_channel_id,
4185                         payment.prev_funding_outpoint,
4186                         payment.prev_user_channel_id,
4187                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4188                 )];
4189                 self.forward_htlcs(&mut per_source_pending_forward);
4190                 Ok(())
4191         }
4192
4193         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4194         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4195         ///
4196         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4197         /// backwards.
4198         ///
4199         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4200         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4201                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4202
4203                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4204                         .ok_or_else(|| APIError::APIMisuseError {
4205                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4206                         })?;
4207
4208                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4209                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4210                                 short_channel_id: payment.prev_short_channel_id,
4211                                 user_channel_id: Some(payment.prev_user_channel_id),
4212                                 outpoint: payment.prev_funding_outpoint,
4213                                 htlc_id: payment.prev_htlc_id,
4214                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4215                                 phantom_shared_secret: None,
4216                                 blinded_failure: payment.forward_info.routing.blinded_failure(),
4217                         });
4218
4219                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4220                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4221                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4222                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4223
4224                 Ok(())
4225         }
4226
4227         /// Processes HTLCs which are pending waiting on random forward delay.
4228         ///
4229         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4230         /// Will likely generate further events.
4231         pub fn process_pending_htlc_forwards(&self) {
4232                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4233
4234                 let mut new_events = VecDeque::new();
4235                 let mut failed_forwards = Vec::new();
4236                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4237                 {
4238                         let mut forward_htlcs = HashMap::new();
4239                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4240
4241                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4242                                 if short_chan_id != 0 {
4243                                         let mut forwarding_counterparty = None;
4244                                         macro_rules! forwarding_channel_not_found {
4245                                                 () => {
4246                                                         for forward_info in pending_forwards.drain(..) {
4247                                                                 match forward_info {
4248                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4249                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4250                                                                                 forward_info: PendingHTLCInfo {
4251                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4252                                                                                         outgoing_cltv_value, ..
4253                                                                                 }
4254                                                                         }) => {
4255                                                                                 macro_rules! failure_handler {
4256                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4257                                                                                                 let logger = WithContext::from(&self.logger, forwarding_counterparty, Some(prev_funding_outpoint.to_channel_id()));
4258                                                                                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4259
4260                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4261                                                                                                         short_channel_id: prev_short_channel_id,
4262                                                                                                         user_channel_id: Some(prev_user_channel_id),
4263                                                                                                         outpoint: prev_funding_outpoint,
4264                                                                                                         htlc_id: prev_htlc_id,
4265                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4266                                                                                                         phantom_shared_secret: $phantom_ss,
4267                                                                                                         blinded_failure: routing.blinded_failure(),
4268                                                                                                 });
4269
4270                                                                                                 let reason = if $next_hop_unknown {
4271                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4272                                                                                                 } else {
4273                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4274                                                                                                 };
4275
4276                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4277                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4278                                                                                                         reason
4279                                                                                                 ));
4280                                                                                                 continue;
4281                                                                                         }
4282                                                                                 }
4283                                                                                 macro_rules! fail_forward {
4284                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4285                                                                                                 {
4286                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4287                                                                                                 }
4288                                                                                         }
4289                                                                                 }
4290                                                                                 macro_rules! failed_payment {
4291                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4292                                                                                                 {
4293                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4294                                                                                                 }
4295                                                                                         }
4296                                                                                 }
4297                                                                                 if let PendingHTLCRouting::Forward { ref onion_packet, .. } = routing {
4298                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4299                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4300                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4301                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4302                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4303                                                                                                         payment_hash, None, &self.node_signer
4304                                                                                                 ) {
4305                                                                                                         Ok(res) => res,
4306                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4307                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).to_byte_array();
4308                                                                                                                 // In this scenario, the phantom would have sent us an
4309                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4310                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4311                                                                                                                 // of the onion.
4312                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4313                                                                                                         },
4314                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4315                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4316                                                                                                         },
4317                                                                                                 };
4318                                                                                                 match next_hop {
4319                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4320                                                                                                                 let current_height: u32 = self.best_block.read().unwrap().height();
4321                                                                                                                 match create_recv_pending_htlc_info(hop_data,
4322                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4323                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None,
4324                                                                                                                         current_height, self.default_configuration.accept_mpp_keysend)
4325                                                                                                                 {
4326                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4327                                                                                                                         Err(InboundHTLCErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4328                                                                                                                 }
4329                                                                                                         },
4330                                                                                                         _ => panic!(),
4331                                                                                                 }
4332                                                                                         } else {
4333                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4334                                                                                         }
4335                                                                                 } else {
4336                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4337                                                                                 }
4338                                                                         },
4339                                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4340                                                                                 // Channel went away before we could fail it. This implies
4341                                                                                 // the channel is now on chain and our counterparty is
4342                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4343                                                                                 // problem, not ours.
4344                                                                         }
4345                                                                 }
4346                                                         }
4347                                                 }
4348                                         }
4349                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4350                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4351                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4352                                                 None => {
4353                                                         forwarding_channel_not_found!();
4354                                                         continue;
4355                                                 }
4356                                         };
4357                                         forwarding_counterparty = Some(counterparty_node_id);
4358                                         let per_peer_state = self.per_peer_state.read().unwrap();
4359                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4360                                         if peer_state_mutex_opt.is_none() {
4361                                                 forwarding_channel_not_found!();
4362                                                 continue;
4363                                         }
4364                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4365                                         let peer_state = &mut *peer_state_lock;
4366                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4367                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4368                                                 for forward_info in pending_forwards.drain(..) {
4369                                                         let queue_fail_htlc_res = match forward_info {
4370                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4371                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4372                                                                         forward_info: PendingHTLCInfo {
4373                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4374                                                                                 routing: PendingHTLCRouting::Forward {
4375                                                                                         onion_packet, blinded, ..
4376                                                                                 }, skimmed_fee_msat, ..
4377                                                                         },
4378                                                                 }) => {
4379                                                                         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);
4380                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4381                                                                                 short_channel_id: prev_short_channel_id,
4382                                                                                 user_channel_id: Some(prev_user_channel_id),
4383                                                                                 outpoint: prev_funding_outpoint,
4384                                                                                 htlc_id: prev_htlc_id,
4385                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4386                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4387                                                                                 phantom_shared_secret: None,
4388                                                                                 blinded_failure: blinded.map(|b| b.failure),
4389                                                                         });
4390                                                                         let next_blinding_point = blinded.and_then(|b| {
4391                                                                                 let encrypted_tlvs_ss = self.node_signer.ecdh(
4392                                                                                         Recipient::Node, &b.inbound_blinding_point, None
4393                                                                                 ).unwrap().secret_bytes();
4394                                                                                 onion_utils::next_hop_pubkey(
4395                                                                                         &self.secp_ctx, b.inbound_blinding_point, &encrypted_tlvs_ss
4396                                                                                 ).ok()
4397                                                                         });
4398                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4399                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4400                                                                                 onion_packet, skimmed_fee_msat, next_blinding_point, &self.fee_estimator,
4401                                                                                 &&logger)
4402                                                                         {
4403                                                                                 if let ChannelError::Ignore(msg) = e {
4404                                                                                         log_trace!(logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4405                                                                                 } else {
4406                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4407                                                                                 }
4408                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4409                                                                                 failed_forwards.push((htlc_source, payment_hash,
4410                                                                                         HTLCFailReason::reason(failure_code, data),
4411                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4412                                                                                 ));
4413                                                                                 continue;
4414                                                                         }
4415                                                                         None
4416                                                                 },
4417                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4418                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4419                                                                 },
4420                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4421                                                                         log_trace!(logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4422                                                                         Some((chan.queue_fail_htlc(htlc_id, err_packet, &&logger), htlc_id))
4423                                                                 },
4424                                                                 HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
4425                                                                         log_trace!(logger, "Failing malformed HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4426                                                                         let res = chan.queue_fail_malformed_htlc(
4427                                                                                 htlc_id, failure_code, sha256_of_onion, &&logger
4428                                                                         );
4429                                                                         Some((res, htlc_id))
4430                                                                 },
4431                                                         };
4432                                                         if let Some((queue_fail_htlc_res, htlc_id)) = queue_fail_htlc_res {
4433                                                                 if let Err(e) = queue_fail_htlc_res {
4434                                                                         if let ChannelError::Ignore(msg) = e {
4435                                                                                 log_trace!(logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4436                                                                         } else {
4437                                                                                 panic!("Stated return value requirements in queue_fail_{{malformed_}}htlc() were not met");
4438                                                                         }
4439                                                                         // fail-backs are best-effort, we probably already have one
4440                                                                         // pending, and if not that's OK, if not, the channel is on
4441                                                                         // the chain and sending the HTLC-Timeout is their problem.
4442                                                                         continue;
4443                                                                 }
4444                                                         }
4445                                                 }
4446                                         } else {
4447                                                 forwarding_channel_not_found!();
4448                                                 continue;
4449                                         }
4450                                 } else {
4451                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4452                                                 match forward_info {
4453                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4454                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4455                                                                 forward_info: PendingHTLCInfo {
4456                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4457                                                                         skimmed_fee_msat, ..
4458                                                                 }
4459                                                         }) => {
4460                                                                 let blinded_failure = routing.blinded_failure();
4461                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4462                                                                         PendingHTLCRouting::Receive {
4463                                                                                 payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret,
4464                                                                                 custom_tlvs, requires_blinded_error: _
4465                                                                         } => {
4466                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4467                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4468                                                                                                 payment_metadata, custom_tlvs };
4469                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4470                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4471                                                                         },
4472                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4473                                                                                 let onion_fields = RecipientOnionFields {
4474                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4475                                                                                         payment_metadata,
4476                                                                                         custom_tlvs,
4477                                                                                 };
4478                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4479                                                                                         payment_data, None, onion_fields)
4480                                                                         },
4481                                                                         _ => {
4482                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4483                                                                         }
4484                                                                 };
4485                                                                 let claimable_htlc = ClaimableHTLC {
4486                                                                         prev_hop: HTLCPreviousHopData {
4487                                                                                 short_channel_id: prev_short_channel_id,
4488                                                                                 user_channel_id: Some(prev_user_channel_id),
4489                                                                                 outpoint: prev_funding_outpoint,
4490                                                                                 htlc_id: prev_htlc_id,
4491                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4492                                                                                 phantom_shared_secret,
4493                                                                                 blinded_failure,
4494                                                                         },
4495                                                                         // We differentiate the received value from the sender intended value
4496                                                                         // if possible so that we don't prematurely mark MPP payments complete
4497                                                                         // if routing nodes overpay
4498                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4499                                                                         sender_intended_value: outgoing_amt_msat,
4500                                                                         timer_ticks: 0,
4501                                                                         total_value_received: None,
4502                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4503                                                                         cltv_expiry,
4504                                                                         onion_payload,
4505                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4506                                                                 };
4507
4508                                                                 let mut committed_to_claimable = false;
4509
4510                                                                 macro_rules! fail_htlc {
4511                                                                         ($htlc: expr, $payment_hash: expr) => {
4512                                                                                 debug_assert!(!committed_to_claimable);
4513                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4514                                                                                 htlc_msat_height_data.extend_from_slice(
4515                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4516                                                                                 );
4517                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4518                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4519                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4520                                                                                                 outpoint: prev_funding_outpoint,
4521                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4522                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4523                                                                                                 phantom_shared_secret,
4524                                                                                                 blinded_failure,
4525                                                                                         }), payment_hash,
4526                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4527                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4528                                                                                 ));
4529                                                                                 continue 'next_forwardable_htlc;
4530                                                                         }
4531                                                                 }
4532                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4533                                                                 let mut receiver_node_id = self.our_network_pubkey;
4534                                                                 if phantom_shared_secret.is_some() {
4535                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4536                                                                                 .expect("Failed to get node_id for phantom node recipient");
4537                                                                 }
4538
4539                                                                 macro_rules! check_total_value {
4540                                                                         ($purpose: expr) => {{
4541                                                                                 let mut payment_claimable_generated = false;
4542                                                                                 let is_keysend = match $purpose {
4543                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4544                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4545                                                                                 };
4546                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4547                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4548                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4549                                                                                 }
4550                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4551                                                                                         .entry(payment_hash)
4552                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4553                                                                                         .or_insert_with(|| {
4554                                                                                                 committed_to_claimable = true;
4555                                                                                                 ClaimablePayment {
4556                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4557                                                                                                 }
4558                                                                                         });
4559                                                                                 if $purpose != claimable_payment.purpose {
4560                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4561                                                                                         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));
4562                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4563                                                                                 }
4564                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4565                                                                                         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);
4566                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4567                                                                                 }
4568                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4569                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4570                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4571                                                                                         }
4572                                                                                 } else {
4573                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4574                                                                                 }
4575                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4576                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4577                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4578                                                                                 for htlc in htlcs.iter() {
4579                                                                                         total_value += htlc.sender_intended_value;
4580                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4581                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4582                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4583                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4584                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4585                                                                                         }
4586                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4587                                                                                 }
4588                                                                                 // The condition determining whether an MPP is complete must
4589                                                                                 // match exactly the condition used in `timer_tick_occurred`
4590                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4591                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4592                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4593                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4594                                                                                                 &payment_hash);
4595                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4596                                                                                 } else if total_value >= claimable_htlc.total_msat {
4597                                                                                         #[allow(unused_assignments)] {
4598                                                                                                 committed_to_claimable = true;
4599                                                                                         }
4600                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4601                                                                                         htlcs.push(claimable_htlc);
4602                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4603                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4604                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4605                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4606                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4607                                                                                                 counterparty_skimmed_fee_msat);
4608                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4609                                                                                                 receiver_node_id: Some(receiver_node_id),
4610                                                                                                 payment_hash,
4611                                                                                                 purpose: $purpose,
4612                                                                                                 amount_msat,
4613                                                                                                 counterparty_skimmed_fee_msat,
4614                                                                                                 via_channel_id: Some(prev_channel_id),
4615                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4616                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4617                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4618                                                                                         }, None));
4619                                                                                         payment_claimable_generated = true;
4620                                                                                 } else {
4621                                                                                         // Nothing to do - we haven't reached the total
4622                                                                                         // payment value yet, wait until we receive more
4623                                                                                         // MPP parts.
4624                                                                                         htlcs.push(claimable_htlc);
4625                                                                                         #[allow(unused_assignments)] {
4626                                                                                                 committed_to_claimable = true;
4627                                                                                         }
4628                                                                                 }
4629                                                                                 payment_claimable_generated
4630                                                                         }}
4631                                                                 }
4632
4633                                                                 // Check that the payment hash and secret are known. Note that we
4634                                                                 // MUST take care to handle the "unknown payment hash" and
4635                                                                 // "incorrect payment secret" cases here identically or we'd expose
4636                                                                 // that we are the ultimate recipient of the given payment hash.
4637                                                                 // Further, we must not expose whether we have any other HTLCs
4638                                                                 // associated with the same payment_hash pending or not.
4639                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4640                                                                 match payment_secrets.entry(payment_hash) {
4641                                                                         hash_map::Entry::Vacant(_) => {
4642                                                                                 match claimable_htlc.onion_payload {
4643                                                                                         OnionPayload::Invoice { .. } => {
4644                                                                                                 let payment_data = payment_data.unwrap();
4645                                                                                                 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) {
4646                                                                                                         Ok(result) => result,
4647                                                                                                         Err(()) => {
4648                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4649                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4650                                                                                                         }
4651                                                                                                 };
4652                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4653                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4654                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4655                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4656                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4657                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4658                                                                                                         }
4659                                                                                                 }
4660                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4661                                                                                                         payment_preimage: payment_preimage.clone(),
4662                                                                                                         payment_secret: payment_data.payment_secret,
4663                                                                                                 };
4664                                                                                                 check_total_value!(purpose);
4665                                                                                         },
4666                                                                                         OnionPayload::Spontaneous(preimage) => {
4667                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4668                                                                                                 check_total_value!(purpose);
4669                                                                                         }
4670                                                                                 }
4671                                                                         },
4672                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4673                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4674                                                                                         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);
4675                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4676                                                                                 }
4677                                                                                 let payment_data = payment_data.unwrap();
4678                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4679                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4680                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4681                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4682                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4683                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4684                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4685                                                                                 } else {
4686                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4687                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4688                                                                                                 payment_secret: payment_data.payment_secret,
4689                                                                                         };
4690                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4691                                                                                         if payment_claimable_generated {
4692                                                                                                 inbound_payment.remove_entry();
4693                                                                                         }
4694                                                                                 }
4695                                                                         },
4696                                                                 };
4697                                                         },
4698                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4699                                                                 panic!("Got pending fail of our own HTLC");
4700                                                         }
4701                                                 }
4702                                         }
4703                                 }
4704                         }
4705                 }
4706
4707                 let best_block_height = self.best_block.read().unwrap().height();
4708                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4709                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4710                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4711
4712                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4713                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4714                 }
4715                 self.forward_htlcs(&mut phantom_receives);
4716
4717                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4718                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4719                 // nice to do the work now if we can rather than while we're trying to get messages in the
4720                 // network stack.
4721                 self.check_free_holding_cells();
4722
4723                 if new_events.is_empty() { return }
4724                 let mut events = self.pending_events.lock().unwrap();
4725                 events.append(&mut new_events);
4726         }
4727
4728         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4729         ///
4730         /// Expects the caller to have a total_consistency_lock read lock.
4731         fn process_background_events(&self) -> NotifyOption {
4732                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4733
4734                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4735
4736                 let mut background_events = Vec::new();
4737                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4738                 if background_events.is_empty() {
4739                         return NotifyOption::SkipPersistNoEvents;
4740                 }
4741
4742                 for event in background_events.drain(..) {
4743                         match event {
4744                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4745                                         // The channel has already been closed, so no use bothering to care about the
4746                                         // monitor updating completing.
4747                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4748                                 },
4749                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4750                                         let mut updated_chan = false;
4751                                         {
4752                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4753                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4754                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4755                                                         let peer_state = &mut *peer_state_lock;
4756                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4757                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4758                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4759                                                                                 updated_chan = true;
4760                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4761                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4762                                                                         } else {
4763                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4764                                                                         }
4765                                                                 },
4766                                                                 hash_map::Entry::Vacant(_) => {},
4767                                                         }
4768                                                 }
4769                                         }
4770                                         if !updated_chan {
4771                                                 // TODO: Track this as in-flight even though the channel is closed.
4772                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4773                                         }
4774                                 },
4775                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4776                                         let per_peer_state = self.per_peer_state.read().unwrap();
4777                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4778                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4779                                                 let peer_state = &mut *peer_state_lock;
4780                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4781                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4782                                                 } else {
4783                                                         let update_actions = peer_state.monitor_update_blocked_actions
4784                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4785                                                         mem::drop(peer_state_lock);
4786                                                         mem::drop(per_peer_state);
4787                                                         self.handle_monitor_update_completion_actions(update_actions);
4788                                                 }
4789                                         }
4790                                 },
4791                         }
4792                 }
4793                 NotifyOption::DoPersist
4794         }
4795
4796         #[cfg(any(test, feature = "_test_utils"))]
4797         /// Process background events, for functional testing
4798         pub fn test_process_background_events(&self) {
4799                 let _lck = self.total_consistency_lock.read().unwrap();
4800                 let _ = self.process_background_events();
4801         }
4802
4803         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4804                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4805
4806                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4807
4808                 // If the feerate has decreased by less than half, don't bother
4809                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4810                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4811                                 log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4812                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4813                         }
4814                         return NotifyOption::SkipPersistNoEvents;
4815                 }
4816                 if !chan.context.is_live() {
4817                         log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
4818                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4819                         return NotifyOption::SkipPersistNoEvents;
4820                 }
4821                 log_trace!(logger, "Channel {} qualifies for a feerate change from {} to {}.",
4822                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4823
4824                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &&logger);
4825                 NotifyOption::DoPersist
4826         }
4827
4828         #[cfg(fuzzing)]
4829         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4830         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4831         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4832         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4833         pub fn maybe_update_chan_fees(&self) {
4834                 PersistenceNotifierGuard::optionally_notify(self, || {
4835                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4836
4837                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4838                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4839
4840                         let per_peer_state = self.per_peer_state.read().unwrap();
4841                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4842                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4843                                 let peer_state = &mut *peer_state_lock;
4844                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4845                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4846                                 ) {
4847                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4848                                                 anchor_feerate
4849                                         } else {
4850                                                 non_anchor_feerate
4851                                         };
4852                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4853                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4854                                 }
4855                         }
4856
4857                         should_persist
4858                 });
4859         }
4860
4861         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4862         ///
4863         /// This currently includes:
4864         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4865         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4866         ///    than a minute, informing the network that they should no longer attempt to route over
4867         ///    the channel.
4868         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4869         ///    with the current [`ChannelConfig`].
4870         ///  * Removing peers which have disconnected but and no longer have any channels.
4871         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4872         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4873         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4874         ///    The latter is determined using the system clock in `std` and the highest seen block time
4875         ///    minus two hours in `no-std`.
4876         ///
4877         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4878         /// estimate fetches.
4879         ///
4880         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4881         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4882         pub fn timer_tick_occurred(&self) {
4883                 PersistenceNotifierGuard::optionally_notify(self, || {
4884                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4885
4886                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4887                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4888
4889                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4890                         let mut timed_out_mpp_htlcs = Vec::new();
4891                         let mut pending_peers_awaiting_removal = Vec::new();
4892                         let mut shutdown_channels = Vec::new();
4893
4894                         let mut process_unfunded_channel_tick = |
4895                                 chan_id: &ChannelId,
4896                                 context: &mut ChannelContext<SP>,
4897                                 unfunded_context: &mut UnfundedChannelContext,
4898                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4899                                 counterparty_node_id: PublicKey,
4900                         | {
4901                                 context.maybe_expire_prev_config();
4902                                 if unfunded_context.should_expire_unfunded_channel() {
4903                                         let logger = WithChannelContext::from(&self.logger, context);
4904                                         log_error!(logger,
4905                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4906                                         update_maps_on_chan_removal!(self, &context);
4907                                         shutdown_channels.push(context.force_shutdown(false, ClosureReason::HolderForceClosed));
4908                                         pending_msg_events.push(MessageSendEvent::HandleError {
4909                                                 node_id: counterparty_node_id,
4910                                                 action: msgs::ErrorAction::SendErrorMessage {
4911                                                         msg: msgs::ErrorMessage {
4912                                                                 channel_id: *chan_id,
4913                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4914                                                         },
4915                                                 },
4916                                         });
4917                                         false
4918                                 } else {
4919                                         true
4920                                 }
4921                         };
4922
4923                         {
4924                                 let per_peer_state = self.per_peer_state.read().unwrap();
4925                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4926                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4927                                         let peer_state = &mut *peer_state_lock;
4928                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4929                                         let counterparty_node_id = *counterparty_node_id;
4930                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4931                                                 match phase {
4932                                                         ChannelPhase::Funded(chan) => {
4933                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4934                                                                         anchor_feerate
4935                                                                 } else {
4936                                                                         non_anchor_feerate
4937                                                                 };
4938                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4939                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4940
4941                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4942                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4943                                                                         handle_errors.push((Err(err), counterparty_node_id));
4944                                                                         if needs_close { return false; }
4945                                                                 }
4946
4947                                                                 match chan.channel_update_status() {
4948                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4949                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4950                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4951                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4952                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4953                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4954                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4955                                                                                 n += 1;
4956                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4957                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4958                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4959                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4960                                                                                                         msg: update
4961                                                                                                 });
4962                                                                                         }
4963                                                                                         should_persist = NotifyOption::DoPersist;
4964                                                                                 } else {
4965                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4966                                                                                 }
4967                                                                         },
4968                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4969                                                                                 n += 1;
4970                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4971                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4972                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4973                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4974                                                                                                         msg: update
4975                                                                                                 });
4976                                                                                         }
4977                                                                                         should_persist = NotifyOption::DoPersist;
4978                                                                                 } else {
4979                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4980                                                                                 }
4981                                                                         },
4982                                                                         _ => {},
4983                                                                 }
4984
4985                                                                 chan.context.maybe_expire_prev_config();
4986
4987                                                                 if chan.should_disconnect_peer_awaiting_response() {
4988                                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
4989                                                                         log_debug!(logger, "Disconnecting peer {} due to not making any progress on channel {}",
4990                                                                                         counterparty_node_id, chan_id);
4991                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4992                                                                                 node_id: counterparty_node_id,
4993                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4994                                                                                         msg: msgs::WarningMessage {
4995                                                                                                 channel_id: *chan_id,
4996                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4997                                                                                         },
4998                                                                                 },
4999                                                                         });
5000                                                                 }
5001
5002                                                                 true
5003                                                         },
5004                                                         ChannelPhase::UnfundedInboundV1(chan) => {
5005                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5006                                                                         pending_msg_events, counterparty_node_id)
5007                                                         },
5008                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
5009                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5010                                                                         pending_msg_events, counterparty_node_id)
5011                                                         },
5012                                                 }
5013                                         });
5014
5015                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
5016                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
5017                                                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(*chan_id));
5018                                                         log_error!(logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
5019                                                         peer_state.pending_msg_events.push(
5020                                                                 events::MessageSendEvent::HandleError {
5021                                                                         node_id: counterparty_node_id,
5022                                                                         action: msgs::ErrorAction::SendErrorMessage {
5023                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
5024                                                                         },
5025                                                                 }
5026                                                         );
5027                                                 }
5028                                         }
5029                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
5030
5031                                         if peer_state.ok_to_remove(true) {
5032                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
5033                                         }
5034                                 }
5035                         }
5036
5037                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
5038                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
5039                         // of to that peer is later closed while still being disconnected (i.e. force closed),
5040                         // we therefore need to remove the peer from `peer_state` separately.
5041                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
5042                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
5043                         // negative effects on parallelism as much as possible.
5044                         if pending_peers_awaiting_removal.len() > 0 {
5045                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
5046                                 for counterparty_node_id in pending_peers_awaiting_removal {
5047                                         match per_peer_state.entry(counterparty_node_id) {
5048                                                 hash_map::Entry::Occupied(entry) => {
5049                                                         // Remove the entry if the peer is still disconnected and we still
5050                                                         // have no channels to the peer.
5051                                                         let remove_entry = {
5052                                                                 let peer_state = entry.get().lock().unwrap();
5053                                                                 peer_state.ok_to_remove(true)
5054                                                         };
5055                                                         if remove_entry {
5056                                                                 entry.remove_entry();
5057                                                         }
5058                                                 },
5059                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
5060                                         }
5061                                 }
5062                         }
5063
5064                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
5065                                 if payment.htlcs.is_empty() {
5066                                         // This should be unreachable
5067                                         debug_assert!(false);
5068                                         return false;
5069                                 }
5070                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
5071                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
5072                                         // In this case we're not going to handle any timeouts of the parts here.
5073                                         // This condition determining whether the MPP is complete here must match
5074                                         // exactly the condition used in `process_pending_htlc_forwards`.
5075                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5076                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5077                                         {
5078                                                 return true;
5079                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5080                                                 htlc.timer_ticks += 1;
5081                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5082                                         }) {
5083                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5084                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5085                                                 return false;
5086                                         }
5087                                 }
5088                                 true
5089                         });
5090
5091                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5092                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5093                                 let reason = HTLCFailReason::from_failure_code(23);
5094                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5095                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5096                         }
5097
5098                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5099                                 let _ = handle_error!(self, err, counterparty_node_id);
5100                         }
5101
5102                         for shutdown_res in shutdown_channels {
5103                                 self.finish_close_channel(shutdown_res);
5104                         }
5105
5106                         #[cfg(feature = "std")]
5107                         let duration_since_epoch = std::time::SystemTime::now()
5108                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5109                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5110                         #[cfg(not(feature = "std"))]
5111                         let duration_since_epoch = Duration::from_secs(
5112                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5113                         );
5114
5115                         self.pending_outbound_payments.remove_stale_payments(
5116                                 duration_since_epoch, &self.pending_events
5117                         );
5118
5119                         // Technically we don't need to do this here, but if we have holding cell entries in a
5120                         // channel that need freeing, it's better to do that here and block a background task
5121                         // than block the message queueing pipeline.
5122                         if self.check_free_holding_cells() {
5123                                 should_persist = NotifyOption::DoPersist;
5124                         }
5125
5126                         should_persist
5127                 });
5128         }
5129
5130         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5131         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5132         /// along the path (including in our own channel on which we received it).
5133         ///
5134         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5135         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5136         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5137         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5138         ///
5139         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5140         /// [`ChannelManager::claim_funds`]), you should still monitor for
5141         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5142         /// startup during which time claims that were in-progress at shutdown may be replayed.
5143         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5144                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5145         }
5146
5147         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5148         /// reason for the failure.
5149         ///
5150         /// See [`FailureCode`] for valid failure codes.
5151         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5152                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5153
5154                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5155                 if let Some(payment) = removed_source {
5156                         for htlc in payment.htlcs {
5157                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5158                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5159                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5160                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5161                         }
5162                 }
5163         }
5164
5165         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5166         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5167                 match failure_code {
5168                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5169                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5170                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5171                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5172                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5173                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5174                         },
5175                         FailureCode::InvalidOnionPayload(data) => {
5176                                 let fail_data = match data {
5177                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5178                                         None => Vec::new(),
5179                                 };
5180                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5181                         }
5182                 }
5183         }
5184
5185         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5186         /// that we want to return and a channel.
5187         ///
5188         /// This is for failures on the channel on which the HTLC was *received*, not failures
5189         /// forwarding
5190         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5191                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5192                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5193                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5194                 // an inbound SCID alias before the real SCID.
5195                 let scid_pref = if chan.context.should_announce() {
5196                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5197                 } else {
5198                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5199                 };
5200                 if let Some(scid) = scid_pref {
5201                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5202                 } else {
5203                         (0x4000|10, Vec::new())
5204                 }
5205         }
5206
5207
5208         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5209         /// that we want to return and a channel.
5210         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5211                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5212                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5213                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5214                         if desired_err_code == 0x1000 | 20 {
5215                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5216                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5217                                 0u16.write(&mut enc).expect("Writes cannot fail");
5218                         }
5219                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5220                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5221                         upd.write(&mut enc).expect("Writes cannot fail");
5222                         (desired_err_code, enc.0)
5223                 } else {
5224                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5225                         // which means we really shouldn't have gotten a payment to be forwarded over this
5226                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5227                         // PERM|no_such_channel should be fine.
5228                         (0x4000|10, Vec::new())
5229                 }
5230         }
5231
5232         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5233         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5234         // be surfaced to the user.
5235         fn fail_holding_cell_htlcs(
5236                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5237                 counterparty_node_id: &PublicKey
5238         ) {
5239                 let (failure_code, onion_failure_data) = {
5240                         let per_peer_state = self.per_peer_state.read().unwrap();
5241                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5242                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5243                                 let peer_state = &mut *peer_state_lock;
5244                                 match peer_state.channel_by_id.entry(channel_id) {
5245                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5246                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5247                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5248                                                 } else {
5249                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5250                                                         debug_assert!(false);
5251                                                         (0x4000|10, Vec::new())
5252                                                 }
5253                                         },
5254                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5255                                 }
5256                         } else { (0x4000|10, Vec::new()) }
5257                 };
5258
5259                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5260                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5261                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5262                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5263                 }
5264         }
5265
5266         /// Fails an HTLC backwards to the sender of it to us.
5267         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5268         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5269                 // Ensure that no peer state channel storage lock is held when calling this function.
5270                 // This ensures that future code doesn't introduce a lock-order requirement for
5271                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5272                 // this function with any `per_peer_state` peer lock acquired would.
5273                 #[cfg(debug_assertions)]
5274                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5275                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5276                 }
5277
5278                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5279                 //identify whether we sent it or not based on the (I presume) very different runtime
5280                 //between the branches here. We should make this async and move it into the forward HTLCs
5281                 //timer handling.
5282
5283                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5284                 // from block_connected which may run during initialization prior to the chain_monitor
5285                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5286                 match source {
5287                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5288                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5289                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5290                                         &self.pending_events, &self.logger)
5291                                 { self.push_pending_forwards_ev(); }
5292                         },
5293                         HTLCSource::PreviousHopData(HTLCPreviousHopData {
5294                                 ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret,
5295                                 ref phantom_shared_secret, ref outpoint, ref blinded_failure, ..
5296                         }) => {
5297                                 log_trace!(
5298                                         WithContext::from(&self.logger, None, Some(outpoint.to_channel_id())),
5299                                         "Failing {}HTLC with payment_hash {} backwards from us: {:?}",
5300                                         if blinded_failure.is_some() { "blinded " } else { "" }, &payment_hash, onion_error
5301                                 );
5302                                 let failure = match blinded_failure {
5303                                         Some(BlindedFailure::FromIntroductionNode) => {
5304                                                 let blinded_onion_error = HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32]);
5305                                                 let err_packet = blinded_onion_error.get_encrypted_failure_packet(
5306                                                         incoming_packet_shared_secret, phantom_shared_secret
5307                                                 );
5308                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5309                                         },
5310                                         Some(BlindedFailure::FromBlindedNode) => {
5311                                                 HTLCForwardInfo::FailMalformedHTLC {
5312                                                         htlc_id: *htlc_id,
5313                                                         failure_code: INVALID_ONION_BLINDING,
5314                                                         sha256_of_onion: [0; 32]
5315                                                 }
5316                                         },
5317                                         None => {
5318                                                 let err_packet = onion_error.get_encrypted_failure_packet(
5319                                                         incoming_packet_shared_secret, phantom_shared_secret
5320                                                 );
5321                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5322                                         }
5323                                 };
5324
5325                                 let mut push_forward_ev = false;
5326                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5327                                 if forward_htlcs.is_empty() {
5328                                         push_forward_ev = true;
5329                                 }
5330                                 match forward_htlcs.entry(*short_channel_id) {
5331                                         hash_map::Entry::Occupied(mut entry) => {
5332                                                 entry.get_mut().push(failure);
5333                                         },
5334                                         hash_map::Entry::Vacant(entry) => {
5335                                                 entry.insert(vec!(failure));
5336                                         }
5337                                 }
5338                                 mem::drop(forward_htlcs);
5339                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5340                                 let mut pending_events = self.pending_events.lock().unwrap();
5341                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5342                                         prev_channel_id: outpoint.to_channel_id(),
5343                                         failed_next_destination: destination,
5344                                 }, None));
5345                         },
5346                 }
5347         }
5348
5349         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5350         /// [`MessageSendEvent`]s needed to claim the payment.
5351         ///
5352         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5353         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5354         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5355         /// successful. It will generally be available in the next [`process_pending_events`] call.
5356         ///
5357         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5358         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5359         /// event matches your expectation. If you fail to do so and call this method, you may provide
5360         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5361         ///
5362         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5363         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5364         /// [`claim_funds_with_known_custom_tlvs`].
5365         ///
5366         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5367         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5368         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5369         /// [`process_pending_events`]: EventsProvider::process_pending_events
5370         /// [`create_inbound_payment`]: Self::create_inbound_payment
5371         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5372         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5373         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5374                 self.claim_payment_internal(payment_preimage, false);
5375         }
5376
5377         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5378         /// even type numbers.
5379         ///
5380         /// # Note
5381         ///
5382         /// You MUST check you've understood all even TLVs before using this to
5383         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5384         ///
5385         /// [`claim_funds`]: Self::claim_funds
5386         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5387                 self.claim_payment_internal(payment_preimage, true);
5388         }
5389
5390         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5391                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
5392
5393                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5394
5395                 let mut sources = {
5396                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5397                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5398                                 let mut receiver_node_id = self.our_network_pubkey;
5399                                 for htlc in payment.htlcs.iter() {
5400                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5401                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5402                                                         .expect("Failed to get node_id for phantom node recipient");
5403                                                 receiver_node_id = phantom_pubkey;
5404                                                 break;
5405                                         }
5406                                 }
5407
5408                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5409                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5410                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5411                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5412                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5413                                 });
5414                                 if dup_purpose.is_some() {
5415                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5416                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5417                                                 &payment_hash);
5418                                 }
5419
5420                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5421                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5422                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5423                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5424                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5425                                                 mem::drop(claimable_payments);
5426                                                 for htlc in payment.htlcs {
5427                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5428                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5429                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5430                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5431                                                 }
5432                                                 return;
5433                                         }
5434                                 }
5435
5436                                 payment.htlcs
5437                         } else { return; }
5438                 };
5439                 debug_assert!(!sources.is_empty());
5440
5441                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5442                 // and when we got here we need to check that the amount we're about to claim matches the
5443                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5444                 // the MPP parts all have the same `total_msat`.
5445                 let mut claimable_amt_msat = 0;
5446                 let mut prev_total_msat = None;
5447                 let mut expected_amt_msat = None;
5448                 let mut valid_mpp = true;
5449                 let mut errs = Vec::new();
5450                 let per_peer_state = self.per_peer_state.read().unwrap();
5451                 for htlc in sources.iter() {
5452                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5453                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5454                                 debug_assert!(false);
5455                                 valid_mpp = false;
5456                                 break;
5457                         }
5458                         prev_total_msat = Some(htlc.total_msat);
5459
5460                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5461                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5462                                 debug_assert!(false);
5463                                 valid_mpp = false;
5464                                 break;
5465                         }
5466                         expected_amt_msat = htlc.total_value_received;
5467                         claimable_amt_msat += htlc.value;
5468                 }
5469                 mem::drop(per_peer_state);
5470                 if sources.is_empty() || expected_amt_msat.is_none() {
5471                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5472                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5473                         return;
5474                 }
5475                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5476                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5477                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5478                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5479                         return;
5480                 }
5481                 if valid_mpp {
5482                         for htlc in sources.drain(..) {
5483                                 let prev_hop_chan_id = htlc.prev_hop.outpoint.to_channel_id();
5484                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5485                                         htlc.prev_hop, payment_preimage,
5486                                         |_, definitely_duplicate| {
5487                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5488                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5489                                         }
5490                                 ) {
5491                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5492                                                 // We got a temporary failure updating monitor, but will claim the
5493                                                 // HTLC when the monitor updating is restored (or on chain).
5494                                                 let logger = WithContext::from(&self.logger, None, Some(prev_hop_chan_id));
5495                                                 log_error!(logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5496                                         } else { errs.push((pk, err)); }
5497                                 }
5498                         }
5499                 }
5500                 if !valid_mpp {
5501                         for htlc in sources.drain(..) {
5502                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5503                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5504                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5505                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5506                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5507                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5508                         }
5509                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5510                 }
5511
5512                 // Now we can handle any errors which were generated.
5513                 for (counterparty_node_id, err) in errs.drain(..) {
5514                         let res: Result<(), _> = Err(err);
5515                         let _ = handle_error!(self, res, counterparty_node_id);
5516                 }
5517         }
5518
5519         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5520                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5521         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5522                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5523
5524                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5525                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5526                 // `BackgroundEvent`s.
5527                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5528
5529                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5530                 // the required mutexes are not held before we start.
5531                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5532                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5533
5534                 {
5535                         let per_peer_state = self.per_peer_state.read().unwrap();
5536                         let chan_id = prev_hop.outpoint.to_channel_id();
5537                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5538                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5539                                 None => None
5540                         };
5541
5542                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5543                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5544                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5545                         ).unwrap_or(None);
5546
5547                         if peer_state_opt.is_some() {
5548                                 let mut peer_state_lock = peer_state_opt.unwrap();
5549                                 let peer_state = &mut *peer_state_lock;
5550                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5551                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5552                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5553                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
5554                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &&logger);
5555
5556                                                 match fulfill_res {
5557                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5558                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5559                                                                         log_trace!(logger, "Tracking monitor update completion action for channel {}: {:?}",
5560                                                                                 chan_id, action);
5561                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5562                                                                 }
5563                                                                 if !during_init {
5564                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5565                                                                                 peer_state, per_peer_state, chan);
5566                                                                 } else {
5567                                                                         // If we're running during init we cannot update a monitor directly -
5568                                                                         // they probably haven't actually been loaded yet. Instead, push the
5569                                                                         // monitor update as a background event.
5570                                                                         self.pending_background_events.lock().unwrap().push(
5571                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5572                                                                                         counterparty_node_id,
5573                                                                                         funding_txo: prev_hop.outpoint,
5574                                                                                         update: monitor_update.clone(),
5575                                                                                 });
5576                                                                 }
5577                                                         }
5578                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5579                                                                 let action = if let Some(action) = completion_action(None, true) {
5580                                                                         action
5581                                                                 } else {
5582                                                                         return Ok(());
5583                                                                 };
5584                                                                 mem::drop(peer_state_lock);
5585
5586                                                                 log_trace!(logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5587                                                                         chan_id, action);
5588                                                                 let (node_id, funding_outpoint, blocker) =
5589                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5590                                                                         downstream_counterparty_node_id: node_id,
5591                                                                         downstream_funding_outpoint: funding_outpoint,
5592                                                                         blocking_action: blocker,
5593                                                                 } = action {
5594                                                                         (node_id, funding_outpoint, blocker)
5595                                                                 } else {
5596                                                                         debug_assert!(false,
5597                                                                                 "Duplicate claims should always free another channel immediately");
5598                                                                         return Ok(());
5599                                                                 };
5600                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5601                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5602                                                                         if let Some(blockers) = peer_state
5603                                                                                 .actions_blocking_raa_monitor_updates
5604                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5605                                                                         {
5606                                                                                 let mut found_blocker = false;
5607                                                                                 blockers.retain(|iter| {
5608                                                                                         // Note that we could actually be blocked, in
5609                                                                                         // which case we need to only remove the one
5610                                                                                         // blocker which was added duplicatively.
5611                                                                                         let first_blocker = !found_blocker;
5612                                                                                         if *iter == blocker { found_blocker = true; }
5613                                                                                         *iter != blocker || !first_blocker
5614                                                                                 });
5615                                                                                 debug_assert!(found_blocker);
5616                                                                         }
5617                                                                 } else {
5618                                                                         debug_assert!(false);
5619                                                                 }
5620                                                         }
5621                                                 }
5622                                         }
5623                                         return Ok(());
5624                                 }
5625                         }
5626                 }
5627                 let preimage_update = ChannelMonitorUpdate {
5628                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5629                         counterparty_node_id: None,
5630                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5631                                 payment_preimage,
5632                         }],
5633                 };
5634
5635                 if !during_init {
5636                         // We update the ChannelMonitor on the backward link, after
5637                         // receiving an `update_fulfill_htlc` from the forward link.
5638                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5639                         if update_res != ChannelMonitorUpdateStatus::Completed {
5640                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5641                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5642                                 // channel, or we must have an ability to receive the same event and try
5643                                 // again on restart.
5644                                 log_error!(WithContext::from(&self.logger, None, Some(prev_hop.outpoint.to_channel_id())), "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5645                                         payment_preimage, update_res);
5646                         }
5647                 } else {
5648                         // If we're running during init we cannot update a monitor directly - they probably
5649                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5650                         // event.
5651                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5652                         // channel is already closed) we need to ultimately handle the monitor update
5653                         // completion action only after we've completed the monitor update. This is the only
5654                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5655                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5656                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5657                         // complete the monitor update completion action from `completion_action`.
5658                         self.pending_background_events.lock().unwrap().push(
5659                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5660                                         prev_hop.outpoint, preimage_update,
5661                                 )));
5662                 }
5663                 // Note that we do process the completion action here. This totally could be a
5664                 // duplicate claim, but we have no way of knowing without interrogating the
5665                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5666                 // generally always allowed to be duplicative (and it's specifically noted in
5667                 // `PaymentForwarded`).
5668                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5669                 Ok(())
5670         }
5671
5672         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5673                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5674         }
5675
5676         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5677                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5678                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5679         ) {
5680                 match source {
5681                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5682                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5683                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5684                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5685                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5686                                 }
5687                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5688                                         channel_funding_outpoint: next_channel_outpoint,
5689                                         counterparty_node_id: path.hops[0].pubkey,
5690                                 };
5691                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5692                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5693                                         &self.logger);
5694                         },
5695                         HTLCSource::PreviousHopData(hop_data) => {
5696                                 let prev_outpoint = hop_data.outpoint;
5697                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5698                                 #[cfg(debug_assertions)]
5699                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5700                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5701                                         |htlc_claim_value_msat, definitely_duplicate| {
5702                                                 let chan_to_release =
5703                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5704                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5705                                                         } else {
5706                                                                 // We can only get `None` here if we are processing a
5707                                                                 // `ChannelMonitor`-originated event, in which case we
5708                                                                 // don't care about ensuring we wake the downstream
5709                                                                 // channel's monitor updating - the channel is already
5710                                                                 // closed.
5711                                                                 None
5712                                                         };
5713
5714                                                 if definitely_duplicate && startup_replay {
5715                                                         // On startup we may get redundant claims which are related to
5716                                                         // monitor updates still in flight. In that case, we shouldn't
5717                                                         // immediately free, but instead let that monitor update complete
5718                                                         // in the background.
5719                                                         #[cfg(debug_assertions)] {
5720                                                                 let background_events = self.pending_background_events.lock().unwrap();
5721                                                                 // There should be a `BackgroundEvent` pending...
5722                                                                 assert!(background_events.iter().any(|ev| {
5723                                                                         match ev {
5724                                                                                 // to apply a monitor update that blocked the claiming channel,
5725                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5726                                                                                         funding_txo, update, ..
5727                                                                                 } => {
5728                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5729                                                                                                 assert!(update.updates.iter().any(|upd|
5730                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5731                                                                                                                 payment_preimage: update_preimage
5732                                                                                                         } = upd {
5733                                                                                                                 payment_preimage == *update_preimage
5734                                                                                                         } else { false }
5735                                                                                                 ), "{:?}", update);
5736                                                                                                 true
5737                                                                                         } else { false }
5738                                                                                 },
5739                                                                                 // or the channel we'd unblock is already closed,
5740                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5741                                                                                         (funding_txo, monitor_update)
5742                                                                                 ) => {
5743                                                                                         if *funding_txo == next_channel_outpoint {
5744                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5745                                                                                                 assert!(matches!(
5746                                                                                                         monitor_update.updates[0],
5747                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5748                                                                                                 ));
5749                                                                                                 true
5750                                                                                         } else { false }
5751                                                                                 },
5752                                                                                 // or the monitor update has completed and will unblock
5753                                                                                 // immediately once we get going.
5754                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5755                                                                                         channel_id, ..
5756                                                                                 } =>
5757                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5758                                                                         }
5759                                                                 }), "{:?}", *background_events);
5760                                                         }
5761                                                         None
5762                                                 } else if definitely_duplicate {
5763                                                         if let Some(other_chan) = chan_to_release {
5764                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5765                                                                         downstream_counterparty_node_id: other_chan.0,
5766                                                                         downstream_funding_outpoint: other_chan.1,
5767                                                                         blocking_action: other_chan.2,
5768                                                                 })
5769                                                         } else { None }
5770                                                 } else {
5771                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5772                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5773                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5774                                                                 } else { None }
5775                                                         } else { None };
5776                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5777                                                                 event: events::Event::PaymentForwarded {
5778                                                                         fee_earned_msat,
5779                                                                         claim_from_onchain_tx: from_onchain,
5780                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5781                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5782                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5783                                                                 },
5784                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5785                                                         })
5786                                                 }
5787                                         });
5788                                 if let Err((pk, err)) = res {
5789                                         let result: Result<(), _> = Err(err);
5790                                         let _ = handle_error!(self, result, pk);
5791                                 }
5792                         },
5793                 }
5794         }
5795
5796         /// Gets the node_id held by this ChannelManager
5797         pub fn get_our_node_id(&self) -> PublicKey {
5798                 self.our_network_pubkey.clone()
5799         }
5800
5801         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5802                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5803                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5804                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5805
5806                 for action in actions.into_iter() {
5807                         match action {
5808                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5809                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5810                                         if let Some(ClaimingPayment {
5811                                                 amount_msat,
5812                                                 payment_purpose: purpose,
5813                                                 receiver_node_id,
5814                                                 htlcs,
5815                                                 sender_intended_value: sender_intended_total_msat,
5816                                         }) = payment {
5817                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5818                                                         payment_hash,
5819                                                         purpose,
5820                                                         amount_msat,
5821                                                         receiver_node_id: Some(receiver_node_id),
5822                                                         htlcs,
5823                                                         sender_intended_total_msat,
5824                                                 }, None));
5825                                         }
5826                                 },
5827                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5828                                         event, downstream_counterparty_and_funding_outpoint
5829                                 } => {
5830                                         self.pending_events.lock().unwrap().push_back((event, None));
5831                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5832                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5833                                         }
5834                                 },
5835                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5836                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5837                                 } => {
5838                                         self.handle_monitor_update_release(
5839                                                 downstream_counterparty_node_id,
5840                                                 downstream_funding_outpoint,
5841                                                 Some(blocking_action),
5842                                         );
5843                                 },
5844                         }
5845                 }
5846         }
5847
5848         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5849         /// update completion.
5850         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5851                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5852                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5853                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5854                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5855         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5856                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5857                 log_trace!(logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5858                         &channel.context.channel_id(),
5859                         if raa.is_some() { "an" } else { "no" },
5860                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5861                         if funding_broadcastable.is_some() { "" } else { "not " },
5862                         if channel_ready.is_some() { "sending" } else { "without" },
5863                         if announcement_sigs.is_some() { "sending" } else { "without" });
5864
5865                 let mut htlc_forwards = None;
5866
5867                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5868                 if !pending_forwards.is_empty() {
5869                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5870                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5871                 }
5872
5873                 if let Some(msg) = channel_ready {
5874                         send_channel_ready!(self, pending_msg_events, channel, msg);
5875                 }
5876                 if let Some(msg) = announcement_sigs {
5877                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5878                                 node_id: counterparty_node_id,
5879                                 msg,
5880                         });
5881                 }
5882
5883                 macro_rules! handle_cs { () => {
5884                         if let Some(update) = commitment_update {
5885                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5886                                         node_id: counterparty_node_id,
5887                                         updates: update,
5888                                 });
5889                         }
5890                 } }
5891                 macro_rules! handle_raa { () => {
5892                         if let Some(revoke_and_ack) = raa {
5893                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5894                                         node_id: counterparty_node_id,
5895                                         msg: revoke_and_ack,
5896                                 });
5897                         }
5898                 } }
5899                 match order {
5900                         RAACommitmentOrder::CommitmentFirst => {
5901                                 handle_cs!();
5902                                 handle_raa!();
5903                         },
5904                         RAACommitmentOrder::RevokeAndACKFirst => {
5905                                 handle_raa!();
5906                                 handle_cs!();
5907                         },
5908                 }
5909
5910                 if let Some(tx) = funding_broadcastable {
5911                         log_info!(logger, "Broadcasting funding transaction with txid {}", tx.txid());
5912                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5913                 }
5914
5915                 {
5916                         let mut pending_events = self.pending_events.lock().unwrap();
5917                         emit_channel_pending_event!(pending_events, channel);
5918                         emit_channel_ready_event!(pending_events, channel);
5919                 }
5920
5921                 htlc_forwards
5922         }
5923
5924         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5925                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5926
5927                 let counterparty_node_id = match counterparty_node_id {
5928                         Some(cp_id) => cp_id.clone(),
5929                         None => {
5930                                 // TODO: Once we can rely on the counterparty_node_id from the
5931                                 // monitor event, this and the outpoint_to_peer map should be removed.
5932                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
5933                                 match outpoint_to_peer.get(&funding_txo) {
5934                                         Some(cp_id) => cp_id.clone(),
5935                                         None => return,
5936                                 }
5937                         }
5938                 };
5939                 let per_peer_state = self.per_peer_state.read().unwrap();
5940                 let mut peer_state_lock;
5941                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5942                 if peer_state_mutex_opt.is_none() { return }
5943                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5944                 let peer_state = &mut *peer_state_lock;
5945                 let channel =
5946                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5947                                 chan
5948                         } else {
5949                                 let update_actions = peer_state.monitor_update_blocked_actions
5950                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5951                                 mem::drop(peer_state_lock);
5952                                 mem::drop(per_peer_state);
5953                                 self.handle_monitor_update_completion_actions(update_actions);
5954                                 return;
5955                         };
5956                 let remaining_in_flight =
5957                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5958                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5959                                 pending.len()
5960                         } else { 0 };
5961                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5962                 log_trace!(logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5963                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5964                         remaining_in_flight);
5965                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5966                         return;
5967                 }
5968                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5969         }
5970
5971         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5972         ///
5973         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5974         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5975         /// the channel.
5976         ///
5977         /// The `user_channel_id` parameter will be provided back in
5978         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5979         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5980         ///
5981         /// Note that this method will return an error and reject the channel, if it requires support
5982         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5983         /// used to accept such channels.
5984         ///
5985         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5986         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5987         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5988                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5989         }
5990
5991         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5992         /// it as confirmed immediately.
5993         ///
5994         /// The `user_channel_id` parameter will be provided back in
5995         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5996         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5997         ///
5998         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5999         /// and (if the counterparty agrees), enables forwarding of payments immediately.
6000         ///
6001         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
6002         /// transaction and blindly assumes that it will eventually confirm.
6003         ///
6004         /// If it does not confirm before we decide to close the channel, or if the funding transaction
6005         /// does not pay to the correct script the correct amount, *you will lose funds*.
6006         ///
6007         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
6008         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
6009         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
6010                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
6011         }
6012
6013         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
6014
6015                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(*temporary_channel_id));
6016                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6017
6018                 let peers_without_funded_channels =
6019                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
6020                 let per_peer_state = self.per_peer_state.read().unwrap();
6021                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6022                 .ok_or_else(|| {
6023                         let err_str = format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id);
6024                         log_error!(logger, "{}", err_str);
6025
6026                         APIError::ChannelUnavailable { err: err_str }
6027                 })?;
6028                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6029                 let peer_state = &mut *peer_state_lock;
6030                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
6031
6032                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
6033                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
6034                 // that we can delay allocating the SCID until after we're sure that the checks below will
6035                 // succeed.
6036                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
6037                         Some(unaccepted_channel) => {
6038                                 let best_block_height = self.best_block.read().unwrap().height();
6039                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6040                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
6041                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
6042                                         &self.logger, accept_0conf).map_err(|e| {
6043                                                 let err_str = e.to_string();
6044                                                 log_error!(logger, "{}", err_str);
6045
6046                                                 APIError::ChannelUnavailable { err: err_str }
6047                                         })
6048                                 }
6049                         _ => {
6050                                 let err_str = "No such channel awaiting to be accepted.".to_owned();
6051                                 log_error!(logger, "{}", err_str);
6052
6053                                 Err(APIError::APIMisuseError { err: err_str })
6054                         }
6055                 }?;
6056
6057                 if accept_0conf {
6058                         // This should have been correctly configured by the call to InboundV1Channel::new.
6059                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
6060                 } else if channel.context.get_channel_type().requires_zero_conf() {
6061                         let send_msg_err_event = events::MessageSendEvent::HandleError {
6062                                 node_id: channel.context.get_counterparty_node_id(),
6063                                 action: msgs::ErrorAction::SendErrorMessage{
6064                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
6065                                 }
6066                         };
6067                         peer_state.pending_msg_events.push(send_msg_err_event);
6068                         let err_str = "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned();
6069                         log_error!(logger, "{}", err_str);
6070
6071                         return Err(APIError::APIMisuseError { err: err_str });
6072                 } else {
6073                         // If this peer already has some channels, a new channel won't increase our number of peers
6074                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6075                         // channels per-peer we can accept channels from a peer with existing ones.
6076                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
6077                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
6078                                         node_id: channel.context.get_counterparty_node_id(),
6079                                         action: msgs::ErrorAction::SendErrorMessage{
6080                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
6081                                         }
6082                                 };
6083                                 peer_state.pending_msg_events.push(send_msg_err_event);
6084                                 let err_str = "Too many peers with unfunded channels, refusing to accept new ones".to_owned();
6085                                 log_error!(logger, "{}", err_str);
6086
6087                                 return Err(APIError::APIMisuseError { err: err_str });
6088                         }
6089                 }
6090
6091                 // Now that we know we have a channel, assign an outbound SCID alias.
6092                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6093                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6094
6095                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6096                         node_id: channel.context.get_counterparty_node_id(),
6097                         msg: channel.accept_inbound_channel(),
6098                 });
6099
6100                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
6101
6102                 Ok(())
6103         }
6104
6105         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
6106         /// or 0-conf channels.
6107         ///
6108         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6109         /// non-0-conf channels we have with the peer.
6110         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6111         where Filter: Fn(&PeerState<SP>) -> bool {
6112                 let mut peers_without_funded_channels = 0;
6113                 let best_block_height = self.best_block.read().unwrap().height();
6114                 {
6115                         let peer_state_lock = self.per_peer_state.read().unwrap();
6116                         for (_, peer_mtx) in peer_state_lock.iter() {
6117                                 let peer = peer_mtx.lock().unwrap();
6118                                 if !maybe_count_peer(&*peer) { continue; }
6119                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6120                                 if num_unfunded_channels == peer.total_channel_count() {
6121                                         peers_without_funded_channels += 1;
6122                                 }
6123                         }
6124                 }
6125                 return peers_without_funded_channels;
6126         }
6127
6128         fn unfunded_channel_count(
6129                 peer: &PeerState<SP>, best_block_height: u32
6130         ) -> usize {
6131                 let mut num_unfunded_channels = 0;
6132                 for (_, phase) in peer.channel_by_id.iter() {
6133                         match phase {
6134                                 ChannelPhase::Funded(chan) => {
6135                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6136                                         // which have not yet had any confirmations on-chain.
6137                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6138                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6139                                         {
6140                                                 num_unfunded_channels += 1;
6141                                         }
6142                                 },
6143                                 ChannelPhase::UnfundedInboundV1(chan) => {
6144                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6145                                                 num_unfunded_channels += 1;
6146                                         }
6147                                 },
6148                                 ChannelPhase::UnfundedOutboundV1(_) => {
6149                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6150                                         continue;
6151                                 }
6152                         }
6153                 }
6154                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6155         }
6156
6157         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6158                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6159                 // likely to be lost on restart!
6160                 if msg.chain_hash != self.chain_hash {
6161                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
6162                 }
6163
6164                 if !self.default_configuration.accept_inbound_channels {
6165                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6166                 }
6167
6168                 // Get the number of peers with channels, but without funded ones. We don't care too much
6169                 // about peers that never open a channel, so we filter by peers that have at least one
6170                 // channel, and then limit the number of those with unfunded channels.
6171                 let channeled_peers_without_funding =
6172                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6173
6174                 let per_peer_state = self.per_peer_state.read().unwrap();
6175                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6176                     .ok_or_else(|| {
6177                                 debug_assert!(false);
6178                                 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())
6179                         })?;
6180                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6181                 let peer_state = &mut *peer_state_lock;
6182
6183                 // If this peer already has some channels, a new channel won't increase our number of peers
6184                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6185                 // channels per-peer we can accept channels from a peer with existing ones.
6186                 if peer_state.total_channel_count() == 0 &&
6187                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6188                         !self.default_configuration.manually_accept_inbound_channels
6189                 {
6190                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6191                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6192                                 msg.temporary_channel_id.clone()));
6193                 }
6194
6195                 let best_block_height = self.best_block.read().unwrap().height();
6196                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6197                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6198                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6199                                 msg.temporary_channel_id.clone()));
6200                 }
6201
6202                 let channel_id = msg.temporary_channel_id;
6203                 let channel_exists = peer_state.has_channel(&channel_id);
6204                 if channel_exists {
6205                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
6206                 }
6207
6208                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6209                 if self.default_configuration.manually_accept_inbound_channels {
6210                         let channel_type = channel::channel_type_from_open_channel(
6211                                         &msg, &peer_state.latest_features, &self.channel_type_features()
6212                                 ).map_err(|e|
6213                                         MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id)
6214                                 )?;
6215                         let mut pending_events = self.pending_events.lock().unwrap();
6216                         pending_events.push_back((events::Event::OpenChannelRequest {
6217                                 temporary_channel_id: msg.temporary_channel_id.clone(),
6218                                 counterparty_node_id: counterparty_node_id.clone(),
6219                                 funding_satoshis: msg.funding_satoshis,
6220                                 push_msat: msg.push_msat,
6221                                 channel_type,
6222                         }, None));
6223                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6224                                 open_channel_msg: msg.clone(),
6225                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6226                         });
6227                         return Ok(());
6228                 }
6229
6230                 // Otherwise create the channel right now.
6231                 let mut random_bytes = [0u8; 16];
6232                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6233                 let user_channel_id = u128::from_be_bytes(random_bytes);
6234                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6235                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6236                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6237                 {
6238                         Err(e) => {
6239                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
6240                         },
6241                         Ok(res) => res
6242                 };
6243
6244                 let channel_type = channel.context.get_channel_type();
6245                 if channel_type.requires_zero_conf() {
6246                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6247                 }
6248                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6249                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
6250                 }
6251
6252                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6253                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6254
6255                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6256                         node_id: counterparty_node_id.clone(),
6257                         msg: channel.accept_inbound_channel(),
6258                 });
6259                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6260                 Ok(())
6261         }
6262
6263         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6264                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6265                 // likely to be lost on restart!
6266                 let (value, output_script, user_id) = {
6267                         let per_peer_state = self.per_peer_state.read().unwrap();
6268                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6269                                 .ok_or_else(|| {
6270                                         debug_assert!(false);
6271                                         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)
6272                                 })?;
6273                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6274                         let peer_state = &mut *peer_state_lock;
6275                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6276                                 hash_map::Entry::Occupied(mut phase) => {
6277                                         match phase.get_mut() {
6278                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6279                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6280                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6281                                                 },
6282                                                 _ => {
6283                                                         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));
6284                                                 }
6285                                         }
6286                                 },
6287                                 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))
6288                         }
6289                 };
6290                 let mut pending_events = self.pending_events.lock().unwrap();
6291                 pending_events.push_back((events::Event::FundingGenerationReady {
6292                         temporary_channel_id: msg.temporary_channel_id,
6293                         counterparty_node_id: *counterparty_node_id,
6294                         channel_value_satoshis: value,
6295                         output_script,
6296                         user_channel_id: user_id,
6297                 }, None));
6298                 Ok(())
6299         }
6300
6301         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6302                 let best_block = *self.best_block.read().unwrap();
6303
6304                 let per_peer_state = self.per_peer_state.read().unwrap();
6305                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6306                         .ok_or_else(|| {
6307                                 debug_assert!(false);
6308                                 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)
6309                         })?;
6310
6311                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6312                 let peer_state = &mut *peer_state_lock;
6313                 let (mut chan, funding_msg_opt, monitor) =
6314                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6315                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6316                                         let logger = WithChannelContext::from(&self.logger, &inbound_chan.context);
6317                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &&logger) {
6318                                                 Ok(res) => res,
6319                                                 Err((inbound_chan, err)) => {
6320                                                         // We've already removed this inbound channel from the map in `PeerState`
6321                                                         // above so at this point we just need to clean up any lingering entries
6322                                                         // concerning this channel as it is safe to do so.
6323                                                         debug_assert!(matches!(err, ChannelError::Close(_)));
6324                                                         // Really we should be returning the channel_id the peer expects based
6325                                                         // on their funding info here, but they're horribly confused anyway, so
6326                                                         // there's not a lot we can do to save them.
6327                                                         return Err(convert_chan_phase_err!(self, err, &mut ChannelPhase::UnfundedInboundV1(inbound_chan), &msg.temporary_channel_id).1);
6328                                                 },
6329                                         }
6330                                 },
6331                                 Some(mut phase) => {
6332                                         let err_msg = format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id);
6333                                         let err = ChannelError::Close(err_msg);
6334                                         return Err(convert_chan_phase_err!(self, err, &mut phase, &msg.temporary_channel_id).1);
6335                                 },
6336                                 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))
6337                         };
6338
6339                 let funded_channel_id = chan.context.channel_id();
6340
6341                 macro_rules! fail_chan { ($err: expr) => { {
6342                         // Note that at this point we've filled in the funding outpoint on our
6343                         // channel, but its actually in conflict with another channel. Thus, if
6344                         // we call `convert_chan_phase_err` immediately (thus calling
6345                         // `update_maps_on_chan_removal`), we'll remove the existing channel
6346                         // from `outpoint_to_peer`. Thus, we must first unset the funding outpoint
6347                         // on the channel.
6348                         let err = ChannelError::Close($err.to_owned());
6349                         chan.unset_funding_info(msg.temporary_channel_id);
6350                         return Err(convert_chan_phase_err!(self, err, chan, &funded_channel_id, UNFUNDED_CHANNEL).1);
6351                 } } }
6352
6353                 match peer_state.channel_by_id.entry(funded_channel_id) {
6354                         hash_map::Entry::Occupied(_) => {
6355                                 fail_chan!("Already had channel with the new channel_id");
6356                         },
6357                         hash_map::Entry::Vacant(e) => {
6358                                 let mut outpoint_to_peer_lock = self.outpoint_to_peer.lock().unwrap();
6359                                 match outpoint_to_peer_lock.entry(monitor.get_funding_txo().0) {
6360                                         hash_map::Entry::Occupied(_) => {
6361                                                 fail_chan!("The funding_created message had the same funding_txid as an existing channel - funding is not possible");
6362                                         },
6363                                         hash_map::Entry::Vacant(i_e) => {
6364                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6365                                                 if let Ok(persist_state) = monitor_res {
6366                                                         i_e.insert(chan.context.get_counterparty_node_id());
6367                                                         mem::drop(outpoint_to_peer_lock);
6368
6369                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6370                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6371                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6372                                                         // until we have persisted our monitor.
6373                                                         if let Some(msg) = funding_msg_opt {
6374                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6375                                                                         node_id: counterparty_node_id.clone(),
6376                                                                         msg,
6377                                                                 });
6378                                                         }
6379
6380                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6381                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6382                                                                         per_peer_state, chan, INITIAL_MONITOR);
6383                                                         } else {
6384                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6385                                                         }
6386                                                         Ok(())
6387                                                 } else {
6388                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6389                                                         log_error!(logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6390                                                         fail_chan!("Duplicate funding outpoint");
6391                                                 }
6392                                         }
6393                                 }
6394                         }
6395                 }
6396         }
6397
6398         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6399                 let best_block = *self.best_block.read().unwrap();
6400                 let per_peer_state = self.per_peer_state.read().unwrap();
6401                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6402                         .ok_or_else(|| {
6403                                 debug_assert!(false);
6404                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6405                         })?;
6406
6407                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6408                 let peer_state = &mut *peer_state_lock;
6409                 match peer_state.channel_by_id.entry(msg.channel_id) {
6410                         hash_map::Entry::Occupied(chan_phase_entry) => {
6411                                 if matches!(chan_phase_entry.get(), ChannelPhase::UnfundedOutboundV1(_)) {
6412                                         let chan = if let ChannelPhase::UnfundedOutboundV1(chan) = chan_phase_entry.remove() { chan } else { unreachable!() };
6413                                         let logger = WithContext::from(
6414                                                 &self.logger,
6415                                                 Some(chan.context.get_counterparty_node_id()),
6416                                                 Some(chan.context.channel_id())
6417                                         );
6418                                         let res =
6419                                                 chan.funding_signed(&msg, best_block, &self.signer_provider, &&logger);
6420                                         match res {
6421                                                 Ok((mut chan, monitor)) => {
6422                                                         if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6423                                                                 // We really should be able to insert here without doing a second
6424                                                                 // lookup, but sadly rust stdlib doesn't currently allow keeping
6425                                                                 // the original Entry around with the value removed.
6426                                                                 let mut chan = peer_state.channel_by_id.entry(msg.channel_id).or_insert(ChannelPhase::Funded(chan));
6427                                                                 if let ChannelPhase::Funded(ref mut chan) = &mut chan {
6428                                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6429                                                                 } else { unreachable!(); }
6430                                                                 Ok(())
6431                                                         } else {
6432                                                                 let e = ChannelError::Close("Channel funding outpoint was a duplicate".to_owned());
6433                                                                 // We weren't able to watch the channel to begin with, so no
6434                                                                 // updates should be made on it. Previously, full_stack_target
6435                                                                 // found an (unreachable) panic when the monitor update contained
6436                                                                 // within `shutdown_finish` was applied.
6437                                                                 chan.unset_funding_info(msg.channel_id);
6438                                                                 return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::Funded(chan), &msg.channel_id).1);
6439                                                         }
6440                                                 },
6441                                                 Err((chan, e)) => {
6442                                                         debug_assert!(matches!(e, ChannelError::Close(_)),
6443                                                                 "We don't have a channel anymore, so the error better have expected close");
6444                                                         // We've already removed this outbound channel from the map in
6445                                                         // `PeerState` above so at this point we just need to clean up any
6446                                                         // lingering entries concerning this channel as it is safe to do so.
6447                                                         return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::UnfundedOutboundV1(chan), &msg.channel_id).1);
6448                                                 }
6449                                         }
6450                                 } else {
6451                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6452                                 }
6453                         },
6454                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6455                 }
6456         }
6457
6458         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6459                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6460                 // closing a channel), so any changes are likely to be lost on restart!
6461                 let per_peer_state = self.per_peer_state.read().unwrap();
6462                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6463                         .ok_or_else(|| {
6464                                 debug_assert!(false);
6465                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6466                         })?;
6467                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6468                 let peer_state = &mut *peer_state_lock;
6469                 match peer_state.channel_by_id.entry(msg.channel_id) {
6470                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6471                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6472                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6473                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6474                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &&logger), chan_phase_entry);
6475                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6476                                                 log_trace!(logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6477                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6478                                                         node_id: counterparty_node_id.clone(),
6479                                                         msg: announcement_sigs,
6480                                                 });
6481                                         } else if chan.context.is_usable() {
6482                                                 // If we're sending an announcement_signatures, we'll send the (public)
6483                                                 // channel_update after sending a channel_announcement when we receive our
6484                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6485                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6486                                                 // announcement_signatures.
6487                                                 log_trace!(logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6488                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6489                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6490                                                                 node_id: counterparty_node_id.clone(),
6491                                                                 msg,
6492                                                         });
6493                                                 }
6494                                         }
6495
6496                                         {
6497                                                 let mut pending_events = self.pending_events.lock().unwrap();
6498                                                 emit_channel_ready_event!(pending_events, chan);
6499                                         }
6500
6501                                         Ok(())
6502                                 } else {
6503                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6504                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6505                                 }
6506                         },
6507                         hash_map::Entry::Vacant(_) => {
6508                                 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))
6509                         }
6510                 }
6511         }
6512
6513         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6514                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6515                 let mut finish_shutdown = None;
6516                 {
6517                         let per_peer_state = self.per_peer_state.read().unwrap();
6518                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6519                                 .ok_or_else(|| {
6520                                         debug_assert!(false);
6521                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6522                                 })?;
6523                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6524                         let peer_state = &mut *peer_state_lock;
6525                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6526                                 let phase = chan_phase_entry.get_mut();
6527                                 match phase {
6528                                         ChannelPhase::Funded(chan) => {
6529                                                 if !chan.received_shutdown() {
6530                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6531                                                         log_info!(logger, "Received a shutdown message from our counterparty for channel {}{}.",
6532                                                                 msg.channel_id,
6533                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6534                                                 }
6535
6536                                                 let funding_txo_opt = chan.context.get_funding_txo();
6537                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6538                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6539                                                 dropped_htlcs = htlcs;
6540
6541                                                 if let Some(msg) = shutdown {
6542                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6543                                                         // here as we don't need the monitor update to complete until we send a
6544                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6545                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6546                                                                 node_id: *counterparty_node_id,
6547                                                                 msg,
6548                                                         });
6549                                                 }
6550                                                 // Update the monitor with the shutdown script if necessary.
6551                                                 if let Some(monitor_update) = monitor_update_opt {
6552                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6553                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6554                                                 }
6555                                         },
6556                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6557                                                 let context = phase.context_mut();
6558                                                 let logger = WithChannelContext::from(&self.logger, context);
6559                                                 log_error!(logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6560                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6561                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false, ClosureReason::CounterpartyCoopClosedUnfundedChannel));
6562                                         },
6563                                 }
6564                         } else {
6565                                 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))
6566                         }
6567                 }
6568                 for htlc_source in dropped_htlcs.drain(..) {
6569                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6570                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6571                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6572                 }
6573                 if let Some(shutdown_res) = finish_shutdown {
6574                         self.finish_close_channel(shutdown_res);
6575                 }
6576
6577                 Ok(())
6578         }
6579
6580         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6581                 let per_peer_state = self.per_peer_state.read().unwrap();
6582                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6583                         .ok_or_else(|| {
6584                                 debug_assert!(false);
6585                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6586                         })?;
6587                 let (tx, chan_option, shutdown_result) = {
6588                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6589                         let peer_state = &mut *peer_state_lock;
6590                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6591                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6592                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6593                                                 let (closing_signed, tx, shutdown_result) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6594                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
6595                                                 if let Some(msg) = closing_signed {
6596                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6597                                                                 node_id: counterparty_node_id.clone(),
6598                                                                 msg,
6599                                                         });
6600                                                 }
6601                                                 if tx.is_some() {
6602                                                         // We're done with this channel, we've got a signed closing transaction and
6603                                                         // will send the closing_signed back to the remote peer upon return. This
6604                                                         // also implies there are no pending HTLCs left on the channel, so we can
6605                                                         // fully delete it from tracking (the channel monitor is still around to
6606                                                         // watch for old state broadcasts)!
6607                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)), shutdown_result)
6608                                                 } else { (tx, None, shutdown_result) }
6609                                         } else {
6610                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6611                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6612                                         }
6613                                 },
6614                                 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))
6615                         }
6616                 };
6617                 if let Some(broadcast_tx) = tx {
6618                         let channel_id = chan_option.as_ref().map(|channel| channel.context().channel_id());
6619                         log_info!(WithContext::from(&self.logger, Some(*counterparty_node_id), channel_id), "Broadcasting {}", log_tx!(broadcast_tx));
6620                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6621                 }
6622                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6623                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6624                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6625                                 let peer_state = &mut *peer_state_lock;
6626                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6627                                         msg: update
6628                                 });
6629                         }
6630                 }
6631                 mem::drop(per_peer_state);
6632                 if let Some(shutdown_result) = shutdown_result {
6633                         self.finish_close_channel(shutdown_result);
6634                 }
6635                 Ok(())
6636         }
6637
6638         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6639                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6640                 //determine the state of the payment based on our response/if we forward anything/the time
6641                 //we take to respond. We should take care to avoid allowing such an attack.
6642                 //
6643                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6644                 //us repeatedly garbled in different ways, and compare our error messages, which are
6645                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6646                 //but we should prevent it anyway.
6647
6648                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6649                 // closing a channel), so any changes are likely to be lost on restart!
6650
6651                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg, counterparty_node_id);
6652                 let per_peer_state = self.per_peer_state.read().unwrap();
6653                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6654                         .ok_or_else(|| {
6655                                 debug_assert!(false);
6656                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6657                         })?;
6658                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6659                 let peer_state = &mut *peer_state_lock;
6660                 match peer_state.channel_by_id.entry(msg.channel_id) {
6661                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6662                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6663                                         let pending_forward_info = match decoded_hop_res {
6664                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6665                                                         self.construct_pending_htlc_status(
6666                                                                 msg, counterparty_node_id, shared_secret, next_hop,
6667                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt,
6668                                                         ),
6669                                                 Err(e) => PendingHTLCStatus::Fail(e)
6670                                         };
6671                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6672                                                 if msg.blinding_point.is_some() {
6673                                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
6674                                                                         msgs::UpdateFailMalformedHTLC {
6675                                                                                 channel_id: msg.channel_id,
6676                                                                                 htlc_id: msg.htlc_id,
6677                                                                                 sha256_of_onion: [0; 32],
6678                                                                                 failure_code: INVALID_ONION_BLINDING,
6679                                                                         }
6680                                                         ))
6681                                                 }
6682                                                 // If the update_add is completely bogus, the call will Err and we will close,
6683                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6684                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6685                                                 match pending_forward_info {
6686                                                         PendingHTLCStatus::Forward(PendingHTLCInfo {
6687                                                                 ref incoming_shared_secret, ref routing, ..
6688                                                         }) => {
6689                                                                 let reason = if routing.blinded_failure().is_some() {
6690                                                                         HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32])
6691                                                                 } else if (error_code & 0x1000) != 0 {
6692                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6693                                                                         HTLCFailReason::reason(real_code, error_data)
6694                                                                 } else {
6695                                                                         HTLCFailReason::from_failure_code(error_code)
6696                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6697                                                                 let msg = msgs::UpdateFailHTLC {
6698                                                                         channel_id: msg.channel_id,
6699                                                                         htlc_id: msg.htlc_id,
6700                                                                         reason
6701                                                                 };
6702                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6703                                                         },
6704                                                         _ => pending_forward_info
6705                                                 }
6706                                         };
6707                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6708                                         try_chan_phase_entry!(self, chan.update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &&logger), chan_phase_entry);
6709                                 } else {
6710                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6711                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6712                                 }
6713                         },
6714                         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))
6715                 }
6716                 Ok(())
6717         }
6718
6719         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6720                 let funding_txo;
6721                 let (htlc_source, forwarded_htlc_value) = {
6722                         let per_peer_state = self.per_peer_state.read().unwrap();
6723                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6724                                 .ok_or_else(|| {
6725                                         debug_assert!(false);
6726                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6727                                 })?;
6728                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6729                         let peer_state = &mut *peer_state_lock;
6730                         match peer_state.channel_by_id.entry(msg.channel_id) {
6731                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6732                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6733                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6734                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6735                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6736                                                         log_trace!(logger,
6737                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6738                                                                 msg.channel_id);
6739                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6740                                                                 .or_insert_with(Vec::new)
6741                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6742                                                 }
6743                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6744                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6745                                                 // We do this instead in the `claim_funds_internal` by attaching a
6746                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6747                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6748                                                 // process the RAA as messages are processed from single peers serially.
6749                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6750                                                 res
6751                                         } else {
6752                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6753                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6754                                         }
6755                                 },
6756                                 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))
6757                         }
6758                 };
6759                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6760                 Ok(())
6761         }
6762
6763         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6764                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6765                 // closing a channel), so any changes are likely to be lost on restart!
6766                 let per_peer_state = self.per_peer_state.read().unwrap();
6767                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6768                         .ok_or_else(|| {
6769                                 debug_assert!(false);
6770                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6771                         })?;
6772                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6773                 let peer_state = &mut *peer_state_lock;
6774                 match peer_state.channel_by_id.entry(msg.channel_id) {
6775                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6776                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6777                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6778                                 } else {
6779                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6780                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6781                                 }
6782                         },
6783                         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))
6784                 }
6785                 Ok(())
6786         }
6787
6788         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6789                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6790                 // closing a channel), so any changes are likely to be lost on restart!
6791                 let per_peer_state = self.per_peer_state.read().unwrap();
6792                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6793                         .ok_or_else(|| {
6794                                 debug_assert!(false);
6795                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6796                         })?;
6797                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6798                 let peer_state = &mut *peer_state_lock;
6799                 match peer_state.channel_by_id.entry(msg.channel_id) {
6800                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6801                                 if (msg.failure_code & 0x8000) == 0 {
6802                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6803                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6804                                 }
6805                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6806                                         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);
6807                                 } else {
6808                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6809                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6810                                 }
6811                                 Ok(())
6812                         },
6813                         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))
6814                 }
6815         }
6816
6817         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6818                 let per_peer_state = self.per_peer_state.read().unwrap();
6819                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6820                         .ok_or_else(|| {
6821                                 debug_assert!(false);
6822                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6823                         })?;
6824                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6825                 let peer_state = &mut *peer_state_lock;
6826                 match peer_state.channel_by_id.entry(msg.channel_id) {
6827                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6828                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6829                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6830                                         let funding_txo = chan.context.get_funding_txo();
6831                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &&logger), chan_phase_entry);
6832                                         if let Some(monitor_update) = monitor_update_opt {
6833                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6834                                                         peer_state, per_peer_state, chan);
6835                                         }
6836                                         Ok(())
6837                                 } else {
6838                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6839                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6840                                 }
6841                         },
6842                         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))
6843                 }
6844         }
6845
6846         #[inline]
6847         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6848                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6849                         let mut push_forward_event = false;
6850                         let mut new_intercept_events = VecDeque::new();
6851                         let mut failed_intercept_forwards = Vec::new();
6852                         if !pending_forwards.is_empty() {
6853                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6854                                         let scid = match forward_info.routing {
6855                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6856                                                 PendingHTLCRouting::Receive { .. } => 0,
6857                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6858                                         };
6859                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6860                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6861
6862                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6863                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6864                                         match forward_htlcs.entry(scid) {
6865                                                 hash_map::Entry::Occupied(mut entry) => {
6866                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6867                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6868                                                 },
6869                                                 hash_map::Entry::Vacant(entry) => {
6870                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6871                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6872                                                         {
6873                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).to_byte_array());
6874                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6875                                                                 match pending_intercepts.entry(intercept_id) {
6876                                                                         hash_map::Entry::Vacant(entry) => {
6877                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6878                                                                                         requested_next_hop_scid: scid,
6879                                                                                         payment_hash: forward_info.payment_hash,
6880                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6881                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6882                                                                                         intercept_id
6883                                                                                 }, None));
6884                                                                                 entry.insert(PendingAddHTLCInfo {
6885                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6886                                                                         },
6887                                                                         hash_map::Entry::Occupied(_) => {
6888                                                                                 let logger = WithContext::from(&self.logger, None, Some(prev_funding_outpoint.to_channel_id()));
6889                                                                                 log_info!(logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6890                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6891                                                                                         short_channel_id: prev_short_channel_id,
6892                                                                                         user_channel_id: Some(prev_user_channel_id),
6893                                                                                         outpoint: prev_funding_outpoint,
6894                                                                                         htlc_id: prev_htlc_id,
6895                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6896                                                                                         phantom_shared_secret: None,
6897                                                                                         blinded_failure: forward_info.routing.blinded_failure(),
6898                                                                                 });
6899
6900                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6901                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6902                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6903                                                                                 ));
6904                                                                         }
6905                                                                 }
6906                                                         } else {
6907                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6908                                                                 // payments are being processed.
6909                                                                 if forward_htlcs_empty {
6910                                                                         push_forward_event = true;
6911                                                                 }
6912                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6913                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6914                                                         }
6915                                                 }
6916                                         }
6917                                 }
6918                         }
6919
6920                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6921                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6922                         }
6923
6924                         if !new_intercept_events.is_empty() {
6925                                 let mut events = self.pending_events.lock().unwrap();
6926                                 events.append(&mut new_intercept_events);
6927                         }
6928                         if push_forward_event { self.push_pending_forwards_ev() }
6929                 }
6930         }
6931
6932         fn push_pending_forwards_ev(&self) {
6933                 let mut pending_events = self.pending_events.lock().unwrap();
6934                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6935                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6936                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6937                 ).count();
6938                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6939                 // events is done in batches and they are not removed until we're done processing each
6940                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6941                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6942                 // payments will need an additional forwarding event before being claimed to make them look
6943                 // real by taking more time.
6944                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6945                         pending_events.push_back((Event::PendingHTLCsForwardable {
6946                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6947                         }, None));
6948                 }
6949         }
6950
6951         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6952         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6953         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6954         /// the [`ChannelMonitorUpdate`] in question.
6955         fn raa_monitor_updates_held(&self,
6956                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6957                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6958         ) -> bool {
6959                 actions_blocking_raa_monitor_updates
6960                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6961                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6962                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6963                                 channel_funding_outpoint,
6964                                 counterparty_node_id,
6965                         })
6966                 })
6967         }
6968
6969         #[cfg(any(test, feature = "_test_utils"))]
6970         pub(crate) fn test_raa_monitor_updates_held(&self,
6971                 counterparty_node_id: PublicKey, channel_id: ChannelId
6972         ) -> bool {
6973                 let per_peer_state = self.per_peer_state.read().unwrap();
6974                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6975                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6976                         let peer_state = &mut *peer_state_lck;
6977
6978                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6979                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6980                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6981                         }
6982                 }
6983                 false
6984         }
6985
6986         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6987                 let htlcs_to_fail = {
6988                         let per_peer_state = self.per_peer_state.read().unwrap();
6989                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6990                                 .ok_or_else(|| {
6991                                         debug_assert!(false);
6992                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6993                                 }).map(|mtx| mtx.lock().unwrap())?;
6994                         let peer_state = &mut *peer_state_lock;
6995                         match peer_state.channel_by_id.entry(msg.channel_id) {
6996                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6997                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6998                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
6999                                                 let funding_txo_opt = chan.context.get_funding_txo();
7000                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
7001                                                         self.raa_monitor_updates_held(
7002                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
7003                                                                 *counterparty_node_id)
7004                                                 } else { false };
7005                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
7006                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &&logger, mon_update_blocked), chan_phase_entry);
7007                                                 if let Some(monitor_update) = monitor_update_opt {
7008                                                         let funding_txo = funding_txo_opt
7009                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
7010                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
7011                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7012                                                 }
7013                                                 htlcs_to_fail
7014                                         } else {
7015                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7016                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
7017                                         }
7018                                 },
7019                                 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))
7020                         }
7021                 };
7022                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
7023                 Ok(())
7024         }
7025
7026         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
7027                 let per_peer_state = self.per_peer_state.read().unwrap();
7028                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7029                         .ok_or_else(|| {
7030                                 debug_assert!(false);
7031                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7032                         })?;
7033                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7034                 let peer_state = &mut *peer_state_lock;
7035                 match peer_state.channel_by_id.entry(msg.channel_id) {
7036                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7037                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7038                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7039                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &&logger), chan_phase_entry);
7040                                 } else {
7041                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7042                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
7043                                 }
7044                         },
7045                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
7046                 }
7047                 Ok(())
7048         }
7049
7050         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
7051                 let per_peer_state = self.per_peer_state.read().unwrap();
7052                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7053                         .ok_or_else(|| {
7054                                 debug_assert!(false);
7055                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7056                         })?;
7057                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7058                 let peer_state = &mut *peer_state_lock;
7059                 match peer_state.channel_by_id.entry(msg.channel_id) {
7060                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7061                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7062                                         if !chan.context.is_usable() {
7063                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
7064                                         }
7065
7066                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7067                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
7068                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
7069                                                         msg, &self.default_configuration
7070                                                 ), chan_phase_entry),
7071                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7072                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7073                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
7074                                         });
7075                                 } else {
7076                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7077                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
7078                                 }
7079                         },
7080                         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))
7081                 }
7082                 Ok(())
7083         }
7084
7085         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
7086         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
7087                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
7088                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
7089                         None => {
7090                                 // It's not a local channel
7091                                 return Ok(NotifyOption::SkipPersistNoEvents)
7092                         }
7093                 };
7094                 let per_peer_state = self.per_peer_state.read().unwrap();
7095                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
7096                 if peer_state_mutex_opt.is_none() {
7097                         return Ok(NotifyOption::SkipPersistNoEvents)
7098                 }
7099                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7100                 let peer_state = &mut *peer_state_lock;
7101                 match peer_state.channel_by_id.entry(chan_id) {
7102                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7103                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7104                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
7105                                                 if chan.context.should_announce() {
7106                                                         // If the announcement is about a channel of ours which is public, some
7107                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
7108                                                         // a scary-looking error message and return Ok instead.
7109                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7110                                                 }
7111                                                 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));
7112                                         }
7113                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
7114                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
7115                                         if were_node_one == msg_from_node_one {
7116                                                 return Ok(NotifyOption::SkipPersistNoEvents);
7117                                         } else {
7118                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
7119                                                 log_debug!(logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
7120                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
7121                                                 // If nothing changed after applying their update, we don't need to bother
7122                                                 // persisting.
7123                                                 if !did_change {
7124                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7125                                                 }
7126                                         }
7127                                 } else {
7128                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7129                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
7130                                 }
7131                         },
7132                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
7133                 }
7134                 Ok(NotifyOption::DoPersist)
7135         }
7136
7137         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
7138                 let htlc_forwards;
7139                 let need_lnd_workaround = {
7140                         let per_peer_state = self.per_peer_state.read().unwrap();
7141
7142                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7143                                 .ok_or_else(|| {
7144                                         debug_assert!(false);
7145                                         MsgHandleErrInternal::send_err_msg_no_close(
7146                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
7147                                                 msg.channel_id
7148                                         )
7149                                 })?;
7150                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
7151                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7152                         let peer_state = &mut *peer_state_lock;
7153                         match peer_state.channel_by_id.entry(msg.channel_id) {
7154                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
7155                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7156                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
7157                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
7158                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
7159                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
7160                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
7161                                                         msg, &&logger, &self.node_signer, self.chain_hash,
7162                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
7163                                                 let mut channel_update = None;
7164                                                 if let Some(msg) = responses.shutdown_msg {
7165                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
7166                                                                 node_id: counterparty_node_id.clone(),
7167                                                                 msg,
7168                                                         });
7169                                                 } else if chan.context.is_usable() {
7170                                                         // If the channel is in a usable state (ie the channel is not being shut
7171                                                         // down), send a unicast channel_update to our counterparty to make sure
7172                                                         // they have the latest channel parameters.
7173                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
7174                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
7175                                                                         node_id: chan.context.get_counterparty_node_id(),
7176                                                                         msg,
7177                                                                 });
7178                                                         }
7179                                                 }
7180                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7181                                                 htlc_forwards = self.handle_channel_resumption(
7182                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7183                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7184                                                 if let Some(upd) = channel_update {
7185                                                         peer_state.pending_msg_events.push(upd);
7186                                                 }
7187                                                 need_lnd_workaround
7188                                         } else {
7189                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7190                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7191                                         }
7192                                 },
7193                                 hash_map::Entry::Vacant(_) => {
7194                                         log_debug!(logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7195                                                 msg.channel_id);
7196                                         // Unfortunately, lnd doesn't force close on errors
7197                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7198                                         // One of the few ways to get an lnd counterparty to force close is by
7199                                         // replicating what they do when restoring static channel backups (SCBs). They
7200                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7201                                         // invalid `your_last_per_commitment_secret`.
7202                                         //
7203                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7204                                         // can assume it's likely the channel closed from our point of view, but it
7205                                         // remains open on the counterparty's side. By sending this bogus
7206                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7207                                         // force close broadcasting their latest state. If the closing transaction from
7208                                         // our point of view remains unconfirmed, it'll enter a race with the
7209                                         // counterparty's to-be-broadcast latest commitment transaction.
7210                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7211                                                 node_id: *counterparty_node_id,
7212                                                 msg: msgs::ChannelReestablish {
7213                                                         channel_id: msg.channel_id,
7214                                                         next_local_commitment_number: 0,
7215                                                         next_remote_commitment_number: 0,
7216                                                         your_last_per_commitment_secret: [1u8; 32],
7217                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7218                                                         next_funding_txid: None,
7219                                                 },
7220                                         });
7221                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7222                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7223                                                         counterparty_node_id), msg.channel_id)
7224                                         )
7225                                 }
7226                         }
7227                 };
7228
7229                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7230                 if let Some(forwards) = htlc_forwards {
7231                         self.forward_htlcs(&mut [forwards][..]);
7232                         persist = NotifyOption::DoPersist;
7233                 }
7234
7235                 if let Some(channel_ready_msg) = need_lnd_workaround {
7236                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7237                 }
7238                 Ok(persist)
7239         }
7240
7241         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7242         fn process_pending_monitor_events(&self) -> bool {
7243                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7244
7245                 let mut failed_channels = Vec::new();
7246                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7247                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7248                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7249                         for monitor_event in monitor_events.drain(..) {
7250                                 match monitor_event {
7251                                         MonitorEvent::HTLCEvent(htlc_update) => {
7252                                                 let logger = WithContext::from(&self.logger, counterparty_node_id, Some(funding_outpoint.to_channel_id()));
7253                                                 if let Some(preimage) = htlc_update.payment_preimage {
7254                                                         log_trace!(logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7255                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
7256                                                 } else {
7257                                                         log_trace!(logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7258                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
7259                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7260                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7261                                                 }
7262                                         },
7263                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
7264                                                 let counterparty_node_id_opt = match counterparty_node_id {
7265                                                         Some(cp_id) => Some(cp_id),
7266                                                         None => {
7267                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7268                                                                 // monitor event, this and the outpoint_to_peer map should be removed.
7269                                                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
7270                                                                 outpoint_to_peer.get(&funding_outpoint).cloned()
7271                                                         }
7272                                                 };
7273                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7274                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7275                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7276                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7277                                                                 let peer_state = &mut *peer_state_lock;
7278                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7279                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
7280                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7281                                                                                 failed_channels.push(chan.context.force_shutdown(false, ClosureReason::HolderForceClosed));
7282                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7283                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7284                                                                                                 msg: update
7285                                                                                         });
7286                                                                                 }
7287                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7288                                                                                         node_id: chan.context.get_counterparty_node_id(),
7289                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7290                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7291                                                                                         },
7292                                                                                 });
7293                                                                         }
7294                                                                 }
7295                                                         }
7296                                                 }
7297                                         },
7298                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
7299                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
7300                                         },
7301                                 }
7302                         }
7303                 }
7304
7305                 for failure in failed_channels.drain(..) {
7306                         self.finish_close_channel(failure);
7307                 }
7308
7309                 has_pending_monitor_events
7310         }
7311
7312         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7313         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7314         /// update events as a separate process method here.
7315         #[cfg(fuzzing)]
7316         pub fn process_monitor_events(&self) {
7317                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7318                 self.process_pending_monitor_events();
7319         }
7320
7321         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7322         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7323         /// update was applied.
7324         fn check_free_holding_cells(&self) -> bool {
7325                 let mut has_monitor_update = false;
7326                 let mut failed_htlcs = Vec::new();
7327
7328                 // Walk our list of channels and find any that need to update. Note that when we do find an
7329                 // update, if it includes actions that must be taken afterwards, we have to drop the
7330                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7331                 // manage to go through all our peers without finding a single channel to update.
7332                 'peer_loop: loop {
7333                         let per_peer_state = self.per_peer_state.read().unwrap();
7334                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7335                                 'chan_loop: loop {
7336                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7337                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7338                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7339                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7340                                         ) {
7341                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7342                                                 let funding_txo = chan.context.get_funding_txo();
7343                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7344                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &&WithChannelContext::from(&self.logger, &chan.context));
7345                                                 if !holding_cell_failed_htlcs.is_empty() {
7346                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7347                                                 }
7348                                                 if let Some(monitor_update) = monitor_opt {
7349                                                         has_monitor_update = true;
7350
7351                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7352                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7353                                                         continue 'peer_loop;
7354                                                 }
7355                                         }
7356                                         break 'chan_loop;
7357                                 }
7358                         }
7359                         break 'peer_loop;
7360                 }
7361
7362                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7363                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7364                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7365                 }
7366
7367                 has_update
7368         }
7369
7370         /// When a call to a [`ChannelSigner`] method returns an error, this indicates that the signer
7371         /// is (temporarily) unavailable, and the operation should be retried later.
7372         ///
7373         /// This method allows for that retry - either checking for any signer-pending messages to be
7374         /// attempted in every channel, or in the specifically provided channel.
7375         ///
7376         /// [`ChannelSigner`]: crate::sign::ChannelSigner
7377         #[cfg(async_signing)]
7378         pub fn signer_unblocked(&self, channel_opt: Option<(PublicKey, ChannelId)>) {
7379                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7380
7381                 let unblock_chan = |phase: &mut ChannelPhase<SP>, pending_msg_events: &mut Vec<MessageSendEvent>| {
7382                         let node_id = phase.context().get_counterparty_node_id();
7383                         match phase {
7384                                 ChannelPhase::Funded(chan) => {
7385                                         let msgs = chan.signer_maybe_unblocked(&self.logger);
7386                                         if let Some(updates) = msgs.commitment_update {
7387                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
7388                                                         node_id,
7389                                                         updates,
7390                                                 });
7391                                         }
7392                                         if let Some(msg) = msgs.funding_signed {
7393                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
7394                                                         node_id,
7395                                                         msg,
7396                                                 });
7397                                         }
7398                                         if let Some(msg) = msgs.channel_ready {
7399                                                 send_channel_ready!(self, pending_msg_events, chan, msg);
7400                                         }
7401                                 }
7402                                 ChannelPhase::UnfundedOutboundV1(chan) => {
7403                                         if let Some(msg) = chan.signer_maybe_unblocked(&self.logger) {
7404                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
7405                                                         node_id,
7406                                                         msg,
7407                                                 });
7408                                         }
7409                                 }
7410                                 ChannelPhase::UnfundedInboundV1(_) => {},
7411                         }
7412                 };
7413
7414                 let per_peer_state = self.per_peer_state.read().unwrap();
7415                 if let Some((counterparty_node_id, channel_id)) = channel_opt {
7416                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7417                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7418                                 let peer_state = &mut *peer_state_lock;
7419                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&channel_id) {
7420                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7421                                 }
7422                         }
7423                 } else {
7424                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7425                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7426                                 let peer_state = &mut *peer_state_lock;
7427                                 for (_, chan) in peer_state.channel_by_id.iter_mut() {
7428                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7429                                 }
7430                         }
7431                 }
7432         }
7433
7434         /// Check whether any channels have finished removing all pending updates after a shutdown
7435         /// exchange and can now send a closing_signed.
7436         /// Returns whether any closing_signed messages were generated.
7437         fn maybe_generate_initial_closing_signed(&self) -> bool {
7438                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7439                 let mut has_update = false;
7440                 let mut shutdown_results = Vec::new();
7441                 {
7442                         let per_peer_state = self.per_peer_state.read().unwrap();
7443
7444                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7445                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7446                                 let peer_state = &mut *peer_state_lock;
7447                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7448                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7449                                         match phase {
7450                                                 ChannelPhase::Funded(chan) => {
7451                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7452                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &&logger) {
7453                                                                 Ok((msg_opt, tx_opt, shutdown_result_opt)) => {
7454                                                                         if let Some(msg) = msg_opt {
7455                                                                                 has_update = true;
7456                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7457                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7458                                                                                 });
7459                                                                         }
7460                                                                         debug_assert_eq!(shutdown_result_opt.is_some(), chan.is_shutdown());
7461                                                                         if let Some(shutdown_result) = shutdown_result_opt {
7462                                                                                 shutdown_results.push(shutdown_result);
7463                                                                         }
7464                                                                         if let Some(tx) = tx_opt {
7465                                                                                 // We're done with this channel. We got a closing_signed and sent back
7466                                                                                 // a closing_signed with a closing transaction to broadcast.
7467                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7468                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7469                                                                                                 msg: update
7470                                                                                         });
7471                                                                                 }
7472
7473                                                                                 log_info!(logger, "Broadcasting {}", log_tx!(tx));
7474                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7475                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7476                                                                                 false
7477                                                                         } else { true }
7478                                                                 },
7479                                                                 Err(e) => {
7480                                                                         has_update = true;
7481                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7482                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7483                                                                         !close_channel
7484                                                                 }
7485                                                         }
7486                                                 },
7487                                                 _ => true, // Retain unfunded channels if present.
7488                                         }
7489                                 });
7490                         }
7491                 }
7492
7493                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7494                         let _ = handle_error!(self, err, counterparty_node_id);
7495                 }
7496
7497                 for shutdown_result in shutdown_results.drain(..) {
7498                         self.finish_close_channel(shutdown_result);
7499                 }
7500
7501                 has_update
7502         }
7503
7504         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7505         /// pushing the channel monitor update (if any) to the background events queue and removing the
7506         /// Channel object.
7507         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7508                 for mut failure in failed_channels.drain(..) {
7509                         // Either a commitment transactions has been confirmed on-chain or
7510                         // Channel::block_disconnected detected that the funding transaction has been
7511                         // reorganized out of the main chain.
7512                         // We cannot broadcast our latest local state via monitor update (as
7513                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7514                         // so we track the update internally and handle it when the user next calls
7515                         // timer_tick_occurred, guaranteeing we're running normally.
7516                         if let Some((counterparty_node_id, funding_txo, update)) = failure.monitor_update.take() {
7517                                 assert_eq!(update.updates.len(), 1);
7518                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7519                                         assert!(should_broadcast);
7520                                 } else { unreachable!(); }
7521                                 self.pending_background_events.lock().unwrap().push(
7522                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7523                                                 counterparty_node_id, funding_txo, update
7524                                         });
7525                         }
7526                         self.finish_close_channel(failure);
7527                 }
7528         }
7529 }
7530
7531 macro_rules! create_offer_builder { ($self: ident, $builder: ty) => {
7532         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7533         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7534         /// not have an expiration unless otherwise set on the builder.
7535         ///
7536         /// # Privacy
7537         ///
7538         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the offer.
7539         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7540         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7541         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7542         /// order to send the [`InvoiceRequest`].
7543         ///
7544         /// Also, uses a derived signing pubkey in the offer for recipient privacy.
7545         ///
7546         /// # Limitations
7547         ///
7548         /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
7549         /// reply path.
7550         ///
7551         /// # Errors
7552         ///
7553         /// Errors if the parameterized [`Router`] is unable to create a blinded path for the offer.
7554         ///
7555         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7556         ///
7557         /// [`Offer`]: crate::offers::offer::Offer
7558         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7559         pub fn create_offer_builder(
7560                 &$self, description: String
7561         ) -> Result<$builder, Bolt12SemanticError> {
7562                 let node_id = $self.get_our_node_id();
7563                 let expanded_key = &$self.inbound_payment_key;
7564                 let entropy = &*$self.entropy_source;
7565                 let secp_ctx = &$self.secp_ctx;
7566
7567                 let path = $self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7568                 let builder = OfferBuilder::deriving_signing_pubkey(
7569                         description, node_id, expanded_key, entropy, secp_ctx
7570                 )
7571                         .chain_hash($self.chain_hash)
7572                         .path(path);
7573
7574                 Ok(builder.into())
7575         }
7576 } }
7577
7578 macro_rules! create_refund_builder { ($self: ident, $builder: ty) => {
7579         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7580         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7581         ///
7582         /// # Payment
7583         ///
7584         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7585         /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
7586         ///
7587         /// The builder will have the provided expiration set. Any changes to the expiration on the
7588         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7589         /// block time minus two hours is used for the current time when determining if the refund has
7590         /// expired.
7591         ///
7592         /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
7593         /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
7594         /// with an [`Event::InvoiceRequestFailed`].
7595         ///
7596         /// If `max_total_routing_fee_msat` is not specified, The default from
7597         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7598         ///
7599         /// # Privacy
7600         ///
7601         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the refund.
7602         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7603         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7604         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7605         /// order to send the [`Bolt12Invoice`].
7606         ///
7607         /// Also, uses a derived payer id in the refund for payer privacy.
7608         ///
7609         /// # Limitations
7610         ///
7611         /// Requires a direct connection to an introduction node in the responding
7612         /// [`Bolt12Invoice::payment_paths`].
7613         ///
7614         /// # Errors
7615         ///
7616         /// Errors if:
7617         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7618         /// - `amount_msats` is invalid, or
7619         /// - the parameterized [`Router`] is unable to create a blinded path for the refund.
7620         ///
7621         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7622         ///
7623         /// [`Refund`]: crate::offers::refund::Refund
7624         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7625         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7626         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7627         pub fn create_refund_builder(
7628                 &$self, description: String, amount_msats: u64, absolute_expiry: Duration,
7629                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7630         ) -> Result<$builder, Bolt12SemanticError> {
7631                 let node_id = $self.get_our_node_id();
7632                 let expanded_key = &$self.inbound_payment_key;
7633                 let entropy = &*$self.entropy_source;
7634                 let secp_ctx = &$self.secp_ctx;
7635
7636                 let path = $self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7637                 let builder = RefundBuilder::deriving_payer_id(
7638                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7639                 )?
7640                         .chain_hash($self.chain_hash)
7641                         .absolute_expiry(absolute_expiry)
7642                         .path(path);
7643
7644                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7645                 $self.pending_outbound_payments
7646                         .add_new_awaiting_invoice(
7647                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7648                         )
7649                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7650
7651                 Ok(builder.into())
7652         }
7653 } }
7654
7655 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>
7656 where
7657         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
7658         T::Target: BroadcasterInterface,
7659         ES::Target: EntropySource,
7660         NS::Target: NodeSigner,
7661         SP::Target: SignerProvider,
7662         F::Target: FeeEstimator,
7663         R::Target: Router,
7664         L::Target: Logger,
7665 {
7666         #[cfg(not(c_bindings))]
7667         create_offer_builder!(self, OfferBuilder<DerivedMetadata, secp256k1::All>);
7668         #[cfg(not(c_bindings))]
7669         create_refund_builder!(self, RefundBuilder<secp256k1::All>);
7670
7671         #[cfg(c_bindings)]
7672         create_offer_builder!(self, OfferWithDerivedMetadataBuilder);
7673         #[cfg(c_bindings)]
7674         create_refund_builder!(self, RefundMaybeWithDerivedMetadataBuilder);
7675
7676         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7677         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7678         /// [`Bolt12Invoice`] once it is received.
7679         ///
7680         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7681         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7682         /// The optional parameters are used in the builder, if `Some`:
7683         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7684         ///   [`Offer::expects_quantity`] is `true`.
7685         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7686         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7687         ///
7688         /// If `max_total_routing_fee_msat` is not specified, The default from
7689         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7690         ///
7691         /// # Payment
7692         ///
7693         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7694         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7695         /// been sent.
7696         ///
7697         /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
7698         /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
7699         /// payment will fail with an [`Event::InvoiceRequestFailed`].
7700         ///
7701         /// # Privacy
7702         ///
7703         /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
7704         /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
7705         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7706         /// in order to send the [`Bolt12Invoice`].
7707         ///
7708         /// # Limitations
7709         ///
7710         /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
7711         /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
7712         /// [`Bolt12Invoice::payment_paths`].
7713         ///
7714         /// # Errors
7715         ///
7716         /// Errors if:
7717         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7718         /// - the provided parameters are invalid for the offer,
7719         /// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice
7720         ///   request.
7721         ///
7722         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7723         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7724         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7725         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7726         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7727         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7728         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7729         pub fn pay_for_offer(
7730                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7731                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7732                 max_total_routing_fee_msat: Option<u64>
7733         ) -> Result<(), Bolt12SemanticError> {
7734                 let expanded_key = &self.inbound_payment_key;
7735                 let entropy = &*self.entropy_source;
7736                 let secp_ctx = &self.secp_ctx;
7737
7738                 let builder = offer
7739                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7740                         .chain_hash(self.chain_hash)?;
7741                 let builder = match quantity {
7742                         None => builder,
7743                         Some(quantity) => builder.quantity(quantity)?,
7744                 };
7745                 let builder = match amount_msats {
7746                         None => builder,
7747                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7748                 };
7749                 let builder = match payer_note {
7750                         None => builder,
7751                         Some(payer_note) => builder.payer_note(payer_note),
7752                 };
7753                 let invoice_request = builder.build_and_sign()?;
7754                 let reply_path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7755
7756                 let expiration = StaleExpiration::TimerTicks(1);
7757                 self.pending_outbound_payments
7758                         .add_new_awaiting_invoice(
7759                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7760                         )
7761                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7762
7763                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7764                 if offer.paths().is_empty() {
7765                         let message = new_pending_onion_message(
7766                                 OffersMessage::InvoiceRequest(invoice_request),
7767                                 Destination::Node(offer.signing_pubkey()),
7768                                 Some(reply_path),
7769                         );
7770                         pending_offers_messages.push(message);
7771                 } else {
7772                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7773                         // Using only one path could result in a failure if the path no longer exists. But only
7774                         // one invoice for a given payment id will be paid, even if more than one is received.
7775                         const REQUEST_LIMIT: usize = 10;
7776                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7777                                 let message = new_pending_onion_message(
7778                                         OffersMessage::InvoiceRequest(invoice_request.clone()),
7779                                         Destination::BlindedPath(path.clone()),
7780                                         Some(reply_path.clone()),
7781                                 );
7782                                 pending_offers_messages.push(message);
7783                         }
7784                 }
7785
7786                 Ok(())
7787         }
7788
7789         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7790         /// message.
7791         ///
7792         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7793         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7794         /// [`PaymentPreimage`].
7795         ///
7796         /// # Limitations
7797         ///
7798         /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
7799         /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
7800         /// node meeting the aforementioned criteria, but there's no guarantee that they will be
7801         /// received and no retries will be made.
7802         ///
7803         /// # Errors
7804         ///
7805         /// Errors if the parameterized [`Router`] is unable to create a blinded payment path or reply
7806         /// path for the invoice.
7807         ///
7808         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7809         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7810                 let expanded_key = &self.inbound_payment_key;
7811                 let entropy = &*self.entropy_source;
7812                 let secp_ctx = &self.secp_ctx;
7813
7814                 let amount_msats = refund.amount_msats();
7815                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7816
7817                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7818                         Ok((payment_hash, payment_secret)) => {
7819                                 let payment_paths = self.create_blinded_payment_paths(amount_msats, payment_secret)
7820                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7821
7822                                 #[cfg(feature = "std")]
7823                                 let builder = refund.respond_using_derived_keys(
7824                                         payment_paths, payment_hash, expanded_key, entropy
7825                                 )?;
7826                                 #[cfg(not(feature = "std"))]
7827                                 let created_at = Duration::from_secs(
7828                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7829                                 );
7830                                 #[cfg(not(feature = "std"))]
7831                                 let builder = refund.respond_using_derived_keys_no_std(
7832                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7833                                 )?;
7834                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7835                                 let reply_path = self.create_blinded_path()
7836                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7837
7838                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7839                                 if refund.paths().is_empty() {
7840                                         let message = new_pending_onion_message(
7841                                                 OffersMessage::Invoice(invoice),
7842                                                 Destination::Node(refund.payer_id()),
7843                                                 Some(reply_path),
7844                                         );
7845                                         pending_offers_messages.push(message);
7846                                 } else {
7847                                         for path in refund.paths() {
7848                                                 let message = new_pending_onion_message(
7849                                                         OffersMessage::Invoice(invoice.clone()),
7850                                                         Destination::BlindedPath(path.clone()),
7851                                                         Some(reply_path.clone()),
7852                                                 );
7853                                                 pending_offers_messages.push(message);
7854                                         }
7855                                 }
7856
7857                                 Ok(())
7858                         },
7859                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7860                 }
7861         }
7862
7863         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7864         /// to pay us.
7865         ///
7866         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7867         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7868         ///
7869         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7870         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7871         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7872         /// passed directly to [`claim_funds`].
7873         ///
7874         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7875         ///
7876         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7877         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7878         ///
7879         /// # Note
7880         ///
7881         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7882         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7883         ///
7884         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7885         ///
7886         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7887         /// on versions of LDK prior to 0.0.114.
7888         ///
7889         /// [`claim_funds`]: Self::claim_funds
7890         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7891         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7892         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7893         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7894         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7895         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7896                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7897                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7898                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7899                         min_final_cltv_expiry_delta)
7900         }
7901
7902         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7903         /// stored external to LDK.
7904         ///
7905         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7906         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7907         /// the `min_value_msat` provided here, if one is provided.
7908         ///
7909         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7910         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7911         /// payments.
7912         ///
7913         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7914         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7915         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7916         /// sender "proof-of-payment" unless they have paid the required amount.
7917         ///
7918         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7919         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7920         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7921         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7922         /// invoices when no timeout is set.
7923         ///
7924         /// Note that we use block header time to time-out pending inbound payments (with some margin
7925         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7926         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7927         /// If you need exact expiry semantics, you should enforce them upon receipt of
7928         /// [`PaymentClaimable`].
7929         ///
7930         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7931         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7932         ///
7933         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7934         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7935         ///
7936         /// # Note
7937         ///
7938         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7939         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7940         ///
7941         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7942         ///
7943         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7944         /// on versions of LDK prior to 0.0.114.
7945         ///
7946         /// [`create_inbound_payment`]: Self::create_inbound_payment
7947         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7948         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7949                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7950                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7951                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7952                         min_final_cltv_expiry)
7953         }
7954
7955         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7956         /// previously returned from [`create_inbound_payment`].
7957         ///
7958         /// [`create_inbound_payment`]: Self::create_inbound_payment
7959         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7960                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7961         }
7962
7963         /// Creates a blinded path by delegating to [`MessageRouter::create_blinded_paths`].
7964         ///
7965         /// Errors if the `MessageRouter` errors or returns an empty `Vec`.
7966         fn create_blinded_path(&self) -> Result<BlindedPath, ()> {
7967                 let recipient = self.get_our_node_id();
7968                 let entropy_source = self.entropy_source.deref();
7969                 let secp_ctx = &self.secp_ctx;
7970
7971                 let peers = self.per_peer_state.read().unwrap()
7972                         .iter()
7973                         .filter(|(_, peer)| peer.lock().unwrap().latest_features.supports_onion_messages())
7974                         .map(|(node_id, _)| *node_id)
7975                         .collect::<Vec<_>>();
7976
7977                 self.router
7978                         .create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
7979                         .and_then(|paths| paths.into_iter().next().ok_or(()))
7980         }
7981
7982         /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
7983         /// [`Router::create_blinded_payment_paths`].
7984         fn create_blinded_payment_paths(
7985                 &self, amount_msats: u64, payment_secret: PaymentSecret
7986         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
7987                 let entropy_source = self.entropy_source.deref();
7988                 let secp_ctx = &self.secp_ctx;
7989
7990                 let first_hops = self.list_usable_channels();
7991                 let payee_node_id = self.get_our_node_id();
7992                 let max_cltv_expiry = self.best_block.read().unwrap().height() + CLTV_FAR_FAR_AWAY
7993                         + LATENCY_GRACE_PERIOD_BLOCKS;
7994                 let payee_tlvs = ReceiveTlvs {
7995                         payment_secret,
7996                         payment_constraints: PaymentConstraints {
7997                                 max_cltv_expiry,
7998                                 htlc_minimum_msat: 1,
7999                         },
8000                 };
8001                 self.router.create_blinded_payment_paths(
8002                         payee_node_id, first_hops, payee_tlvs, amount_msats, entropy_source, secp_ctx
8003                 )
8004         }
8005
8006         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
8007         /// are used when constructing the phantom invoice's route hints.
8008         ///
8009         /// [phantom node payments]: crate::sign::PhantomKeysManager
8010         pub fn get_phantom_scid(&self) -> u64 {
8011                 let best_block_height = self.best_block.read().unwrap().height();
8012                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8013                 loop {
8014                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8015                         // Ensure the generated scid doesn't conflict with a real channel.
8016                         match short_to_chan_info.get(&scid_candidate) {
8017                                 Some(_) => continue,
8018                                 None => return scid_candidate
8019                         }
8020                 }
8021         }
8022
8023         /// Gets route hints for use in receiving [phantom node payments].
8024         ///
8025         /// [phantom node payments]: crate::sign::PhantomKeysManager
8026         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
8027                 PhantomRouteHints {
8028                         channels: self.list_usable_channels(),
8029                         phantom_scid: self.get_phantom_scid(),
8030                         real_node_pubkey: self.get_our_node_id(),
8031                 }
8032         }
8033
8034         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
8035         /// used when constructing the route hints for HTLCs intended to be intercepted. See
8036         /// [`ChannelManager::forward_intercepted_htlc`].
8037         ///
8038         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
8039         /// times to get a unique scid.
8040         pub fn get_intercept_scid(&self) -> u64 {
8041                 let best_block_height = self.best_block.read().unwrap().height();
8042                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8043                 loop {
8044                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8045                         // Ensure the generated scid doesn't conflict with a real channel.
8046                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
8047                         return scid_candidate
8048                 }
8049         }
8050
8051         /// Gets inflight HTLC information by processing pending outbound payments that are in
8052         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
8053         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
8054                 let mut inflight_htlcs = InFlightHtlcs::new();
8055
8056                 let per_peer_state = self.per_peer_state.read().unwrap();
8057                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8058                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8059                         let peer_state = &mut *peer_state_lock;
8060                         for chan in peer_state.channel_by_id.values().filter_map(
8061                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
8062                         ) {
8063                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
8064                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
8065                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
8066                                         }
8067                                 }
8068                         }
8069                 }
8070
8071                 inflight_htlcs
8072         }
8073
8074         #[cfg(any(test, feature = "_test_utils"))]
8075         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
8076                 let events = core::cell::RefCell::new(Vec::new());
8077                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
8078                 self.process_pending_events(&event_handler);
8079                 events.into_inner()
8080         }
8081
8082         #[cfg(feature = "_test_utils")]
8083         pub fn push_pending_event(&self, event: events::Event) {
8084                 let mut events = self.pending_events.lock().unwrap();
8085                 events.push_back((event, None));
8086         }
8087
8088         #[cfg(test)]
8089         pub fn pop_pending_event(&self) -> Option<events::Event> {
8090                 let mut events = self.pending_events.lock().unwrap();
8091                 events.pop_front().map(|(e, _)| e)
8092         }
8093
8094         #[cfg(test)]
8095         pub fn has_pending_payments(&self) -> bool {
8096                 self.pending_outbound_payments.has_pending_payments()
8097         }
8098
8099         #[cfg(test)]
8100         pub fn clear_pending_payments(&self) {
8101                 self.pending_outbound_payments.clear_pending_payments()
8102         }
8103
8104         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
8105         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
8106         /// operation. It will double-check that nothing *else* is also blocking the same channel from
8107         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
8108         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
8109                 let logger = WithContext::from(
8110                         &self.logger, Some(counterparty_node_id), Some(channel_funding_outpoint.to_channel_id())
8111                 );
8112                 loop {
8113                         let per_peer_state = self.per_peer_state.read().unwrap();
8114                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
8115                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
8116                                 let peer_state = &mut *peer_state_lck;
8117                                 if let Some(blocker) = completed_blocker.take() {
8118                                         // Only do this on the first iteration of the loop.
8119                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
8120                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
8121                                         {
8122                                                 blockers.retain(|iter| iter != &blocker);
8123                                         }
8124                                 }
8125
8126                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
8127                                         channel_funding_outpoint, counterparty_node_id) {
8128                                         // Check that, while holding the peer lock, we don't have anything else
8129                                         // blocking monitor updates for this channel. If we do, release the monitor
8130                                         // update(s) when those blockers complete.
8131                                         log_trace!(logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
8132                                                 &channel_funding_outpoint.to_channel_id());
8133                                         break;
8134                                 }
8135
8136                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
8137                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
8138                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
8139                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
8140                                                         log_debug!(logger, "Unlocking monitor updating for channel {} and updating monitor",
8141                                                                 channel_funding_outpoint.to_channel_id());
8142                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
8143                                                                 peer_state_lck, peer_state, per_peer_state, chan);
8144                                                         if further_update_exists {
8145                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
8146                                                                 // top of the loop.
8147                                                                 continue;
8148                                                         }
8149                                                 } else {
8150                                                         log_trace!(logger, "Unlocked monitor updating for channel {} without monitors to update",
8151                                                                 channel_funding_outpoint.to_channel_id());
8152                                                 }
8153                                         }
8154                                 }
8155                         } else {
8156                                 log_debug!(logger,
8157                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
8158                                         log_pubkey!(counterparty_node_id));
8159                         }
8160                         break;
8161                 }
8162         }
8163
8164         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
8165                 for action in actions {
8166                         match action {
8167                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
8168                                         channel_funding_outpoint, counterparty_node_id
8169                                 } => {
8170                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
8171                                 }
8172                         }
8173                 }
8174         }
8175
8176         /// Processes any events asynchronously in the order they were generated since the last call
8177         /// using the given event handler.
8178         ///
8179         /// See the trait-level documentation of [`EventsProvider`] for requirements.
8180         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
8181                 &self, handler: H
8182         ) {
8183                 let mut ev;
8184                 process_events_body!(self, ev, { handler(ev).await });
8185         }
8186 }
8187
8188 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>
8189 where
8190         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8191         T::Target: BroadcasterInterface,
8192         ES::Target: EntropySource,
8193         NS::Target: NodeSigner,
8194         SP::Target: SignerProvider,
8195         F::Target: FeeEstimator,
8196         R::Target: Router,
8197         L::Target: Logger,
8198 {
8199         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
8200         /// The returned array will contain `MessageSendEvent`s for different peers if
8201         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
8202         /// is always placed next to each other.
8203         ///
8204         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
8205         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
8206         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
8207         /// will randomly be placed first or last in the returned array.
8208         ///
8209         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
8210         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
8211         /// the `MessageSendEvent`s to the specific peer they were generated under.
8212         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
8213                 let events = RefCell::new(Vec::new());
8214                 PersistenceNotifierGuard::optionally_notify(self, || {
8215                         let mut result = NotifyOption::SkipPersistNoEvents;
8216
8217                         // TODO: This behavior should be documented. It's unintuitive that we query
8218                         // ChannelMonitors when clearing other events.
8219                         if self.process_pending_monitor_events() {
8220                                 result = NotifyOption::DoPersist;
8221                         }
8222
8223                         if self.check_free_holding_cells() {
8224                                 result = NotifyOption::DoPersist;
8225                         }
8226                         if self.maybe_generate_initial_closing_signed() {
8227                                 result = NotifyOption::DoPersist;
8228                         }
8229
8230                         let mut pending_events = Vec::new();
8231                         let per_peer_state = self.per_peer_state.read().unwrap();
8232                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8233                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8234                                 let peer_state = &mut *peer_state_lock;
8235                                 if peer_state.pending_msg_events.len() > 0 {
8236                                         pending_events.append(&mut peer_state.pending_msg_events);
8237                                 }
8238                         }
8239
8240                         if !pending_events.is_empty() {
8241                                 events.replace(pending_events);
8242                         }
8243
8244                         result
8245                 });
8246                 events.into_inner()
8247         }
8248 }
8249
8250 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>
8251 where
8252         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8253         T::Target: BroadcasterInterface,
8254         ES::Target: EntropySource,
8255         NS::Target: NodeSigner,
8256         SP::Target: SignerProvider,
8257         F::Target: FeeEstimator,
8258         R::Target: Router,
8259         L::Target: Logger,
8260 {
8261         /// Processes events that must be periodically handled.
8262         ///
8263         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
8264         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
8265         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
8266                 let mut ev;
8267                 process_events_body!(self, ev, handler.handle_event(ev));
8268         }
8269 }
8270
8271 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>
8272 where
8273         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8274         T::Target: BroadcasterInterface,
8275         ES::Target: EntropySource,
8276         NS::Target: NodeSigner,
8277         SP::Target: SignerProvider,
8278         F::Target: FeeEstimator,
8279         R::Target: Router,
8280         L::Target: Logger,
8281 {
8282         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
8283                 {
8284                         let best_block = self.best_block.read().unwrap();
8285                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
8286                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
8287                         assert_eq!(best_block.height(), height - 1,
8288                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
8289                 }
8290
8291                 self.transactions_confirmed(header, txdata, height);
8292                 self.best_block_updated(header, height);
8293         }
8294
8295         fn block_disconnected(&self, header: &Header, height: u32) {
8296                 let _persistence_guard =
8297                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8298                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8299                 let new_height = height - 1;
8300                 {
8301                         let mut best_block = self.best_block.write().unwrap();
8302                         assert_eq!(best_block.block_hash(), header.block_hash(),
8303                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
8304                         assert_eq!(best_block.height(), height,
8305                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
8306                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
8307                 }
8308
8309                 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)));
8310         }
8311 }
8312
8313 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>
8314 where
8315         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8316         T::Target: BroadcasterInterface,
8317         ES::Target: EntropySource,
8318         NS::Target: NodeSigner,
8319         SP::Target: SignerProvider,
8320         F::Target: FeeEstimator,
8321         R::Target: Router,
8322         L::Target: Logger,
8323 {
8324         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
8325                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8326                 // during initialization prior to the chain_monitor being fully configured in some cases.
8327                 // See the docs for `ChannelManagerReadArgs` for more.
8328
8329                 let block_hash = header.block_hash();
8330                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
8331
8332                 let _persistence_guard =
8333                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8334                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8335                 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))
8336                         .map(|(a, b)| (a, Vec::new(), b)));
8337
8338                 let last_best_block_height = self.best_block.read().unwrap().height();
8339                 if height < last_best_block_height {
8340                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
8341                         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)));
8342                 }
8343         }
8344
8345         fn best_block_updated(&self, header: &Header, height: u32) {
8346                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8347                 // during initialization prior to the chain_monitor being fully configured in some cases.
8348                 // See the docs for `ChannelManagerReadArgs` for more.
8349
8350                 let block_hash = header.block_hash();
8351                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
8352
8353                 let _persistence_guard =
8354                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8355                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8356                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
8357
8358                 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)));
8359
8360                 macro_rules! max_time {
8361                         ($timestamp: expr) => {
8362                                 loop {
8363                                         // Update $timestamp to be the max of its current value and the block
8364                                         // timestamp. This should keep us close to the current time without relying on
8365                                         // having an explicit local time source.
8366                                         // Just in case we end up in a race, we loop until we either successfully
8367                                         // update $timestamp or decide we don't need to.
8368                                         let old_serial = $timestamp.load(Ordering::Acquire);
8369                                         if old_serial >= header.time as usize { break; }
8370                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8371                                                 break;
8372                                         }
8373                                 }
8374                         }
8375                 }
8376                 max_time!(self.highest_seen_timestamp);
8377                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8378                 payment_secrets.retain(|_, inbound_payment| {
8379                         inbound_payment.expiry_time > header.time as u64
8380                 });
8381         }
8382
8383         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
8384                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8385                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8386                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8387                         let peer_state = &mut *peer_state_lock;
8388                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8389                                 let txid_opt = chan.context.get_funding_txo();
8390                                 let height_opt = chan.context.get_funding_tx_confirmation_height();
8391                                 let hash_opt = chan.context.get_funding_tx_confirmed_in();
8392                                 if let (Some(funding_txo), Some(conf_height), Some(block_hash)) = (txid_opt, height_opt, hash_opt) {
8393                                         res.push((funding_txo.txid, conf_height, Some(block_hash)));
8394                                 }
8395                         }
8396                 }
8397                 res
8398         }
8399
8400         fn transaction_unconfirmed(&self, txid: &Txid) {
8401                 let _persistence_guard =
8402                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8403                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8404                 self.do_chain_event(None, |channel| {
8405                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8406                                 if funding_txo.txid == *txid {
8407                                         channel.funding_transaction_unconfirmed(&&WithChannelContext::from(&self.logger, &channel.context)).map(|()| (None, Vec::new(), None))
8408                                 } else { Ok((None, Vec::new(), None)) }
8409                         } else { Ok((None, Vec::new(), None)) }
8410                 });
8411         }
8412 }
8413
8414 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>
8415 where
8416         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8417         T::Target: BroadcasterInterface,
8418         ES::Target: EntropySource,
8419         NS::Target: NodeSigner,
8420         SP::Target: SignerProvider,
8421         F::Target: FeeEstimator,
8422         R::Target: Router,
8423         L::Target: Logger,
8424 {
8425         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8426         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8427         /// the function.
8428         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8429                         (&self, height_opt: Option<u32>, f: FN) {
8430                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8431                 // during initialization prior to the chain_monitor being fully configured in some cases.
8432                 // See the docs for `ChannelManagerReadArgs` for more.
8433
8434                 let mut failed_channels = Vec::new();
8435                 let mut timed_out_htlcs = Vec::new();
8436                 {
8437                         let per_peer_state = self.per_peer_state.read().unwrap();
8438                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8439                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8440                                 let peer_state = &mut *peer_state_lock;
8441                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8442                                 peer_state.channel_by_id.retain(|_, phase| {
8443                                         match phase {
8444                                                 // Retain unfunded channels.
8445                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8446                                                 ChannelPhase::Funded(channel) => {
8447                                                         let res = f(channel);
8448                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8449                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8450                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8451                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8452                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8453                                                                 }
8454                                                                 let logger = WithChannelContext::from(&self.logger, &channel.context);
8455                                                                 if let Some(channel_ready) = channel_ready_opt {
8456                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8457                                                                         if channel.context.is_usable() {
8458                                                                                 log_trace!(logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8459                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8460                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8461                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8462                                                                                                 msg,
8463                                                                                         });
8464                                                                                 }
8465                                                                         } else {
8466                                                                                 log_trace!(logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8467                                                                         }
8468                                                                 }
8469
8470                                                                 {
8471                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8472                                                                         emit_channel_ready_event!(pending_events, channel);
8473                                                                 }
8474
8475                                                                 if let Some(announcement_sigs) = announcement_sigs {
8476                                                                         log_trace!(logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8477                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8478                                                                                 node_id: channel.context.get_counterparty_node_id(),
8479                                                                                 msg: announcement_sigs,
8480                                                                         });
8481                                                                         if let Some(height) = height_opt {
8482                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8483                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8484                                                                                                 msg: announcement,
8485                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8486                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8487                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8488                                                                                         });
8489                                                                                 }
8490                                                                         }
8491                                                                 }
8492                                                                 if channel.is_our_channel_ready() {
8493                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8494                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8495                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8496                                                                                 // can relay using the real SCID at relay-time (i.e.
8497                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8498                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8499                                                                                 // is always consistent.
8500                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8501                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8502                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8503                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8504                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8505                                                                         }
8506                                                                 }
8507                                                         } else if let Err(reason) = res {
8508                                                                 update_maps_on_chan_removal!(self, &channel.context);
8509                                                                 // It looks like our counterparty went on-chain or funding transaction was
8510                                                                 // reorged out of the main chain. Close the channel.
8511                                                                 let reason_message = format!("{}", reason);
8512                                                                 failed_channels.push(channel.context.force_shutdown(true, reason));
8513                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8514                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
8515                                                                                 msg: update
8516                                                                         });
8517                                                                 }
8518                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8519                                                                         node_id: channel.context.get_counterparty_node_id(),
8520                                                                         action: msgs::ErrorAction::DisconnectPeer {
8521                                                                                 msg: Some(msgs::ErrorMessage {
8522                                                                                         channel_id: channel.context.channel_id(),
8523                                                                                         data: reason_message,
8524                                                                                 })
8525                                                                         },
8526                                                                 });
8527                                                                 return false;
8528                                                         }
8529                                                         true
8530                                                 }
8531                                         }
8532                                 });
8533                         }
8534                 }
8535
8536                 if let Some(height) = height_opt {
8537                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8538                                 payment.htlcs.retain(|htlc| {
8539                                         // If height is approaching the number of blocks we think it takes us to get
8540                                         // our commitment transaction confirmed before the HTLC expires, plus the
8541                                         // number of blocks we generally consider it to take to do a commitment update,
8542                                         // just give up on it and fail the HTLC.
8543                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8544                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8545                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8546
8547                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8548                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8549                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8550                                                 false
8551                                         } else { true }
8552                                 });
8553                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8554                         });
8555
8556                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8557                         intercepted_htlcs.retain(|_, htlc| {
8558                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8559                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8560                                                 short_channel_id: htlc.prev_short_channel_id,
8561                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8562                                                 htlc_id: htlc.prev_htlc_id,
8563                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8564                                                 phantom_shared_secret: None,
8565                                                 outpoint: htlc.prev_funding_outpoint,
8566                                                 blinded_failure: htlc.forward_info.routing.blinded_failure(),
8567                                         });
8568
8569                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8570                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8571                                                 _ => unreachable!(),
8572                                         };
8573                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8574                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8575                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8576                                         let logger = WithContext::from(
8577                                                 &self.logger, None, Some(htlc.prev_funding_outpoint.to_channel_id())
8578                                         );
8579                                         log_trace!(logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8580                                         false
8581                                 } else { true }
8582                         });
8583                 }
8584
8585                 self.handle_init_event_channel_failures(failed_channels);
8586
8587                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8588                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8589                 }
8590         }
8591
8592         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8593         /// may have events that need processing.
8594         ///
8595         /// In order to check if this [`ChannelManager`] needs persisting, call
8596         /// [`Self::get_and_clear_needs_persistence`].
8597         ///
8598         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8599         /// [`ChannelManager`] and should instead register actions to be taken later.
8600         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8601                 self.event_persist_notifier.get_future()
8602         }
8603
8604         /// Returns true if this [`ChannelManager`] needs to be persisted.
8605         pub fn get_and_clear_needs_persistence(&self) -> bool {
8606                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8607         }
8608
8609         #[cfg(any(test, feature = "_test_utils"))]
8610         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8611                 self.event_persist_notifier.notify_pending()
8612         }
8613
8614         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8615         /// [`chain::Confirm`] interfaces.
8616         pub fn current_best_block(&self) -> BestBlock {
8617                 self.best_block.read().unwrap().clone()
8618         }
8619
8620         /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
8621         /// [`ChannelManager`].
8622         pub fn node_features(&self) -> NodeFeatures {
8623                 provided_node_features(&self.default_configuration)
8624         }
8625
8626         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
8627         /// [`ChannelManager`].
8628         ///
8629         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8630         /// or not. Thus, this method is not public.
8631         #[cfg(any(feature = "_test_utils", test))]
8632         pub fn bolt11_invoice_features(&self) -> Bolt11InvoiceFeatures {
8633                 provided_bolt11_invoice_features(&self.default_configuration)
8634         }
8635
8636         /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
8637         /// [`ChannelManager`].
8638         fn bolt12_invoice_features(&self) -> Bolt12InvoiceFeatures {
8639                 provided_bolt12_invoice_features(&self.default_configuration)
8640         }
8641
8642         /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
8643         /// [`ChannelManager`].
8644         pub fn channel_features(&self) -> ChannelFeatures {
8645                 provided_channel_features(&self.default_configuration)
8646         }
8647
8648         /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
8649         /// [`ChannelManager`].
8650         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8651                 provided_channel_type_features(&self.default_configuration)
8652         }
8653
8654         /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
8655         /// [`ChannelManager`].
8656         pub fn init_features(&self) -> InitFeatures {
8657                 provided_init_features(&self.default_configuration)
8658         }
8659 }
8660
8661 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8662         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8663 where
8664         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8665         T::Target: BroadcasterInterface,
8666         ES::Target: EntropySource,
8667         NS::Target: NodeSigner,
8668         SP::Target: SignerProvider,
8669         F::Target: FeeEstimator,
8670         R::Target: Router,
8671         L::Target: Logger,
8672 {
8673         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8674                 // Note that we never need to persist the updated ChannelManager for an inbound
8675                 // open_channel message - pre-funded channels are never written so there should be no
8676                 // change to the contents.
8677                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8678                         let res = self.internal_open_channel(counterparty_node_id, msg);
8679                         let persist = match &res {
8680                                 Err(e) if e.closes_channel() => {
8681                                         debug_assert!(false, "We shouldn't close a new channel");
8682                                         NotifyOption::DoPersist
8683                                 },
8684                                 _ => NotifyOption::SkipPersistHandleEvents,
8685                         };
8686                         let _ = handle_error!(self, res, *counterparty_node_id);
8687                         persist
8688                 });
8689         }
8690
8691         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8692                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8693                         "Dual-funded channels not supported".to_owned(),
8694                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8695         }
8696
8697         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8698                 // Note that we never need to persist the updated ChannelManager for an inbound
8699                 // accept_channel message - pre-funded channels are never written so there should be no
8700                 // change to the contents.
8701                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8702                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8703                         NotifyOption::SkipPersistHandleEvents
8704                 });
8705         }
8706
8707         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8708                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8709                         "Dual-funded channels not supported".to_owned(),
8710                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8711         }
8712
8713         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8714                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8715                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8716         }
8717
8718         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8719                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8720                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8721         }
8722
8723         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8724                 // Note that we never need to persist the updated ChannelManager for an inbound
8725                 // channel_ready message - while the channel's state will change, any channel_ready message
8726                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8727                 // will not force-close the channel on startup.
8728                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8729                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8730                         let persist = match &res {
8731                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8732                                 _ => NotifyOption::SkipPersistHandleEvents,
8733                         };
8734                         let _ = handle_error!(self, res, *counterparty_node_id);
8735                         persist
8736                 });
8737         }
8738
8739         fn handle_stfu(&self, counterparty_node_id: &PublicKey, msg: &msgs::Stfu) {
8740                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8741                         "Quiescence not supported".to_owned(),
8742                          msg.channel_id.clone())), *counterparty_node_id);
8743         }
8744
8745         fn handle_splice(&self, counterparty_node_id: &PublicKey, msg: &msgs::Splice) {
8746                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8747                         "Splicing not supported".to_owned(),
8748                          msg.channel_id.clone())), *counterparty_node_id);
8749         }
8750
8751         fn handle_splice_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceAck) {
8752                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8753                         "Splicing not supported (splice_ack)".to_owned(),
8754                          msg.channel_id.clone())), *counterparty_node_id);
8755         }
8756
8757         fn handle_splice_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
8758                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8759                         "Splicing not supported (splice_locked)".to_owned(),
8760                          msg.channel_id.clone())), *counterparty_node_id);
8761         }
8762
8763         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8764                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8765                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8766         }
8767
8768         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8769                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8770                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8771         }
8772
8773         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8774                 // Note that we never need to persist the updated ChannelManager for an inbound
8775                 // update_add_htlc message - the message itself doesn't change our channel state only the
8776                 // `commitment_signed` message afterwards will.
8777                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8778                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8779                         let persist = match &res {
8780                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8781                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8782                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8783                         };
8784                         let _ = handle_error!(self, res, *counterparty_node_id);
8785                         persist
8786                 });
8787         }
8788
8789         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8790                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8791                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8792         }
8793
8794         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8795                 // Note that we never need to persist the updated ChannelManager for an inbound
8796                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8797                 // `commitment_signed` message afterwards will.
8798                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8799                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8800                         let persist = match &res {
8801                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8802                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8803                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8804                         };
8805                         let _ = handle_error!(self, res, *counterparty_node_id);
8806                         persist
8807                 });
8808         }
8809
8810         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8811                 // Note that we never need to persist the updated ChannelManager for an inbound
8812                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8813                 // only the `commitment_signed` message afterwards will.
8814                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8815                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8816                         let persist = match &res {
8817                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8818                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8819                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8820                         };
8821                         let _ = handle_error!(self, res, *counterparty_node_id);
8822                         persist
8823                 });
8824         }
8825
8826         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8827                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8828                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8829         }
8830
8831         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8832                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8833                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8834         }
8835
8836         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8837                 // Note that we never need to persist the updated ChannelManager for an inbound
8838                 // update_fee message - the message itself doesn't change our channel state only the
8839                 // `commitment_signed` message afterwards will.
8840                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8841                         let res = self.internal_update_fee(counterparty_node_id, msg);
8842                         let persist = match &res {
8843                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8844                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8845                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8846                         };
8847                         let _ = handle_error!(self, res, *counterparty_node_id);
8848                         persist
8849                 });
8850         }
8851
8852         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8853                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8854                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8855         }
8856
8857         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8858                 PersistenceNotifierGuard::optionally_notify(self, || {
8859                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8860                                 persist
8861                         } else {
8862                                 NotifyOption::DoPersist
8863                         }
8864                 });
8865         }
8866
8867         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8868                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8869                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8870                         let persist = match &res {
8871                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8872                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8873                                 Ok(persist) => *persist,
8874                         };
8875                         let _ = handle_error!(self, res, *counterparty_node_id);
8876                         persist
8877                 });
8878         }
8879
8880         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8881                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8882                         self, || NotifyOption::SkipPersistHandleEvents);
8883                 let mut failed_channels = Vec::new();
8884                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8885                 let remove_peer = {
8886                         log_debug!(
8887                                 WithContext::from(&self.logger, Some(*counterparty_node_id), None),
8888                                 "Marking channels with {} disconnected and generating channel_updates.",
8889                                 log_pubkey!(counterparty_node_id)
8890                         );
8891                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8892                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8893                                 let peer_state = &mut *peer_state_lock;
8894                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8895                                 peer_state.channel_by_id.retain(|_, phase| {
8896                                         let context = match phase {
8897                                                 ChannelPhase::Funded(chan) => {
8898                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
8899                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&&logger).is_ok() {
8900                                                                 // We only retain funded channels that are not shutdown.
8901                                                                 return true;
8902                                                         }
8903                                                         &mut chan.context
8904                                                 },
8905                                                 // Unfunded channels will always be removed.
8906                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8907                                                         &mut chan.context
8908                                                 },
8909                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8910                                                         &mut chan.context
8911                                                 },
8912                                         };
8913                                         // Clean up for removal.
8914                                         update_maps_on_chan_removal!(self, &context);
8915                                         failed_channels.push(context.force_shutdown(false, ClosureReason::DisconnectedPeer));
8916                                         false
8917                                 });
8918                                 // Note that we don't bother generating any events for pre-accept channels -
8919                                 // they're not considered "channels" yet from the PoV of our events interface.
8920                                 peer_state.inbound_channel_request_by_id.clear();
8921                                 pending_msg_events.retain(|msg| {
8922                                         match msg {
8923                                                 // V1 Channel Establishment
8924                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8925                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8926                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8927                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8928                                                 // V2 Channel Establishment
8929                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8930                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8931                                                 // Common Channel Establishment
8932                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8933                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8934                                                 // Quiescence
8935                                                 &events::MessageSendEvent::SendStfu { .. } => false,
8936                                                 // Splicing
8937                                                 &events::MessageSendEvent::SendSplice { .. } => false,
8938                                                 &events::MessageSendEvent::SendSpliceAck { .. } => false,
8939                                                 &events::MessageSendEvent::SendSpliceLocked { .. } => false,
8940                                                 // Interactive Transaction Construction
8941                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8942                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8943                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8944                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8945                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8946                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8947                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8948                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8949                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8950                                                 // Channel Operations
8951                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8952                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8953                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8954                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8955                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8956                                                 &events::MessageSendEvent::HandleError { .. } => false,
8957                                                 // Gossip
8958                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8959                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8960                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8961                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8962                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8963                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8964                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8965                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8966                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8967                                         }
8968                                 });
8969                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8970                                 peer_state.is_connected = false;
8971                                 peer_state.ok_to_remove(true)
8972                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8973                 };
8974                 if remove_peer {
8975                         per_peer_state.remove(counterparty_node_id);
8976                 }
8977                 mem::drop(per_peer_state);
8978
8979                 for failure in failed_channels.drain(..) {
8980                         self.finish_close_channel(failure);
8981                 }
8982         }
8983
8984         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8985                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), None);
8986                 if !init_msg.features.supports_static_remote_key() {
8987                         log_debug!(logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8988                         return Err(());
8989                 }
8990
8991                 let mut res = Ok(());
8992
8993                 PersistenceNotifierGuard::optionally_notify(self, || {
8994                         // If we have too many peers connected which don't have funded channels, disconnect the
8995                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8996                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8997                         // peers connect, but we'll reject new channels from them.
8998                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8999                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
9000
9001                         {
9002                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
9003                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
9004                                         hash_map::Entry::Vacant(e) => {
9005                                                 if inbound_peer_limited {
9006                                                         res = Err(());
9007                                                         return NotifyOption::SkipPersistNoEvents;
9008                                                 }
9009                                                 e.insert(Mutex::new(PeerState {
9010                                                         channel_by_id: HashMap::new(),
9011                                                         inbound_channel_request_by_id: HashMap::new(),
9012                                                         latest_features: init_msg.features.clone(),
9013                                                         pending_msg_events: Vec::new(),
9014                                                         in_flight_monitor_updates: BTreeMap::new(),
9015                                                         monitor_update_blocked_actions: BTreeMap::new(),
9016                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
9017                                                         is_connected: true,
9018                                                 }));
9019                                         },
9020                                         hash_map::Entry::Occupied(e) => {
9021                                                 let mut peer_state = e.get().lock().unwrap();
9022                                                 peer_state.latest_features = init_msg.features.clone();
9023
9024                                                 let best_block_height = self.best_block.read().unwrap().height();
9025                                                 if inbound_peer_limited &&
9026                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
9027                                                         peer_state.channel_by_id.len()
9028                                                 {
9029                                                         res = Err(());
9030                                                         return NotifyOption::SkipPersistNoEvents;
9031                                                 }
9032
9033                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
9034                                                 peer_state.is_connected = true;
9035                                         },
9036                                 }
9037                         }
9038
9039                         log_debug!(logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
9040
9041                         let per_peer_state = self.per_peer_state.read().unwrap();
9042                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
9043                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9044                                 let peer_state = &mut *peer_state_lock;
9045                                 let pending_msg_events = &mut peer_state.pending_msg_events;
9046
9047                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
9048                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
9049                                 ).for_each(|chan| {
9050                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
9051                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
9052                                                 node_id: chan.context.get_counterparty_node_id(),
9053                                                 msg: chan.get_channel_reestablish(&&logger),
9054                                         });
9055                                 });
9056                         }
9057
9058                         return NotifyOption::SkipPersistHandleEvents;
9059                         //TODO: Also re-broadcast announcement_signatures
9060                 });
9061                 res
9062         }
9063
9064         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
9065                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9066
9067                 match &msg.data as &str {
9068                         "cannot co-op close channel w/ active htlcs"|
9069                         "link failed to shutdown" =>
9070                         {
9071                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
9072                                 // send one while HTLCs are still present. The issue is tracked at
9073                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
9074                                 // to fix it but none so far have managed to land upstream. The issue appears to be
9075                                 // very low priority for the LND team despite being marked "P1".
9076                                 // We're not going to bother handling this in a sensible way, instead simply
9077                                 // repeating the Shutdown message on repeat until morale improves.
9078                                 if !msg.channel_id.is_zero() {
9079                                         let per_peer_state = self.per_peer_state.read().unwrap();
9080                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9081                                         if peer_state_mutex_opt.is_none() { return; }
9082                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
9083                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
9084                                                 if let Some(msg) = chan.get_outbound_shutdown() {
9085                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
9086                                                                 node_id: *counterparty_node_id,
9087                                                                 msg,
9088                                                         });
9089                                                 }
9090                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
9091                                                         node_id: *counterparty_node_id,
9092                                                         action: msgs::ErrorAction::SendWarningMessage {
9093                                                                 msg: msgs::WarningMessage {
9094                                                                         channel_id: msg.channel_id,
9095                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
9096                                                                 },
9097                                                                 log_level: Level::Trace,
9098                                                         }
9099                                                 });
9100                                         }
9101                                 }
9102                                 return;
9103                         }
9104                         _ => {}
9105                 }
9106
9107                 if msg.channel_id.is_zero() {
9108                         let channel_ids: Vec<ChannelId> = {
9109                                 let per_peer_state = self.per_peer_state.read().unwrap();
9110                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9111                                 if peer_state_mutex_opt.is_none() { return; }
9112                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9113                                 let peer_state = &mut *peer_state_lock;
9114                                 // Note that we don't bother generating any events for pre-accept channels -
9115                                 // they're not considered "channels" yet from the PoV of our events interface.
9116                                 peer_state.inbound_channel_request_by_id.clear();
9117                                 peer_state.channel_by_id.keys().cloned().collect()
9118                         };
9119                         for channel_id in channel_ids {
9120                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9121                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
9122                         }
9123                 } else {
9124                         {
9125                                 // First check if we can advance the channel type and try again.
9126                                 let per_peer_state = self.per_peer_state.read().unwrap();
9127                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9128                                 if peer_state_mutex_opt.is_none() { return; }
9129                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9130                                 let peer_state = &mut *peer_state_lock;
9131                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
9132                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
9133                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
9134                                                         node_id: *counterparty_node_id,
9135                                                         msg,
9136                                                 });
9137                                                 return;
9138                                         }
9139                                 }
9140                         }
9141
9142                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9143                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
9144                 }
9145         }
9146
9147         fn provided_node_features(&self) -> NodeFeatures {
9148                 provided_node_features(&self.default_configuration)
9149         }
9150
9151         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
9152                 provided_init_features(&self.default_configuration)
9153         }
9154
9155         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
9156                 Some(vec![self.chain_hash])
9157         }
9158
9159         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
9160                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9161                         "Dual-funded channels not supported".to_owned(),
9162                          msg.channel_id.clone())), *counterparty_node_id);
9163         }
9164
9165         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
9166                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9167                         "Dual-funded channels not supported".to_owned(),
9168                          msg.channel_id.clone())), *counterparty_node_id);
9169         }
9170
9171         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
9172                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9173                         "Dual-funded channels not supported".to_owned(),
9174                          msg.channel_id.clone())), *counterparty_node_id);
9175         }
9176
9177         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
9178                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9179                         "Dual-funded channels not supported".to_owned(),
9180                          msg.channel_id.clone())), *counterparty_node_id);
9181         }
9182
9183         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
9184                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9185                         "Dual-funded channels not supported".to_owned(),
9186                          msg.channel_id.clone())), *counterparty_node_id);
9187         }
9188
9189         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
9190                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9191                         "Dual-funded channels not supported".to_owned(),
9192                          msg.channel_id.clone())), *counterparty_node_id);
9193         }
9194
9195         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
9196                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9197                         "Dual-funded channels not supported".to_owned(),
9198                          msg.channel_id.clone())), *counterparty_node_id);
9199         }
9200
9201         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
9202                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9203                         "Dual-funded channels not supported".to_owned(),
9204                          msg.channel_id.clone())), *counterparty_node_id);
9205         }
9206
9207         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
9208                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9209                         "Dual-funded channels not supported".to_owned(),
9210                          msg.channel_id.clone())), *counterparty_node_id);
9211         }
9212 }
9213
9214 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9215 OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
9216 where
9217         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9218         T::Target: BroadcasterInterface,
9219         ES::Target: EntropySource,
9220         NS::Target: NodeSigner,
9221         SP::Target: SignerProvider,
9222         F::Target: FeeEstimator,
9223         R::Target: Router,
9224         L::Target: Logger,
9225 {
9226         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
9227                 let secp_ctx = &self.secp_ctx;
9228                 let expanded_key = &self.inbound_payment_key;
9229
9230                 match message {
9231                         OffersMessage::InvoiceRequest(invoice_request) => {
9232                                 let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
9233                                         &invoice_request
9234                                 ) {
9235                                         Ok(amount_msats) => amount_msats,
9236                                         Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
9237                                 };
9238                                 let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
9239                                         Ok(invoice_request) => invoice_request,
9240                                         Err(()) => {
9241                                                 let error = Bolt12SemanticError::InvalidMetadata;
9242                                                 return Some(OffersMessage::InvoiceError(error.into()));
9243                                         },
9244                                 };
9245
9246                                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9247                                 let (payment_hash, payment_secret) = match self.create_inbound_payment(
9248                                         Some(amount_msats), relative_expiry, None
9249                                 ) {
9250                                         Ok((payment_hash, payment_secret)) => (payment_hash, payment_secret),
9251                                         Err(()) => {
9252                                                 let error = Bolt12SemanticError::InvalidAmount;
9253                                                 return Some(OffersMessage::InvoiceError(error.into()));
9254                                         },
9255                                 };
9256
9257                                 let payment_paths = match self.create_blinded_payment_paths(
9258                                         amount_msats, payment_secret
9259                                 ) {
9260                                         Ok(payment_paths) => payment_paths,
9261                                         Err(()) => {
9262                                                 let error = Bolt12SemanticError::MissingPaths;
9263                                                 return Some(OffersMessage::InvoiceError(error.into()));
9264                                         },
9265                                 };
9266
9267                                 #[cfg(not(feature = "std"))]
9268                                 let created_at = Duration::from_secs(
9269                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9270                                 );
9271
9272                                 if invoice_request.keys.is_some() {
9273                                         #[cfg(feature = "std")]
9274                                         let builder = invoice_request.respond_using_derived_keys(
9275                                                 payment_paths, payment_hash
9276                                         );
9277                                         #[cfg(not(feature = "std"))]
9278                                         let builder = invoice_request.respond_using_derived_keys_no_std(
9279                                                 payment_paths, payment_hash, created_at
9280                                         );
9281                                         match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
9282                                                 Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
9283                                                 Err(error) => Some(OffersMessage::InvoiceError(error.into())),
9284                                         }
9285                                 } else {
9286                                         #[cfg(feature = "std")]
9287                                         let builder = invoice_request.respond_with(payment_paths, payment_hash);
9288                                         #[cfg(not(feature = "std"))]
9289                                         let builder = invoice_request.respond_with_no_std(
9290                                                 payment_paths, payment_hash, created_at
9291                                         );
9292                                         let response = builder.and_then(|builder| builder.allow_mpp().build())
9293                                                 .map_err(|e| OffersMessage::InvoiceError(e.into()))
9294                                                 .and_then(|invoice|
9295                                                         match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
9296                                                                 Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
9297                                                                 Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
9298                                                                                 InvoiceError::from_string("Failed signing invoice".to_string())
9299                                                                 )),
9300                                                                 Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
9301                                                                                 InvoiceError::from_string("Failed invoice signature verification".to_string())
9302                                                                 )),
9303                                                         });
9304                                         match response {
9305                                                 Ok(invoice) => Some(invoice),
9306                                                 Err(error) => Some(error),
9307                                         }
9308                                 }
9309                         },
9310                         OffersMessage::Invoice(invoice) => {
9311                                 match invoice.verify(expanded_key, secp_ctx) {
9312                                         Err(()) => {
9313                                                 Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
9314                                         },
9315                                         Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
9316                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
9317                                         },
9318                                         Ok(payment_id) => {
9319                                                 if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
9320                                                         log_trace!(self.logger, "Failed paying invoice: {:?}", e);
9321                                                         Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
9322                                                 } else {
9323                                                         None
9324                                                 }
9325                                         },
9326                                 }
9327                         },
9328                         OffersMessage::InvoiceError(invoice_error) => {
9329                                 log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
9330                                 None
9331                         },
9332                 }
9333         }
9334
9335         fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> {
9336                 core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
9337         }
9338 }
9339
9340 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
9341 /// [`ChannelManager`].
9342 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
9343         let mut node_features = provided_init_features(config).to_context();
9344         node_features.set_keysend_optional();
9345         node_features
9346 }
9347
9348 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
9349 /// [`ChannelManager`].
9350 ///
9351 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
9352 /// or not. Thus, this method is not public.
9353 #[cfg(any(feature = "_test_utils", test))]
9354 pub(crate) fn provided_bolt11_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
9355         provided_init_features(config).to_context()
9356 }
9357
9358 /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
9359 /// [`ChannelManager`].
9360 pub(crate) fn provided_bolt12_invoice_features(config: &UserConfig) -> Bolt12InvoiceFeatures {
9361         provided_init_features(config).to_context()
9362 }
9363
9364 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
9365 /// [`ChannelManager`].
9366 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
9367         provided_init_features(config).to_context()
9368 }
9369
9370 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
9371 /// [`ChannelManager`].
9372 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
9373         ChannelTypeFeatures::from_init(&provided_init_features(config))
9374 }
9375
9376 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
9377 /// [`ChannelManager`].
9378 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
9379         // Note that if new features are added here which other peers may (eventually) require, we
9380         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
9381         // [`ErroringMessageHandler`].
9382         let mut features = InitFeatures::empty();
9383         features.set_data_loss_protect_required();
9384         features.set_upfront_shutdown_script_optional();
9385         features.set_variable_length_onion_required();
9386         features.set_static_remote_key_required();
9387         features.set_payment_secret_required();
9388         features.set_basic_mpp_optional();
9389         features.set_wumbo_optional();
9390         features.set_shutdown_any_segwit_optional();
9391         features.set_channel_type_optional();
9392         features.set_scid_privacy_optional();
9393         features.set_zero_conf_optional();
9394         features.set_route_blinding_optional();
9395         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
9396                 features.set_anchors_zero_fee_htlc_tx_optional();
9397         }
9398         features
9399 }
9400
9401 const SERIALIZATION_VERSION: u8 = 1;
9402 const MIN_SERIALIZATION_VERSION: u8 = 1;
9403
9404 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
9405         (2, fee_base_msat, required),
9406         (4, fee_proportional_millionths, required),
9407         (6, cltv_expiry_delta, required),
9408 });
9409
9410 impl_writeable_tlv_based!(ChannelCounterparty, {
9411         (2, node_id, required),
9412         (4, features, required),
9413         (6, unspendable_punishment_reserve, required),
9414         (8, forwarding_info, option),
9415         (9, outbound_htlc_minimum_msat, option),
9416         (11, outbound_htlc_maximum_msat, option),
9417 });
9418
9419 impl Writeable for ChannelDetails {
9420         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9421                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9422                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9423                 let user_channel_id_low = self.user_channel_id as u64;
9424                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
9425                 write_tlv_fields!(writer, {
9426                         (1, self.inbound_scid_alias, option),
9427                         (2, self.channel_id, required),
9428                         (3, self.channel_type, option),
9429                         (4, self.counterparty, required),
9430                         (5, self.outbound_scid_alias, option),
9431                         (6, self.funding_txo, option),
9432                         (7, self.config, option),
9433                         (8, self.short_channel_id, option),
9434                         (9, self.confirmations, option),
9435                         (10, self.channel_value_satoshis, required),
9436                         (12, self.unspendable_punishment_reserve, option),
9437                         (14, user_channel_id_low, required),
9438                         (16, self.balance_msat, required),
9439                         (18, self.outbound_capacity_msat, required),
9440                         (19, self.next_outbound_htlc_limit_msat, required),
9441                         (20, self.inbound_capacity_msat, required),
9442                         (21, self.next_outbound_htlc_minimum_msat, required),
9443                         (22, self.confirmations_required, option),
9444                         (24, self.force_close_spend_delay, option),
9445                         (26, self.is_outbound, required),
9446                         (28, self.is_channel_ready, required),
9447                         (30, self.is_usable, required),
9448                         (32, self.is_public, required),
9449                         (33, self.inbound_htlc_minimum_msat, option),
9450                         (35, self.inbound_htlc_maximum_msat, option),
9451                         (37, user_channel_id_high_opt, option),
9452                         (39, self.feerate_sat_per_1000_weight, option),
9453                         (41, self.channel_shutdown_state, option),
9454                 });
9455                 Ok(())
9456         }
9457 }
9458
9459 impl Readable for ChannelDetails {
9460         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9461                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9462                         (1, inbound_scid_alias, option),
9463                         (2, channel_id, required),
9464                         (3, channel_type, option),
9465                         (4, counterparty, required),
9466                         (5, outbound_scid_alias, option),
9467                         (6, funding_txo, option),
9468                         (7, config, option),
9469                         (8, short_channel_id, option),
9470                         (9, confirmations, option),
9471                         (10, channel_value_satoshis, required),
9472                         (12, unspendable_punishment_reserve, option),
9473                         (14, user_channel_id_low, required),
9474                         (16, balance_msat, required),
9475                         (18, outbound_capacity_msat, required),
9476                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
9477                         // filled in, so we can safely unwrap it here.
9478                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
9479                         (20, inbound_capacity_msat, required),
9480                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
9481                         (22, confirmations_required, option),
9482                         (24, force_close_spend_delay, option),
9483                         (26, is_outbound, required),
9484                         (28, is_channel_ready, required),
9485                         (30, is_usable, required),
9486                         (32, is_public, required),
9487                         (33, inbound_htlc_minimum_msat, option),
9488                         (35, inbound_htlc_maximum_msat, option),
9489                         (37, user_channel_id_high_opt, option),
9490                         (39, feerate_sat_per_1000_weight, option),
9491                         (41, channel_shutdown_state, option),
9492                 });
9493
9494                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9495                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9496                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
9497                 let user_channel_id = user_channel_id_low as u128 +
9498                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
9499
9500                 Ok(Self {
9501                         inbound_scid_alias,
9502                         channel_id: channel_id.0.unwrap(),
9503                         channel_type,
9504                         counterparty: counterparty.0.unwrap(),
9505                         outbound_scid_alias,
9506                         funding_txo,
9507                         config,
9508                         short_channel_id,
9509                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
9510                         unspendable_punishment_reserve,
9511                         user_channel_id,
9512                         balance_msat: balance_msat.0.unwrap(),
9513                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
9514                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
9515                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
9516                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
9517                         confirmations_required,
9518                         confirmations,
9519                         force_close_spend_delay,
9520                         is_outbound: is_outbound.0.unwrap(),
9521                         is_channel_ready: is_channel_ready.0.unwrap(),
9522                         is_usable: is_usable.0.unwrap(),
9523                         is_public: is_public.0.unwrap(),
9524                         inbound_htlc_minimum_msat,
9525                         inbound_htlc_maximum_msat,
9526                         feerate_sat_per_1000_weight,
9527                         channel_shutdown_state,
9528                 })
9529         }
9530 }
9531
9532 impl_writeable_tlv_based!(PhantomRouteHints, {
9533         (2, channels, required_vec),
9534         (4, phantom_scid, required),
9535         (6, real_node_pubkey, required),
9536 });
9537
9538 impl_writeable_tlv_based!(BlindedForward, {
9539         (0, inbound_blinding_point, required),
9540         (1, failure, (default_value, BlindedFailure::FromIntroductionNode)),
9541 });
9542
9543 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
9544         (0, Forward) => {
9545                 (0, onion_packet, required),
9546                 (1, blinded, option),
9547                 (2, short_channel_id, required),
9548         },
9549         (1, Receive) => {
9550                 (0, payment_data, required),
9551                 (1, phantom_shared_secret, option),
9552                 (2, incoming_cltv_expiry, required),
9553                 (3, payment_metadata, option),
9554                 (5, custom_tlvs, optional_vec),
9555                 (7, requires_blinded_error, (default_value, false)),
9556         },
9557         (2, ReceiveKeysend) => {
9558                 (0, payment_preimage, required),
9559                 (2, incoming_cltv_expiry, required),
9560                 (3, payment_metadata, option),
9561                 (4, payment_data, option), // Added in 0.0.116
9562                 (5, custom_tlvs, optional_vec),
9563         },
9564 ;);
9565
9566 impl_writeable_tlv_based!(PendingHTLCInfo, {
9567         (0, routing, required),
9568         (2, incoming_shared_secret, required),
9569         (4, payment_hash, required),
9570         (6, outgoing_amt_msat, required),
9571         (8, outgoing_cltv_value, required),
9572         (9, incoming_amt_msat, option),
9573         (10, skimmed_fee_msat, option),
9574 });
9575
9576
9577 impl Writeable for HTLCFailureMsg {
9578         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9579                 match self {
9580                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9581                                 0u8.write(writer)?;
9582                                 channel_id.write(writer)?;
9583                                 htlc_id.write(writer)?;
9584                                 reason.write(writer)?;
9585                         },
9586                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9587                                 channel_id, htlc_id, sha256_of_onion, failure_code
9588                         }) => {
9589                                 1u8.write(writer)?;
9590                                 channel_id.write(writer)?;
9591                                 htlc_id.write(writer)?;
9592                                 sha256_of_onion.write(writer)?;
9593                                 failure_code.write(writer)?;
9594                         },
9595                 }
9596                 Ok(())
9597         }
9598 }
9599
9600 impl Readable for HTLCFailureMsg {
9601         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9602                 let id: u8 = Readable::read(reader)?;
9603                 match id {
9604                         0 => {
9605                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9606                                         channel_id: Readable::read(reader)?,
9607                                         htlc_id: Readable::read(reader)?,
9608                                         reason: Readable::read(reader)?,
9609                                 }))
9610                         },
9611                         1 => {
9612                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9613                                         channel_id: Readable::read(reader)?,
9614                                         htlc_id: Readable::read(reader)?,
9615                                         sha256_of_onion: Readable::read(reader)?,
9616                                         failure_code: Readable::read(reader)?,
9617                                 }))
9618                         },
9619                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9620                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9621                         // messages contained in the variants.
9622                         // In version 0.0.101, support for reading the variants with these types was added, and
9623                         // we should migrate to writing these variants when UpdateFailHTLC or
9624                         // UpdateFailMalformedHTLC get TLV fields.
9625                         2 => {
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::Relay(res))
9631                         },
9632                         3 => {
9633                                 let length: BigSize = Readable::read(reader)?;
9634                                 let mut s = FixedLengthReader::new(reader, length.0);
9635                                 let res = Readable::read(&mut s)?;
9636                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9637                                 Ok(HTLCFailureMsg::Malformed(res))
9638                         },
9639                         _ => Err(DecodeError::UnknownRequiredFeature),
9640                 }
9641         }
9642 }
9643
9644 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9645         (0, Forward),
9646         (1, Fail),
9647 );
9648
9649 impl_writeable_tlv_based_enum!(BlindedFailure,
9650         (0, FromIntroductionNode) => {},
9651         (2, FromBlindedNode) => {}, ;
9652 );
9653
9654 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9655         (0, short_channel_id, required),
9656         (1, phantom_shared_secret, option),
9657         (2, outpoint, required),
9658         (3, blinded_failure, option),
9659         (4, htlc_id, required),
9660         (6, incoming_packet_shared_secret, required),
9661         (7, user_channel_id, option),
9662 });
9663
9664 impl Writeable for ClaimableHTLC {
9665         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9666                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9667                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9668                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9669                 };
9670                 write_tlv_fields!(writer, {
9671                         (0, self.prev_hop, required),
9672                         (1, self.total_msat, required),
9673                         (2, self.value, required),
9674                         (3, self.sender_intended_value, required),
9675                         (4, payment_data, option),
9676                         (5, self.total_value_received, option),
9677                         (6, self.cltv_expiry, required),
9678                         (8, keysend_preimage, option),
9679                         (10, self.counterparty_skimmed_fee_msat, option),
9680                 });
9681                 Ok(())
9682         }
9683 }
9684
9685 impl Readable for ClaimableHTLC {
9686         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9687                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9688                         (0, prev_hop, required),
9689                         (1, total_msat, option),
9690                         (2, value_ser, required),
9691                         (3, sender_intended_value, option),
9692                         (4, payment_data_opt, option),
9693                         (5, total_value_received, option),
9694                         (6, cltv_expiry, required),
9695                         (8, keysend_preimage, option),
9696                         (10, counterparty_skimmed_fee_msat, option),
9697                 });
9698                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9699                 let value = value_ser.0.unwrap();
9700                 let onion_payload = match keysend_preimage {
9701                         Some(p) => {
9702                                 if payment_data.is_some() {
9703                                         return Err(DecodeError::InvalidValue)
9704                                 }
9705                                 if total_msat.is_none() {
9706                                         total_msat = Some(value);
9707                                 }
9708                                 OnionPayload::Spontaneous(p)
9709                         },
9710                         None => {
9711                                 if total_msat.is_none() {
9712                                         if payment_data.is_none() {
9713                                                 return Err(DecodeError::InvalidValue)
9714                                         }
9715                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9716                                 }
9717                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9718                         },
9719                 };
9720                 Ok(Self {
9721                         prev_hop: prev_hop.0.unwrap(),
9722                         timer_ticks: 0,
9723                         value,
9724                         sender_intended_value: sender_intended_value.unwrap_or(value),
9725                         total_value_received,
9726                         total_msat: total_msat.unwrap(),
9727                         onion_payload,
9728                         cltv_expiry: cltv_expiry.0.unwrap(),
9729                         counterparty_skimmed_fee_msat,
9730                 })
9731         }
9732 }
9733
9734 impl Readable for HTLCSource {
9735         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9736                 let id: u8 = Readable::read(reader)?;
9737                 match id {
9738                         0 => {
9739                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9740                                 let mut first_hop_htlc_msat: u64 = 0;
9741                                 let mut path_hops = Vec::new();
9742                                 let mut payment_id = None;
9743                                 let mut payment_params: Option<PaymentParameters> = None;
9744                                 let mut blinded_tail: Option<BlindedTail> = None;
9745                                 read_tlv_fields!(reader, {
9746                                         (0, session_priv, required),
9747                                         (1, payment_id, option),
9748                                         (2, first_hop_htlc_msat, required),
9749                                         (4, path_hops, required_vec),
9750                                         (5, payment_params, (option: ReadableArgs, 0)),
9751                                         (6, blinded_tail, option),
9752                                 });
9753                                 if payment_id.is_none() {
9754                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9755                                         // instead.
9756                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9757                                 }
9758                                 let path = Path { hops: path_hops, blinded_tail };
9759                                 if path.hops.len() == 0 {
9760                                         return Err(DecodeError::InvalidValue);
9761                                 }
9762                                 if let Some(params) = payment_params.as_mut() {
9763                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9764                                                 if final_cltv_expiry_delta == &0 {
9765                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9766                                                 }
9767                                         }
9768                                 }
9769                                 Ok(HTLCSource::OutboundRoute {
9770                                         session_priv: session_priv.0.unwrap(),
9771                                         first_hop_htlc_msat,
9772                                         path,
9773                                         payment_id: payment_id.unwrap(),
9774                                 })
9775                         }
9776                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9777                         _ => Err(DecodeError::UnknownRequiredFeature),
9778                 }
9779         }
9780 }
9781
9782 impl Writeable for HTLCSource {
9783         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9784                 match self {
9785                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9786                                 0u8.write(writer)?;
9787                                 let payment_id_opt = Some(payment_id);
9788                                 write_tlv_fields!(writer, {
9789                                         (0, session_priv, required),
9790                                         (1, payment_id_opt, option),
9791                                         (2, first_hop_htlc_msat, required),
9792                                         // 3 was previously used to write a PaymentSecret for the payment.
9793                                         (4, path.hops, required_vec),
9794                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9795                                         (6, path.blinded_tail, option),
9796                                  });
9797                         }
9798                         HTLCSource::PreviousHopData(ref field) => {
9799                                 1u8.write(writer)?;
9800                                 field.write(writer)?;
9801                         }
9802                 }
9803                 Ok(())
9804         }
9805 }
9806
9807 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9808         (0, forward_info, required),
9809         (1, prev_user_channel_id, (default_value, 0)),
9810         (2, prev_short_channel_id, required),
9811         (4, prev_htlc_id, required),
9812         (6, prev_funding_outpoint, required),
9813 });
9814
9815 impl Writeable for HTLCForwardInfo {
9816         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9817                 const FAIL_HTLC_VARIANT_ID: u8 = 1;
9818                 match self {
9819                         Self::AddHTLC(info) => {
9820                                 0u8.write(w)?;
9821                                 info.write(w)?;
9822                         },
9823                         Self::FailHTLC { htlc_id, err_packet } => {
9824                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9825                                 write_tlv_fields!(w, {
9826                                         (0, htlc_id, required),
9827                                         (2, err_packet, required),
9828                                 });
9829                         },
9830                         Self::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
9831                                 // Since this variant was added in 0.0.119, write this as `::FailHTLC` with an empty error
9832                                 // packet so older versions have something to fail back with, but serialize the real data as
9833                                 // optional TLVs for the benefit of newer versions.
9834                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9835                                 let dummy_err_packet = msgs::OnionErrorPacket { data: Vec::new() };
9836                                 write_tlv_fields!(w, {
9837                                         (0, htlc_id, required),
9838                                         (1, failure_code, required),
9839                                         (2, dummy_err_packet, required),
9840                                         (3, sha256_of_onion, required),
9841                                 });
9842                         },
9843                 }
9844                 Ok(())
9845         }
9846 }
9847
9848 impl Readable for HTLCForwardInfo {
9849         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
9850                 let id: u8 = Readable::read(r)?;
9851                 Ok(match id {
9852                         0 => Self::AddHTLC(Readable::read(r)?),
9853                         1 => {
9854                                 _init_and_read_len_prefixed_tlv_fields!(r, {
9855                                         (0, htlc_id, required),
9856                                         (1, malformed_htlc_failure_code, option),
9857                                         (2, err_packet, required),
9858                                         (3, sha256_of_onion, option),
9859                                 });
9860                                 if let Some(failure_code) = malformed_htlc_failure_code {
9861                                         Self::FailMalformedHTLC {
9862                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
9863                                                 failure_code,
9864                                                 sha256_of_onion: sha256_of_onion.ok_or(DecodeError::InvalidValue)?,
9865                                         }
9866                                 } else {
9867                                         Self::FailHTLC {
9868                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
9869                                                 err_packet: _init_tlv_based_struct_field!(err_packet, required),
9870                                         }
9871                                 }
9872                         },
9873                         _ => return Err(DecodeError::InvalidValue),
9874                 })
9875         }
9876 }
9877
9878 impl_writeable_tlv_based!(PendingInboundPayment, {
9879         (0, payment_secret, required),
9880         (2, expiry_time, required),
9881         (4, user_payment_id, required),
9882         (6, payment_preimage, required),
9883         (8, min_value_msat, required),
9884 });
9885
9886 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>
9887 where
9888         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9889         T::Target: BroadcasterInterface,
9890         ES::Target: EntropySource,
9891         NS::Target: NodeSigner,
9892         SP::Target: SignerProvider,
9893         F::Target: FeeEstimator,
9894         R::Target: Router,
9895         L::Target: Logger,
9896 {
9897         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9898                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9899
9900                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9901
9902                 self.chain_hash.write(writer)?;
9903                 {
9904                         let best_block = self.best_block.read().unwrap();
9905                         best_block.height().write(writer)?;
9906                         best_block.block_hash().write(writer)?;
9907                 }
9908
9909                 let mut serializable_peer_count: u64 = 0;
9910                 {
9911                         let per_peer_state = self.per_peer_state.read().unwrap();
9912                         let mut number_of_funded_channels = 0;
9913                         for (_, peer_state_mutex) in per_peer_state.iter() {
9914                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9915                                 let peer_state = &mut *peer_state_lock;
9916                                 if !peer_state.ok_to_remove(false) {
9917                                         serializable_peer_count += 1;
9918                                 }
9919
9920                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9921                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9922                                 ).count();
9923                         }
9924
9925                         (number_of_funded_channels as u64).write(writer)?;
9926
9927                         for (_, peer_state_mutex) in per_peer_state.iter() {
9928                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9929                                 let peer_state = &mut *peer_state_lock;
9930                                 for channel in peer_state.channel_by_id.iter().filter_map(
9931                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9932                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9933                                         } else { None }
9934                                 ) {
9935                                         channel.write(writer)?;
9936                                 }
9937                         }
9938                 }
9939
9940                 {
9941                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9942                         (forward_htlcs.len() as u64).write(writer)?;
9943                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9944                                 short_channel_id.write(writer)?;
9945                                 (pending_forwards.len() as u64).write(writer)?;
9946                                 for forward in pending_forwards {
9947                                         forward.write(writer)?;
9948                                 }
9949                         }
9950                 }
9951
9952                 let per_peer_state = self.per_peer_state.write().unwrap();
9953
9954                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9955                 let claimable_payments = self.claimable_payments.lock().unwrap();
9956                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9957
9958                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9959                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9960                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9961                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9962                         payment_hash.write(writer)?;
9963                         (payment.htlcs.len() as u64).write(writer)?;
9964                         for htlc in payment.htlcs.iter() {
9965                                 htlc.write(writer)?;
9966                         }
9967                         htlc_purposes.push(&payment.purpose);
9968                         htlc_onion_fields.push(&payment.onion_fields);
9969                 }
9970
9971                 let mut monitor_update_blocked_actions_per_peer = None;
9972                 let mut peer_states = Vec::new();
9973                 for (_, peer_state_mutex) in per_peer_state.iter() {
9974                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9975                         // of a lockorder violation deadlock - no other thread can be holding any
9976                         // per_peer_state lock at all.
9977                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9978                 }
9979
9980                 (serializable_peer_count).write(writer)?;
9981                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9982                         // Peers which we have no channels to should be dropped once disconnected. As we
9983                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9984                         // consider all peers as disconnected here. There's therefore no need write peers with
9985                         // no channels.
9986                         if !peer_state.ok_to_remove(false) {
9987                                 peer_pubkey.write(writer)?;
9988                                 peer_state.latest_features.write(writer)?;
9989                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9990                                         monitor_update_blocked_actions_per_peer
9991                                                 .get_or_insert_with(Vec::new)
9992                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9993                                 }
9994                         }
9995                 }
9996
9997                 let events = self.pending_events.lock().unwrap();
9998                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9999                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
10000                 // refuse to read the new ChannelManager.
10001                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
10002                 if events_not_backwards_compatible {
10003                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
10004                         // well save the space and not write any events here.
10005                         0u64.write(writer)?;
10006                 } else {
10007                         (events.len() as u64).write(writer)?;
10008                         for (event, _) in events.iter() {
10009                                 event.write(writer)?;
10010                         }
10011                 }
10012
10013                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
10014                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
10015                 // the closing monitor updates were always effectively replayed on startup (either directly
10016                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
10017                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
10018                 0u64.write(writer)?;
10019
10020                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
10021                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
10022                 // likely to be identical.
10023                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10024                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10025
10026                 (pending_inbound_payments.len() as u64).write(writer)?;
10027                 for (hash, pending_payment) in pending_inbound_payments.iter() {
10028                         hash.write(writer)?;
10029                         pending_payment.write(writer)?;
10030                 }
10031
10032                 // For backwards compat, write the session privs and their total length.
10033                 let mut num_pending_outbounds_compat: u64 = 0;
10034                 for (_, outbound) in pending_outbound_payments.iter() {
10035                         if !outbound.is_fulfilled() && !outbound.abandoned() {
10036                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
10037                         }
10038                 }
10039                 num_pending_outbounds_compat.write(writer)?;
10040                 for (_, outbound) in pending_outbound_payments.iter() {
10041                         match outbound {
10042                                 PendingOutboundPayment::Legacy { session_privs } |
10043                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10044                                         for session_priv in session_privs.iter() {
10045                                                 session_priv.write(writer)?;
10046                                         }
10047                                 }
10048                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
10049                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
10050                                 PendingOutboundPayment::Fulfilled { .. } => {},
10051                                 PendingOutboundPayment::Abandoned { .. } => {},
10052                         }
10053                 }
10054
10055                 // Encode without retry info for 0.0.101 compatibility.
10056                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
10057                 for (id, outbound) in pending_outbound_payments.iter() {
10058                         match outbound {
10059                                 PendingOutboundPayment::Legacy { session_privs } |
10060                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10061                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
10062                                 },
10063                                 _ => {},
10064                         }
10065                 }
10066
10067                 let mut pending_intercepted_htlcs = None;
10068                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
10069                 if our_pending_intercepts.len() != 0 {
10070                         pending_intercepted_htlcs = Some(our_pending_intercepts);
10071                 }
10072
10073                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
10074                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
10075                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
10076                         // map. Thus, if there are no entries we skip writing a TLV for it.
10077                         pending_claiming_payments = None;
10078                 }
10079
10080                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
10081                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
10082                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
10083                                 if !updates.is_empty() {
10084                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
10085                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
10086                                 }
10087                         }
10088                 }
10089
10090                 write_tlv_fields!(writer, {
10091                         (1, pending_outbound_payments_no_retry, required),
10092                         (2, pending_intercepted_htlcs, option),
10093                         (3, pending_outbound_payments, required),
10094                         (4, pending_claiming_payments, option),
10095                         (5, self.our_network_pubkey, required),
10096                         (6, monitor_update_blocked_actions_per_peer, option),
10097                         (7, self.fake_scid_rand_bytes, required),
10098                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
10099                         (9, htlc_purposes, required_vec),
10100                         (10, in_flight_monitor_updates, option),
10101                         (11, self.probing_cookie_secret, required),
10102                         (13, htlc_onion_fields, optional_vec),
10103                 });
10104
10105                 Ok(())
10106         }
10107 }
10108
10109 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
10110         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
10111                 (self.len() as u64).write(w)?;
10112                 for (event, action) in self.iter() {
10113                         event.write(w)?;
10114                         action.write(w)?;
10115                         #[cfg(debug_assertions)] {
10116                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
10117                                 // be persisted and are regenerated on restart. However, if such an event has a
10118                                 // post-event-handling action we'll write nothing for the event and would have to
10119                                 // either forget the action or fail on deserialization (which we do below). Thus,
10120                                 // check that the event is sane here.
10121                                 let event_encoded = event.encode();
10122                                 let event_read: Option<Event> =
10123                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
10124                                 if action.is_some() { assert!(event_read.is_some()); }
10125                         }
10126                 }
10127                 Ok(())
10128         }
10129 }
10130 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
10131         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
10132                 let len: u64 = Readable::read(reader)?;
10133                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
10134                 let mut events: Self = VecDeque::with_capacity(cmp::min(
10135                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
10136                         len) as usize);
10137                 for _ in 0..len {
10138                         let ev_opt = MaybeReadable::read(reader)?;
10139                         let action = Readable::read(reader)?;
10140                         if let Some(ev) = ev_opt {
10141                                 events.push_back((ev, action));
10142                         } else if action.is_some() {
10143                                 return Err(DecodeError::InvalidValue);
10144                         }
10145                 }
10146                 Ok(events)
10147         }
10148 }
10149
10150 impl_writeable_tlv_based_enum!(ChannelShutdownState,
10151         (0, NotShuttingDown) => {},
10152         (2, ShutdownInitiated) => {},
10153         (4, ResolvingHTLCs) => {},
10154         (6, NegotiatingClosingFee) => {},
10155         (8, ShutdownComplete) => {}, ;
10156 );
10157
10158 /// Arguments for the creation of a ChannelManager that are not deserialized.
10159 ///
10160 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
10161 /// is:
10162 /// 1) Deserialize all stored [`ChannelMonitor`]s.
10163 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
10164 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
10165 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
10166 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
10167 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
10168 ///    same way you would handle a [`chain::Filter`] call using
10169 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
10170 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
10171 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
10172 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
10173 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
10174 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
10175 ///    the next step.
10176 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
10177 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
10178 ///
10179 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
10180 /// call any other methods on the newly-deserialized [`ChannelManager`].
10181 ///
10182 /// Note that because some channels may be closed during deserialization, it is critical that you
10183 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
10184 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
10185 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
10186 /// not force-close the same channels but consider them live), you may end up revoking a state for
10187 /// which you've already broadcasted the transaction.
10188 ///
10189 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
10190 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10191 where
10192         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10193         T::Target: BroadcasterInterface,
10194         ES::Target: EntropySource,
10195         NS::Target: NodeSigner,
10196         SP::Target: SignerProvider,
10197         F::Target: FeeEstimator,
10198         R::Target: Router,
10199         L::Target: Logger,
10200 {
10201         /// A cryptographically secure source of entropy.
10202         pub entropy_source: ES,
10203
10204         /// A signer that is able to perform node-scoped cryptographic operations.
10205         pub node_signer: NS,
10206
10207         /// The keys provider which will give us relevant keys. Some keys will be loaded during
10208         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
10209         /// signing data.
10210         pub signer_provider: SP,
10211
10212         /// The fee_estimator for use in the ChannelManager in the future.
10213         ///
10214         /// No calls to the FeeEstimator will be made during deserialization.
10215         pub fee_estimator: F,
10216         /// The chain::Watch for use in the ChannelManager in the future.
10217         ///
10218         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
10219         /// you have deserialized ChannelMonitors separately and will add them to your
10220         /// chain::Watch after deserializing this ChannelManager.
10221         pub chain_monitor: M,
10222
10223         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
10224         /// used to broadcast the latest local commitment transactions of channels which must be
10225         /// force-closed during deserialization.
10226         pub tx_broadcaster: T,
10227         /// The router which will be used in the ChannelManager in the future for finding routes
10228         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
10229         ///
10230         /// No calls to the router will be made during deserialization.
10231         pub router: R,
10232         /// The Logger for use in the ChannelManager and which may be used to log information during
10233         /// deserialization.
10234         pub logger: L,
10235         /// Default settings used for new channels. Any existing channels will continue to use the
10236         /// runtime settings which were stored when the ChannelManager was serialized.
10237         pub default_config: UserConfig,
10238
10239         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
10240         /// value.context.get_funding_txo() should be the key).
10241         ///
10242         /// If a monitor is inconsistent with the channel state during deserialization the channel will
10243         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
10244         /// is true for missing channels as well. If there is a monitor missing for which we find
10245         /// channel data Err(DecodeError::InvalidValue) will be returned.
10246         ///
10247         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
10248         /// this struct.
10249         ///
10250         /// This is not exported to bindings users because we have no HashMap bindings
10251         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>,
10252 }
10253
10254 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10255                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
10256 where
10257         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10258         T::Target: BroadcasterInterface,
10259         ES::Target: EntropySource,
10260         NS::Target: NodeSigner,
10261         SP::Target: SignerProvider,
10262         F::Target: FeeEstimator,
10263         R::Target: Router,
10264         L::Target: Logger,
10265 {
10266         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
10267         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
10268         /// populate a HashMap directly from C.
10269         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,
10270                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>) -> Self {
10271                 Self {
10272                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
10273                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
10274                 }
10275         }
10276 }
10277
10278 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
10279 // SipmleArcChannelManager type:
10280 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10281         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
10282 where
10283         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10284         T::Target: BroadcasterInterface,
10285         ES::Target: EntropySource,
10286         NS::Target: NodeSigner,
10287         SP::Target: SignerProvider,
10288         F::Target: FeeEstimator,
10289         R::Target: Router,
10290         L::Target: Logger,
10291 {
10292         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10293                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
10294                 Ok((blockhash, Arc::new(chan_manager)))
10295         }
10296 }
10297
10298 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10299         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
10300 where
10301         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10302         T::Target: BroadcasterInterface,
10303         ES::Target: EntropySource,
10304         NS::Target: NodeSigner,
10305         SP::Target: SignerProvider,
10306         F::Target: FeeEstimator,
10307         R::Target: Router,
10308         L::Target: Logger,
10309 {
10310         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10311                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
10312
10313                 let chain_hash: ChainHash = Readable::read(reader)?;
10314                 let best_block_height: u32 = Readable::read(reader)?;
10315                 let best_block_hash: BlockHash = Readable::read(reader)?;
10316
10317                 let mut failed_htlcs = Vec::new();
10318
10319                 let channel_count: u64 = Readable::read(reader)?;
10320                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
10321                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10322                 let mut outpoint_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10323                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10324                 let mut channel_closures = VecDeque::new();
10325                 let mut close_background_events = Vec::new();
10326                 for _ in 0..channel_count {
10327                         let mut channel: Channel<SP> = Channel::read(reader, (
10328                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
10329                         ))?;
10330                         let logger = WithChannelContext::from(&args.logger, &channel.context);
10331                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10332                         funding_txo_set.insert(funding_txo.clone());
10333                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10334                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
10335                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
10336                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
10337                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10338                                         // But if the channel is behind of the monitor, close the channel:
10339                                         log_error!(logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
10340                                         log_error!(logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
10341                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10342                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
10343                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
10344                                         }
10345                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
10346                                                 log_error!(logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
10347                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
10348                                         }
10349                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
10350                                                 log_error!(logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
10351                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
10352                                         }
10353                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
10354                                                 log_error!(logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
10355                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
10356                                         }
10357                                         let mut shutdown_result = channel.context.force_shutdown(true, ClosureReason::OutdatedChannelManager);
10358                                         if shutdown_result.unbroadcasted_batch_funding_txid.is_some() {
10359                                                 return Err(DecodeError::InvalidValue);
10360                                         }
10361                                         if let Some((counterparty_node_id, funding_txo, update)) = shutdown_result.monitor_update {
10362                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10363                                                         counterparty_node_id, funding_txo, update
10364                                                 });
10365                                         }
10366                                         failed_htlcs.append(&mut shutdown_result.dropped_outbound_htlcs);
10367                                         channel_closures.push_back((events::Event::ChannelClosed {
10368                                                 channel_id: channel.context.channel_id(),
10369                                                 user_channel_id: channel.context.get_user_id(),
10370                                                 reason: ClosureReason::OutdatedChannelManager,
10371                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10372                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10373                                                 channel_funding_txo: channel.context.get_funding_txo(),
10374                                         }, None));
10375                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
10376                                                 let mut found_htlc = false;
10377                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
10378                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
10379                                                 }
10380                                                 if !found_htlc {
10381                                                         // If we have some HTLCs in the channel which are not present in the newer
10382                                                         // ChannelMonitor, they have been removed and should be failed back to
10383                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
10384                                                         // were actually claimed we'd have generated and ensured the previous-hop
10385                                                         // claim update ChannelMonitor updates were persisted prior to persising
10386                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
10387                                                         // backwards leg of the HTLC will simply be rejected.
10388                                                         log_info!(logger,
10389                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
10390                                                                 &channel.context.channel_id(), &payment_hash);
10391                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10392                                                 }
10393                                         }
10394                                 } else {
10395                                         log_info!(logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
10396                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
10397                                                 monitor.get_latest_update_id());
10398                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
10399                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10400                                         }
10401                                         if let Some(funding_txo) = channel.context.get_funding_txo() {
10402                                                 outpoint_to_peer.insert(funding_txo, channel.context.get_counterparty_node_id());
10403                                         }
10404                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
10405                                                 hash_map::Entry::Occupied(mut entry) => {
10406                                                         let by_id_map = entry.get_mut();
10407                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10408                                                 },
10409                                                 hash_map::Entry::Vacant(entry) => {
10410                                                         let mut by_id_map = HashMap::new();
10411                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10412                                                         entry.insert(by_id_map);
10413                                                 }
10414                                         }
10415                                 }
10416                         } else if channel.is_awaiting_initial_mon_persist() {
10417                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
10418                                 // was in-progress, we never broadcasted the funding transaction and can still
10419                                 // safely discard the channel.
10420                                 let _ = channel.context.force_shutdown(false, ClosureReason::DisconnectedPeer);
10421                                 channel_closures.push_back((events::Event::ChannelClosed {
10422                                         channel_id: channel.context.channel_id(),
10423                                         user_channel_id: channel.context.get_user_id(),
10424                                         reason: ClosureReason::DisconnectedPeer,
10425                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10426                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10427                                         channel_funding_txo: channel.context.get_funding_txo(),
10428                                 }, None));
10429                         } else {
10430                                 log_error!(logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
10431                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10432                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10433                                 log_error!(logger, " Without the ChannelMonitor we cannot continue without risking funds.");
10434                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10435                                 return Err(DecodeError::InvalidValue);
10436                         }
10437                 }
10438
10439                 for (funding_txo, monitor) in args.channel_monitors.iter() {
10440                         if !funding_txo_set.contains(funding_txo) {
10441                                 let logger = WithChannelMonitor::from(&args.logger, monitor);
10442                                 log_info!(logger, "Queueing monitor update to ensure missing channel {} is force closed",
10443                                         &funding_txo.to_channel_id());
10444                                 let monitor_update = ChannelMonitorUpdate {
10445                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
10446                                         counterparty_node_id: None,
10447                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
10448                                 };
10449                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
10450                         }
10451                 }
10452
10453                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
10454                 let forward_htlcs_count: u64 = Readable::read(reader)?;
10455                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
10456                 for _ in 0..forward_htlcs_count {
10457                         let short_channel_id = Readable::read(reader)?;
10458                         let pending_forwards_count: u64 = Readable::read(reader)?;
10459                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
10460                         for _ in 0..pending_forwards_count {
10461                                 pending_forwards.push(Readable::read(reader)?);
10462                         }
10463                         forward_htlcs.insert(short_channel_id, pending_forwards);
10464                 }
10465
10466                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
10467                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
10468                 for _ in 0..claimable_htlcs_count {
10469                         let payment_hash = Readable::read(reader)?;
10470                         let previous_hops_len: u64 = Readable::read(reader)?;
10471                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
10472                         for _ in 0..previous_hops_len {
10473                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
10474                         }
10475                         claimable_htlcs_list.push((payment_hash, previous_hops));
10476                 }
10477
10478                 let peer_state_from_chans = |channel_by_id| {
10479                         PeerState {
10480                                 channel_by_id,
10481                                 inbound_channel_request_by_id: HashMap::new(),
10482                                 latest_features: InitFeatures::empty(),
10483                                 pending_msg_events: Vec::new(),
10484                                 in_flight_monitor_updates: BTreeMap::new(),
10485                                 monitor_update_blocked_actions: BTreeMap::new(),
10486                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
10487                                 is_connected: false,
10488                         }
10489                 };
10490
10491                 let peer_count: u64 = Readable::read(reader)?;
10492                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
10493                 for _ in 0..peer_count {
10494                         let peer_pubkey = Readable::read(reader)?;
10495                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
10496                         let mut peer_state = peer_state_from_chans(peer_chans);
10497                         peer_state.latest_features = Readable::read(reader)?;
10498                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
10499                 }
10500
10501                 let event_count: u64 = Readable::read(reader)?;
10502                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
10503                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
10504                 for _ in 0..event_count {
10505                         match MaybeReadable::read(reader)? {
10506                                 Some(event) => pending_events_read.push_back((event, None)),
10507                                 None => continue,
10508                         }
10509                 }
10510
10511                 let background_event_count: u64 = Readable::read(reader)?;
10512                 for _ in 0..background_event_count {
10513                         match <u8 as Readable>::read(reader)? {
10514                                 0 => {
10515                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
10516                                         // however we really don't (and never did) need them - we regenerate all
10517                                         // on-startup monitor updates.
10518                                         let _: OutPoint = Readable::read(reader)?;
10519                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
10520                                 }
10521                                 _ => return Err(DecodeError::InvalidValue),
10522                         }
10523                 }
10524
10525                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
10526                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
10527
10528                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
10529                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
10530                 for _ in 0..pending_inbound_payment_count {
10531                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
10532                                 return Err(DecodeError::InvalidValue);
10533                         }
10534                 }
10535
10536                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
10537                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
10538                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
10539                 for _ in 0..pending_outbound_payments_count_compat {
10540                         let session_priv = Readable::read(reader)?;
10541                         let payment = PendingOutboundPayment::Legacy {
10542                                 session_privs: [session_priv].iter().cloned().collect()
10543                         };
10544                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
10545                                 return Err(DecodeError::InvalidValue)
10546                         };
10547                 }
10548
10549                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
10550                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
10551                 let mut pending_outbound_payments = None;
10552                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
10553                 let mut received_network_pubkey: Option<PublicKey> = None;
10554                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
10555                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
10556                 let mut claimable_htlc_purposes = None;
10557                 let mut claimable_htlc_onion_fields = None;
10558                 let mut pending_claiming_payments = Some(HashMap::new());
10559                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
10560                 let mut events_override = None;
10561                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
10562                 read_tlv_fields!(reader, {
10563                         (1, pending_outbound_payments_no_retry, option),
10564                         (2, pending_intercepted_htlcs, option),
10565                         (3, pending_outbound_payments, option),
10566                         (4, pending_claiming_payments, option),
10567                         (5, received_network_pubkey, option),
10568                         (6, monitor_update_blocked_actions_per_peer, option),
10569                         (7, fake_scid_rand_bytes, option),
10570                         (8, events_override, option),
10571                         (9, claimable_htlc_purposes, optional_vec),
10572                         (10, in_flight_monitor_updates, option),
10573                         (11, probing_cookie_secret, option),
10574                         (13, claimable_htlc_onion_fields, optional_vec),
10575                 });
10576                 if fake_scid_rand_bytes.is_none() {
10577                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
10578                 }
10579
10580                 if probing_cookie_secret.is_none() {
10581                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
10582                 }
10583
10584                 if let Some(events) = events_override {
10585                         pending_events_read = events;
10586                 }
10587
10588                 if !channel_closures.is_empty() {
10589                         pending_events_read.append(&mut channel_closures);
10590                 }
10591
10592                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
10593                         pending_outbound_payments = Some(pending_outbound_payments_compat);
10594                 } else if pending_outbound_payments.is_none() {
10595                         let mut outbounds = HashMap::new();
10596                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
10597                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
10598                         }
10599                         pending_outbound_payments = Some(outbounds);
10600                 }
10601                 let pending_outbounds = OutboundPayments {
10602                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
10603                         retry_lock: Mutex::new(())
10604                 };
10605
10606                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
10607                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
10608                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
10609                 // replayed, and for each monitor update we have to replay we have to ensure there's a
10610                 // `ChannelMonitor` for it.
10611                 //
10612                 // In order to do so we first walk all of our live channels (so that we can check their
10613                 // state immediately after doing the update replays, when we have the `update_id`s
10614                 // available) and then walk any remaining in-flight updates.
10615                 //
10616                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10617                 let mut pending_background_events = Vec::new();
10618                 macro_rules! handle_in_flight_updates {
10619                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10620                          $monitor: expr, $peer_state: expr, $logger: expr, $channel_info_log: expr
10621                         ) => { {
10622                                 let mut max_in_flight_update_id = 0;
10623                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10624                                 for update in $chan_in_flight_upds.iter() {
10625                                         log_trace!($logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10626                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
10627                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10628                                         pending_background_events.push(
10629                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10630                                                         counterparty_node_id: $counterparty_node_id,
10631                                                         funding_txo: $funding_txo,
10632                                                         update: update.clone(),
10633                                                 });
10634                                 }
10635                                 if $chan_in_flight_upds.is_empty() {
10636                                         // We had some updates to apply, but it turns out they had completed before we
10637                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10638                                         // the completion actions for any monitor updates, but otherwise are done.
10639                                         pending_background_events.push(
10640                                                 BackgroundEvent::MonitorUpdatesComplete {
10641                                                         counterparty_node_id: $counterparty_node_id,
10642                                                         channel_id: $funding_txo.to_channel_id(),
10643                                                 });
10644                                 }
10645                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10646                                         log_error!($logger, "Duplicate in-flight monitor update set for the same channel!");
10647                                         return Err(DecodeError::InvalidValue);
10648                                 }
10649                                 max_in_flight_update_id
10650                         } }
10651                 }
10652
10653                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10654                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10655                         let peer_state = &mut *peer_state_lock;
10656                         for phase in peer_state.channel_by_id.values() {
10657                                 if let ChannelPhase::Funded(chan) = phase {
10658                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10659
10660                                         // Channels that were persisted have to be funded, otherwise they should have been
10661                                         // discarded.
10662                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10663                                         let monitor = args.channel_monitors.get(&funding_txo)
10664                                                 .expect("We already checked for monitor presence when loading channels");
10665                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10666                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10667                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10668                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10669                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10670                                                                         funding_txo, monitor, peer_state, logger, ""));
10671                                                 }
10672                                         }
10673                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10674                                                 // If the channel is ahead of the monitor, return InvalidValue:
10675                                                 log_error!(logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10676                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10677                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10678                                                 log_error!(logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10679                                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10680                                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10681                                                 log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10682                                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10683                                                 return Err(DecodeError::InvalidValue);
10684                                         }
10685                                 } else {
10686                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10687                                         // created in this `channel_by_id` map.
10688                                         debug_assert!(false);
10689                                         return Err(DecodeError::InvalidValue);
10690                                 }
10691                         }
10692                 }
10693
10694                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10695                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10696                                 let logger = WithContext::from(&args.logger, Some(counterparty_id), Some(funding_txo.to_channel_id()));
10697                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10698                                         // Now that we've removed all the in-flight monitor updates for channels that are
10699                                         // still open, we need to replay any monitor updates that are for closed channels,
10700                                         // creating the neccessary peer_state entries as we go.
10701                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10702                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
10703                                         });
10704                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10705                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10706                                                 funding_txo, monitor, peer_state, logger, "closed ");
10707                                 } else {
10708                                         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!");
10709                                         log_error!(logger, " The ChannelMonitor for channel {} is missing.",
10710                                                 &funding_txo.to_channel_id());
10711                                         log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10712                                         log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10713                                         log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10714                                         log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10715                                         return Err(DecodeError::InvalidValue);
10716                                 }
10717                         }
10718                 }
10719
10720                 // Note that we have to do the above replays before we push new monitor updates.
10721                 pending_background_events.append(&mut close_background_events);
10722
10723                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10724                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10725                 // have a fully-constructed `ChannelManager` at the end.
10726                 let mut pending_claims_to_replay = Vec::new();
10727
10728                 {
10729                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10730                         // ChannelMonitor data for any channels for which we do not have authorative state
10731                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10732                         // corresponding `Channel` at all).
10733                         // This avoids several edge-cases where we would otherwise "forget" about pending
10734                         // payments which are still in-flight via their on-chain state.
10735                         // We only rebuild the pending payments map if we were most recently serialized by
10736                         // 0.0.102+
10737                         for (_, monitor) in args.channel_monitors.iter() {
10738                                 let counterparty_opt = outpoint_to_peer.get(&monitor.get_funding_txo().0);
10739                                 if counterparty_opt.is_none() {
10740                                         let logger = WithChannelMonitor::from(&args.logger, monitor);
10741                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10742                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10743                                                         if path.hops.is_empty() {
10744                                                                 log_error!(logger, "Got an empty path for a pending payment");
10745                                                                 return Err(DecodeError::InvalidValue);
10746                                                         }
10747
10748                                                         let path_amt = path.final_value_msat();
10749                                                         let mut session_priv_bytes = [0; 32];
10750                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10751                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10752                                                                 hash_map::Entry::Occupied(mut entry) => {
10753                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10754                                                                         log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10755                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), htlc.payment_hash);
10756                                                                 },
10757                                                                 hash_map::Entry::Vacant(entry) => {
10758                                                                         let path_fee = path.fee_msat();
10759                                                                         entry.insert(PendingOutboundPayment::Retryable {
10760                                                                                 retry_strategy: None,
10761                                                                                 attempts: PaymentAttempts::new(),
10762                                                                                 payment_params: None,
10763                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
10764                                                                                 payment_hash: htlc.payment_hash,
10765                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10766                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10767                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10768                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10769                                                                                 pending_amt_msat: path_amt,
10770                                                                                 pending_fee_msat: Some(path_fee),
10771                                                                                 total_msat: path_amt,
10772                                                                                 starting_block_height: best_block_height,
10773                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10774                                                                         });
10775                                                                         log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10776                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10777                                                                 }
10778                                                         }
10779                                                 }
10780                                         }
10781                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10782                                                 match htlc_source {
10783                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10784                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10785                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10786                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10787                                                                 };
10788                                                                 // The ChannelMonitor is now responsible for this HTLC's
10789                                                                 // failure/success and will let us know what its outcome is. If we
10790                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10791                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10792                                                                 // the monitor was when forwarding the payment.
10793                                                                 forward_htlcs.retain(|_, forwards| {
10794                                                                         forwards.retain(|forward| {
10795                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10796                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10797                                                                                                 log_info!(logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10798                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10799                                                                                                 false
10800                                                                                         } else { true }
10801                                                                                 } else { true }
10802                                                                         });
10803                                                                         !forwards.is_empty()
10804                                                                 });
10805                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10806                                                                         if pending_forward_matches_htlc(&htlc_info) {
10807                                                                                 log_info!(logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10808                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10809                                                                                 pending_events_read.retain(|(event, _)| {
10810                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10811                                                                                                 intercepted_id != ev_id
10812                                                                                         } else { true }
10813                                                                                 });
10814                                                                                 false
10815                                                                         } else { true }
10816                                                                 });
10817                                                         },
10818                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10819                                                                 if let Some(preimage) = preimage_opt {
10820                                                                         let pending_events = Mutex::new(pending_events_read);
10821                                                                         // Note that we set `from_onchain` to "false" here,
10822                                                                         // deliberately keeping the pending payment around forever.
10823                                                                         // Given it should only occur when we have a channel we're
10824                                                                         // force-closing for being stale that's okay.
10825                                                                         // The alternative would be to wipe the state when claiming,
10826                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10827                                                                         // it and the `PaymentSent` on every restart until the
10828                                                                         // `ChannelMonitor` is removed.
10829                                                                         let compl_action =
10830                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10831                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10832                                                                                         counterparty_node_id: path.hops[0].pubkey,
10833                                                                                 };
10834                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10835                                                                                 path, false, compl_action, &pending_events, &&logger);
10836                                                                         pending_events_read = pending_events.into_inner().unwrap();
10837                                                                 }
10838                                                         },
10839                                                 }
10840                                         }
10841                                 }
10842
10843                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10844                                 // preimages from it which may be needed in upstream channels for forwarded
10845                                 // payments.
10846                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10847                                         .into_iter()
10848                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10849                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10850                                                         if let Some(payment_preimage) = preimage_opt {
10851                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10852                                                                         // Check if `counterparty_opt.is_none()` to see if the
10853                                                                         // downstream chan is closed (because we don't have a
10854                                                                         // channel_id -> peer map entry).
10855                                                                         counterparty_opt.is_none(),
10856                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10857                                                                         monitor.get_funding_txo().0))
10858                                                         } else { None }
10859                                                 } else {
10860                                                         // If it was an outbound payment, we've handled it above - if a preimage
10861                                                         // came in and we persisted the `ChannelManager` we either handled it and
10862                                                         // are good to go or the channel force-closed - we don't have to handle the
10863                                                         // channel still live case here.
10864                                                         None
10865                                                 }
10866                                         });
10867                                 for tuple in outbound_claimed_htlcs_iter {
10868                                         pending_claims_to_replay.push(tuple);
10869                                 }
10870                         }
10871                 }
10872
10873                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10874                         // If we have pending HTLCs to forward, assume we either dropped a
10875                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10876                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10877                         // constant as enough time has likely passed that we should simply handle the forwards
10878                         // now, or at least after the user gets a chance to reconnect to our peers.
10879                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10880                                 time_forwardable: Duration::from_secs(2),
10881                         }, None));
10882                 }
10883
10884                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10885                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10886
10887                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10888                 if let Some(purposes) = claimable_htlc_purposes {
10889                         if purposes.len() != claimable_htlcs_list.len() {
10890                                 return Err(DecodeError::InvalidValue);
10891                         }
10892                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10893                                 if onion_fields.len() != claimable_htlcs_list.len() {
10894                                         return Err(DecodeError::InvalidValue);
10895                                 }
10896                                 for (purpose, (onion, (payment_hash, htlcs))) in
10897                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10898                                 {
10899                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10900                                                 purpose, htlcs, onion_fields: onion,
10901                                         });
10902                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10903                                 }
10904                         } else {
10905                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10906                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10907                                                 purpose, htlcs, onion_fields: None,
10908                                         });
10909                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10910                                 }
10911                         }
10912                 } else {
10913                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10914                         // include a `_legacy_hop_data` in the `OnionPayload`.
10915                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10916                                 if htlcs.is_empty() {
10917                                         return Err(DecodeError::InvalidValue);
10918                                 }
10919                                 let purpose = match &htlcs[0].onion_payload {
10920                                         OnionPayload::Invoice { _legacy_hop_data } => {
10921                                                 if let Some(hop_data) = _legacy_hop_data {
10922                                                         events::PaymentPurpose::InvoicePayment {
10923                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10924                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10925                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10926                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10927                                                                                 Err(()) => {
10928                                                                                         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);
10929                                                                                         return Err(DecodeError::InvalidValue);
10930                                                                                 }
10931                                                                         }
10932                                                                 },
10933                                                                 payment_secret: hop_data.payment_secret,
10934                                                         }
10935                                                 } else { return Err(DecodeError::InvalidValue); }
10936                                         },
10937                                         OnionPayload::Spontaneous(payment_preimage) =>
10938                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10939                                 };
10940                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10941                                         purpose, htlcs, onion_fields: None,
10942                                 });
10943                         }
10944                 }
10945
10946                 let mut secp_ctx = Secp256k1::new();
10947                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10948
10949                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10950                         Ok(key) => key,
10951                         Err(()) => return Err(DecodeError::InvalidValue)
10952                 };
10953                 if let Some(network_pubkey) = received_network_pubkey {
10954                         if network_pubkey != our_network_pubkey {
10955                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10956                                 return Err(DecodeError::InvalidValue);
10957                         }
10958                 }
10959
10960                 let mut outbound_scid_aliases = HashSet::new();
10961                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10962                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10963                         let peer_state = &mut *peer_state_lock;
10964                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10965                                 if let ChannelPhase::Funded(chan) = phase {
10966                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10967                                         if chan.context.outbound_scid_alias() == 0 {
10968                                                 let mut outbound_scid_alias;
10969                                                 loop {
10970                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10971                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10972                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10973                                                 }
10974                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10975                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
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                                         if chan.context.is_usable() {
10982                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10983                                                         // Note that in rare cases its possible to hit this while reading an older
10984                                                         // channel if we just happened to pick a colliding outbound alias above.
10985                                                         log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10986                                                         return Err(DecodeError::InvalidValue);
10987                                                 }
10988                                         }
10989                                 } else {
10990                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10991                                         // created in this `channel_by_id` map.
10992                                         debug_assert!(false);
10993                                         return Err(DecodeError::InvalidValue);
10994                                 }
10995                         }
10996                 }
10997
10998                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10999
11000                 for (_, monitor) in args.channel_monitors.iter() {
11001                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
11002                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
11003                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
11004                                         let mut claimable_amt_msat = 0;
11005                                         let mut receiver_node_id = Some(our_network_pubkey);
11006                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
11007                                         if phantom_shared_secret.is_some() {
11008                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
11009                                                         .expect("Failed to get node_id for phantom node recipient");
11010                                                 receiver_node_id = Some(phantom_pubkey)
11011                                         }
11012                                         for claimable_htlc in &payment.htlcs {
11013                                                 claimable_amt_msat += claimable_htlc.value;
11014
11015                                                 // Add a holding-cell claim of the payment to the Channel, which should be
11016                                                 // applied ~immediately on peer reconnection. Because it won't generate a
11017                                                 // new commitment transaction we can just provide the payment preimage to
11018                                                 // the corresponding ChannelMonitor and nothing else.
11019                                                 //
11020                                                 // We do so directly instead of via the normal ChannelMonitor update
11021                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
11022                                                 // we're not allowed to call it directly yet. Further, we do the update
11023                                                 // without incrementing the ChannelMonitor update ID as there isn't any
11024                                                 // reason to.
11025                                                 // If we were to generate a new ChannelMonitor update ID here and then
11026                                                 // crash before the user finishes block connect we'd end up force-closing
11027                                                 // this channel as well. On the flip side, there's no harm in restarting
11028                                                 // without the new monitor persisted - we'll end up right back here on
11029                                                 // restart.
11030                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
11031                                                 if let Some(peer_node_id) = outpoint_to_peer.get(&claimable_htlc.prev_hop.outpoint) {
11032                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
11033                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
11034                                                         let peer_state = &mut *peer_state_lock;
11035                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
11036                                                                 let logger = WithChannelContext::from(&args.logger, &channel.context);
11037                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &&logger);
11038                                                         }
11039                                                 }
11040                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
11041                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
11042                                                 }
11043                                         }
11044                                         pending_events_read.push_back((events::Event::PaymentClaimed {
11045                                                 receiver_node_id,
11046                                                 payment_hash,
11047                                                 purpose: payment.purpose,
11048                                                 amount_msat: claimable_amt_msat,
11049                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
11050                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
11051                                         }, None));
11052                                 }
11053                         }
11054                 }
11055
11056                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
11057                         if let Some(peer_state) = per_peer_state.get(&node_id) {
11058                                 for (channel_id, actions) in monitor_update_blocked_actions.iter() {
11059                                         let logger = WithContext::from(&args.logger, Some(node_id), Some(*channel_id));
11060                                         for action in actions.iter() {
11061                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
11062                                                         downstream_counterparty_and_funding_outpoint:
11063                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
11064                                                 } = action {
11065                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
11066                                                                 log_trace!(logger,
11067                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
11068                                                                         blocked_channel_outpoint.to_channel_id());
11069                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
11070                                                                         .entry(blocked_channel_outpoint.to_channel_id())
11071                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
11072                                                         } else {
11073                                                                 // If the channel we were blocking has closed, we don't need to
11074                                                                 // worry about it - the blocked monitor update should never have
11075                                                                 // been released from the `Channel` object so it can't have
11076                                                                 // completed, and if the channel closed there's no reason to bother
11077                                                                 // anymore.
11078                                                         }
11079                                                 }
11080                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
11081                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
11082                                                 }
11083                                         }
11084                                 }
11085                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
11086                         } else {
11087                                 log_error!(WithContext::from(&args.logger, Some(node_id), None), "Got blocked actions without a per-peer-state for {}", node_id);
11088                                 return Err(DecodeError::InvalidValue);
11089                         }
11090                 }
11091
11092                 let channel_manager = ChannelManager {
11093                         chain_hash,
11094                         fee_estimator: bounded_fee_estimator,
11095                         chain_monitor: args.chain_monitor,
11096                         tx_broadcaster: args.tx_broadcaster,
11097                         router: args.router,
11098
11099                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
11100
11101                         inbound_payment_key: expanded_inbound_key,
11102                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
11103                         pending_outbound_payments: pending_outbounds,
11104                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
11105
11106                         forward_htlcs: Mutex::new(forward_htlcs),
11107                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
11108                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
11109                         outpoint_to_peer: Mutex::new(outpoint_to_peer),
11110                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
11111                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
11112
11113                         probing_cookie_secret: probing_cookie_secret.unwrap(),
11114
11115                         our_network_pubkey,
11116                         secp_ctx,
11117
11118                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
11119
11120                         per_peer_state: FairRwLock::new(per_peer_state),
11121
11122                         pending_events: Mutex::new(pending_events_read),
11123                         pending_events_processor: AtomicBool::new(false),
11124                         pending_background_events: Mutex::new(pending_background_events),
11125                         total_consistency_lock: RwLock::new(()),
11126                         background_events_processed_since_startup: AtomicBool::new(false),
11127
11128                         event_persist_notifier: Notifier::new(),
11129                         needs_persist_flag: AtomicBool::new(false),
11130
11131                         funding_batch_states: Mutex::new(BTreeMap::new()),
11132
11133                         pending_offers_messages: Mutex::new(Vec::new()),
11134
11135                         entropy_source: args.entropy_source,
11136                         node_signer: args.node_signer,
11137                         signer_provider: args.signer_provider,
11138
11139                         logger: args.logger,
11140                         default_configuration: args.default_config,
11141                 };
11142
11143                 for htlc_source in failed_htlcs.drain(..) {
11144                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
11145                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
11146                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
11147                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
11148                 }
11149
11150                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
11151                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
11152                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
11153                         // channel is closed we just assume that it probably came from an on-chain claim.
11154                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
11155                                 downstream_closed, true, downstream_node_id, downstream_funding);
11156                 }
11157
11158                 //TODO: Broadcast channel update for closed channels, but only after we've made a
11159                 //connection or two.
11160
11161                 Ok((best_block_hash.clone(), channel_manager))
11162         }
11163 }
11164
11165 #[cfg(test)]
11166 mod tests {
11167         use bitcoin::hashes::Hash;
11168         use bitcoin::hashes::sha256::Hash as Sha256;
11169         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
11170         use core::sync::atomic::Ordering;
11171         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
11172         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
11173         use crate::ln::ChannelId;
11174         use crate::ln::channelmanager::{create_recv_pending_htlc_info, HTLCForwardInfo, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
11175         use crate::ln::functional_test_utils::*;
11176         use crate::ln::msgs::{self, ErrorAction};
11177         use crate::ln::msgs::ChannelMessageHandler;
11178         use crate::prelude::*;
11179         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
11180         use crate::util::errors::APIError;
11181         use crate::util::ser::Writeable;
11182         use crate::util::test_utils;
11183         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
11184         use crate::sign::EntropySource;
11185
11186         #[test]
11187         fn test_notify_limits() {
11188                 // Check that a few cases which don't require the persistence of a new ChannelManager,
11189                 // indeed, do not cause the persistence of a new ChannelManager.
11190                 let chanmon_cfgs = create_chanmon_cfgs(3);
11191                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11192                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
11193                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11194
11195                 // All nodes start with a persistable update pending as `create_network` connects each node
11196                 // with all other nodes to make most tests simpler.
11197                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11198                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11199                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11200
11201                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11202
11203                 // We check that the channel info nodes have doesn't change too early, even though we try
11204                 // to connect messages with new values
11205                 chan.0.contents.fee_base_msat *= 2;
11206                 chan.1.contents.fee_base_msat *= 2;
11207                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
11208                         &nodes[1].node.get_our_node_id()).pop().unwrap();
11209                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
11210                         &nodes[0].node.get_our_node_id()).pop().unwrap();
11211
11212                 // The first two nodes (which opened a channel) should now require fresh persistence
11213                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11214                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11215                 // ... but the last node should not.
11216                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11217                 // After persisting the first two nodes they should no longer need fresh persistence.
11218                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11219                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11220
11221                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
11222                 // about the channel.
11223                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
11224                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
11225                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11226
11227                 // The nodes which are a party to the channel should also ignore messages from unrelated
11228                 // parties.
11229                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11230                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11231                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11232                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11233                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11234                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11235
11236                 // At this point the channel info given by peers should still be the same.
11237                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11238                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11239
11240                 // An earlier version of handle_channel_update didn't check the directionality of the
11241                 // update message and would always update the local fee info, even if our peer was
11242                 // (spuriously) forwarding us our own channel_update.
11243                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
11244                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
11245                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
11246
11247                 // First deliver each peers' own message, checking that the node doesn't need to be
11248                 // persisted and that its channel info remains the same.
11249                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
11250                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
11251                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11252                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11253                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11254                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11255
11256                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
11257                 // the channel info has updated.
11258                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
11259                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
11260                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11261                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11262                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
11263                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
11264         }
11265
11266         #[test]
11267         fn test_keysend_dup_hash_partial_mpp() {
11268                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
11269                 // expected.
11270                 let chanmon_cfgs = create_chanmon_cfgs(2);
11271                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11272                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11273                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11274                 create_announced_chan_between_nodes(&nodes, 0, 1);
11275
11276                 // First, send a partial MPP payment.
11277                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
11278                 let mut mpp_route = route.clone();
11279                 mpp_route.paths.push(mpp_route.paths[0].clone());
11280
11281                 let payment_id = PaymentId([42; 32]);
11282                 // Use the utility function send_payment_along_path to send the payment with MPP data which
11283                 // indicates there are more HTLCs coming.
11284                 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.
11285                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
11286                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
11287                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
11288                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
11289                 check_added_monitors!(nodes[0], 1);
11290                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11291                 assert_eq!(events.len(), 1);
11292                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
11293
11294                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
11295                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11296                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11297                 check_added_monitors!(nodes[0], 1);
11298                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11299                 assert_eq!(events.len(), 1);
11300                 let ev = events.drain(..).next().unwrap();
11301                 let payment_event = SendEvent::from_event(ev);
11302                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11303                 check_added_monitors!(nodes[1], 0);
11304                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11305                 expect_pending_htlcs_forwardable!(nodes[1]);
11306                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
11307                 check_added_monitors!(nodes[1], 1);
11308                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11309                 assert!(updates.update_add_htlcs.is_empty());
11310                 assert!(updates.update_fulfill_htlcs.is_empty());
11311                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11312                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11313                 assert!(updates.update_fee.is_none());
11314                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11315                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11316                 expect_payment_failed!(nodes[0], our_payment_hash, true);
11317
11318                 // Send the second half of the original MPP payment.
11319                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
11320                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
11321                 check_added_monitors!(nodes[0], 1);
11322                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11323                 assert_eq!(events.len(), 1);
11324                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
11325
11326                 // Claim the full MPP payment. Note that we can't use a test utility like
11327                 // claim_funds_along_route because the ordering of the messages causes the second half of the
11328                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
11329                 // lightning messages manually.
11330                 nodes[1].node.claim_funds(payment_preimage);
11331                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
11332                 check_added_monitors!(nodes[1], 2);
11333
11334                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11335                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
11336                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
11337                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
11338                 check_added_monitors!(nodes[0], 1);
11339                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11340                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
11341                 check_added_monitors!(nodes[1], 1);
11342                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11343                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
11344                 check_added_monitors!(nodes[1], 1);
11345                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11346                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
11347                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
11348                 check_added_monitors!(nodes[0], 1);
11349                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
11350                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
11351                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11352                 check_added_monitors!(nodes[0], 1);
11353                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
11354                 check_added_monitors!(nodes[1], 1);
11355                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
11356                 check_added_monitors!(nodes[1], 1);
11357                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11358                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
11359                 check_added_monitors!(nodes[0], 1);
11360
11361                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
11362                 // path's success and a PaymentPathSuccessful event for each path's success.
11363                 let events = nodes[0].node.get_and_clear_pending_events();
11364                 assert_eq!(events.len(), 2);
11365                 match events[0] {
11366                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11367                                 assert_eq!(payment_id, *actual_payment_id);
11368                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11369                                 assert_eq!(route.paths[0], *path);
11370                         },
11371                         _ => panic!("Unexpected event"),
11372                 }
11373                 match events[1] {
11374                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11375                                 assert_eq!(payment_id, *actual_payment_id);
11376                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11377                                 assert_eq!(route.paths[0], *path);
11378                         },
11379                         _ => panic!("Unexpected event"),
11380                 }
11381         }
11382
11383         #[test]
11384         fn test_keysend_dup_payment_hash() {
11385                 do_test_keysend_dup_payment_hash(false);
11386                 do_test_keysend_dup_payment_hash(true);
11387         }
11388
11389         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
11390                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
11391                 //      outbound regular payment fails as expected.
11392                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
11393                 //      fails as expected.
11394                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
11395                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
11396                 //      reject MPP keysend payments, since in this case where the payment has no payment
11397                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
11398                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
11399                 //      payment secrets and reject otherwise.
11400                 let chanmon_cfgs = create_chanmon_cfgs(2);
11401                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11402                 let mut mpp_keysend_cfg = test_default_channel_config();
11403                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
11404                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
11405                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11406                 create_announced_chan_between_nodes(&nodes, 0, 1);
11407                 let scorer = test_utils::TestScorer::new();
11408                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11409
11410                 // To start (1), send a regular payment but don't claim it.
11411                 let expected_route = [&nodes[1]];
11412                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
11413
11414                 // Next, attempt a keysend payment and make sure it fails.
11415                 let route_params = RouteParameters::from_payment_params_and_value(
11416                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
11417                         TEST_FINAL_CLTV, false), 100_000);
11418                 let route = find_route(
11419                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11420                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11421                 ).unwrap();
11422                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11423                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11424                 check_added_monitors!(nodes[0], 1);
11425                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11426                 assert_eq!(events.len(), 1);
11427                 let ev = events.drain(..).next().unwrap();
11428                 let payment_event = SendEvent::from_event(ev);
11429                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11430                 check_added_monitors!(nodes[1], 0);
11431                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11432                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
11433                 // fails), the second will process the resulting failure and fail the HTLC backward
11434                 expect_pending_htlcs_forwardable!(nodes[1]);
11435                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11436                 check_added_monitors!(nodes[1], 1);
11437                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11438                 assert!(updates.update_add_htlcs.is_empty());
11439                 assert!(updates.update_fulfill_htlcs.is_empty());
11440                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11441                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11442                 assert!(updates.update_fee.is_none());
11443                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11444                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11445                 expect_payment_failed!(nodes[0], payment_hash, true);
11446
11447                 // Finally, claim the original payment.
11448                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11449
11450                 // To start (2), send a keysend payment but don't claim it.
11451                 let payment_preimage = PaymentPreimage([42; 32]);
11452                 let route = find_route(
11453                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11454                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11455                 ).unwrap();
11456                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11457                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11458                 check_added_monitors!(nodes[0], 1);
11459                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11460                 assert_eq!(events.len(), 1);
11461                 let event = events.pop().unwrap();
11462                 let path = vec![&nodes[1]];
11463                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11464
11465                 // Next, attempt a regular payment and make sure it fails.
11466                 let payment_secret = PaymentSecret([43; 32]);
11467                 nodes[0].node.send_payment_with_route(&route, payment_hash,
11468                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
11469                 check_added_monitors!(nodes[0], 1);
11470                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11471                 assert_eq!(events.len(), 1);
11472                 let ev = events.drain(..).next().unwrap();
11473                 let payment_event = SendEvent::from_event(ev);
11474                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11475                 check_added_monitors!(nodes[1], 0);
11476                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11477                 expect_pending_htlcs_forwardable!(nodes[1]);
11478                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11479                 check_added_monitors!(nodes[1], 1);
11480                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11481                 assert!(updates.update_add_htlcs.is_empty());
11482                 assert!(updates.update_fulfill_htlcs.is_empty());
11483                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11484                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11485                 assert!(updates.update_fee.is_none());
11486                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11487                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11488                 expect_payment_failed!(nodes[0], payment_hash, true);
11489
11490                 // Finally, succeed the keysend payment.
11491                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11492
11493                 // To start (3), send a keysend payment but don't claim it.
11494                 let payment_id_1 = PaymentId([44; 32]);
11495                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11496                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
11497                 check_added_monitors!(nodes[0], 1);
11498                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11499                 assert_eq!(events.len(), 1);
11500                 let event = events.pop().unwrap();
11501                 let path = vec![&nodes[1]];
11502                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11503
11504                 // Next, attempt a keysend payment and make sure it fails.
11505                 let route_params = RouteParameters::from_payment_params_and_value(
11506                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
11507                         100_000
11508                 );
11509                 let route = find_route(
11510                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11511                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11512                 ).unwrap();
11513                 let payment_id_2 = PaymentId([45; 32]);
11514                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11515                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
11516                 check_added_monitors!(nodes[0], 1);
11517                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11518                 assert_eq!(events.len(), 1);
11519                 let ev = events.drain(..).next().unwrap();
11520                 let payment_event = SendEvent::from_event(ev);
11521                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11522                 check_added_monitors!(nodes[1], 0);
11523                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11524                 expect_pending_htlcs_forwardable!(nodes[1]);
11525                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11526                 check_added_monitors!(nodes[1], 1);
11527                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11528                 assert!(updates.update_add_htlcs.is_empty());
11529                 assert!(updates.update_fulfill_htlcs.is_empty());
11530                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11531                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11532                 assert!(updates.update_fee.is_none());
11533                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11534                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11535                 expect_payment_failed!(nodes[0], payment_hash, true);
11536
11537                 // Finally, claim the original payment.
11538                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11539         }
11540
11541         #[test]
11542         fn test_keysend_hash_mismatch() {
11543                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
11544                 // preimage doesn't match the msg's payment hash.
11545                 let chanmon_cfgs = create_chanmon_cfgs(2);
11546                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11547                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11548                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11549
11550                 let payer_pubkey = nodes[0].node.get_our_node_id();
11551                 let payee_pubkey = nodes[1].node.get_our_node_id();
11552
11553                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11554                 let route_params = RouteParameters::from_payment_params_and_value(
11555                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11556                 let network_graph = nodes[0].network_graph;
11557                 let first_hops = nodes[0].node.list_usable_channels();
11558                 let scorer = test_utils::TestScorer::new();
11559                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11560                 let route = find_route(
11561                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11562                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11563                 ).unwrap();
11564
11565                 let test_preimage = PaymentPreimage([42; 32]);
11566                 let mismatch_payment_hash = PaymentHash([43; 32]);
11567                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
11568                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
11569                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
11570                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
11571                 check_added_monitors!(nodes[0], 1);
11572
11573                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11574                 assert_eq!(updates.update_add_htlcs.len(), 1);
11575                 assert!(updates.update_fulfill_htlcs.is_empty());
11576                 assert!(updates.update_fail_htlcs.is_empty());
11577                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11578                 assert!(updates.update_fee.is_none());
11579                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11580
11581                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
11582         }
11583
11584         #[test]
11585         fn test_keysend_msg_with_secret_err() {
11586                 // Test that we error as expected if we receive a keysend payment that includes a payment
11587                 // secret when we don't support MPP keysend.
11588                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
11589                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
11590                 let chanmon_cfgs = create_chanmon_cfgs(2);
11591                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11592                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
11593                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11594
11595                 let payer_pubkey = nodes[0].node.get_our_node_id();
11596                 let payee_pubkey = nodes[1].node.get_our_node_id();
11597
11598                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11599                 let route_params = RouteParameters::from_payment_params_and_value(
11600                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11601                 let network_graph = nodes[0].network_graph;
11602                 let first_hops = nodes[0].node.list_usable_channels();
11603                 let scorer = test_utils::TestScorer::new();
11604                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11605                 let route = find_route(
11606                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11607                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11608                 ).unwrap();
11609
11610                 let test_preimage = PaymentPreimage([42; 32]);
11611                 let test_secret = PaymentSecret([43; 32]);
11612                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).to_byte_array());
11613                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
11614                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
11615                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
11616                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
11617                         PaymentId(payment_hash.0), None, session_privs).unwrap();
11618                 check_added_monitors!(nodes[0], 1);
11619
11620                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11621                 assert_eq!(updates.update_add_htlcs.len(), 1);
11622                 assert!(updates.update_fulfill_htlcs.is_empty());
11623                 assert!(updates.update_fail_htlcs.is_empty());
11624                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11625                 assert!(updates.update_fee.is_none());
11626                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11627
11628                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11629         }
11630
11631         #[test]
11632         fn test_multi_hop_missing_secret() {
11633                 let chanmon_cfgs = create_chanmon_cfgs(4);
11634                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11635                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11636                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11637
11638                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11639                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11640                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11641                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11642
11643                 // Marshall an MPP route.
11644                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11645                 let path = route.paths[0].clone();
11646                 route.paths.push(path);
11647                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11648                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11649                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11650                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11651                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11652                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11653
11654                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11655                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11656                 .unwrap_err() {
11657                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11658                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11659                         },
11660                         _ => panic!("unexpected error")
11661                 }
11662         }
11663
11664         #[test]
11665         fn test_drop_disconnected_peers_when_removing_channels() {
11666                 let chanmon_cfgs = create_chanmon_cfgs(2);
11667                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11668                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11669                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11670
11671                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11672
11673                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11674                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11675
11676                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11677                 check_closed_broadcast!(nodes[0], true);
11678                 check_added_monitors!(nodes[0], 1);
11679                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11680
11681                 {
11682                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11683                         // disconnected and the channel between has been force closed.
11684                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11685                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11686                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11687                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11688                 }
11689
11690                 nodes[0].node.timer_tick_occurred();
11691
11692                 {
11693                         // Assert that nodes[1] has now been removed.
11694                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11695                 }
11696         }
11697
11698         #[test]
11699         fn bad_inbound_payment_hash() {
11700                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11701                 let chanmon_cfgs = create_chanmon_cfgs(2);
11702                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11703                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11704                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11705
11706                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11707                 let payment_data = msgs::FinalOnionHopData {
11708                         payment_secret,
11709                         total_msat: 100_000,
11710                 };
11711
11712                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11713                 // payment verification fails as expected.
11714                 let mut bad_payment_hash = payment_hash.clone();
11715                 bad_payment_hash.0[0] += 1;
11716                 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) {
11717                         Ok(_) => panic!("Unexpected ok"),
11718                         Err(()) => {
11719                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11720                         }
11721                 }
11722
11723                 // Check that using the original payment hash succeeds.
11724                 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());
11725         }
11726
11727         #[test]
11728         fn test_outpoint_to_peer_coverage() {
11729                 // Test that the `ChannelManager:outpoint_to_peer` contains channels which have been assigned
11730                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11731                 // the channel is successfully closed.
11732                 let chanmon_cfgs = create_chanmon_cfgs(2);
11733                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11734                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11735                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11736
11737                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
11738                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11739                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11740                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11741                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11742
11743                 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11744                 let channel_id = ChannelId::from_bytes(tx.txid().to_byte_array());
11745                 {
11746                         // Ensure that the `outpoint_to_peer` map is empty until either party has received the
11747                         // funding transaction, and have the real `channel_id`.
11748                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11749                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11750                 }
11751
11752                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11753                 {
11754                         // Assert that `nodes[0]`'s `outpoint_to_peer` map is populated with the channel as soon as
11755                         // as it has the funding transaction.
11756                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11757                         assert_eq!(nodes_0_lock.len(), 1);
11758                         assert!(nodes_0_lock.contains_key(&funding_output));
11759                 }
11760
11761                 assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11762
11763                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11764
11765                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11766                 {
11767                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11768                         assert_eq!(nodes_0_lock.len(), 1);
11769                         assert!(nodes_0_lock.contains_key(&funding_output));
11770                 }
11771                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11772
11773                 {
11774                         // Assert that `nodes[1]`'s `outpoint_to_peer` map is populated with the channel as
11775                         // soon as it has the funding transaction.
11776                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11777                         assert_eq!(nodes_1_lock.len(), 1);
11778                         assert!(nodes_1_lock.contains_key(&funding_output));
11779                 }
11780                 check_added_monitors!(nodes[1], 1);
11781                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11782                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11783                 check_added_monitors!(nodes[0], 1);
11784                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11785                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11786                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11787                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11788
11789                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11790                 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()));
11791                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11792                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11793
11794                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11795                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11796                 {
11797                         // Assert that the channel is kept in the `outpoint_to_peer` map for both nodes until the
11798                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11799                         // fee for the closing transaction has been negotiated and the parties has the other
11800                         // party's signature for the fee negotiated closing transaction.)
11801                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11802                         assert_eq!(nodes_0_lock.len(), 1);
11803                         assert!(nodes_0_lock.contains_key(&funding_output));
11804                 }
11805
11806                 {
11807                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11808                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11809                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11810                         // kept in the `nodes[1]`'s `outpoint_to_peer` map.
11811                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11812                         assert_eq!(nodes_1_lock.len(), 1);
11813                         assert!(nodes_1_lock.contains_key(&funding_output));
11814                 }
11815
11816                 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()));
11817                 {
11818                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11819                         // therefore has all it needs to fully close the channel (both signatures for the
11820                         // closing transaction).
11821                         // Assert that the channel is removed from `nodes[0]`'s `outpoint_to_peer` map as it can be
11822                         // fully closed by `nodes[0]`.
11823                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11824
11825                         // Assert that the channel is still in `nodes[1]`'s  `outpoint_to_peer` map, as `nodes[1]`
11826                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11827                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11828                         assert_eq!(nodes_1_lock.len(), 1);
11829                         assert!(nodes_1_lock.contains_key(&funding_output));
11830                 }
11831
11832                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11833
11834                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11835                 {
11836                         // Assert that the channel has now been removed from both parties `outpoint_to_peer` map once
11837                         // they both have everything required to fully close the channel.
11838                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11839                 }
11840                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11841
11842                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11843                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11844         }
11845
11846         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11847                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11848                 check_api_error_message(expected_message, res_err)
11849         }
11850
11851         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11852                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11853                 check_api_error_message(expected_message, res_err)
11854         }
11855
11856         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11857                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11858                 check_api_error_message(expected_message, res_err)
11859         }
11860
11861         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11862                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11863                 check_api_error_message(expected_message, res_err)
11864         }
11865
11866         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11867                 match res_err {
11868                         Err(APIError::APIMisuseError { err }) => {
11869                                 assert_eq!(err, expected_err_message);
11870                         },
11871                         Err(APIError::ChannelUnavailable { err }) => {
11872                                 assert_eq!(err, expected_err_message);
11873                         },
11874                         Ok(_) => panic!("Unexpected Ok"),
11875                         Err(_) => panic!("Unexpected Error"),
11876                 }
11877         }
11878
11879         #[test]
11880         fn test_api_calls_with_unkown_counterparty_node() {
11881                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11882                 // expected if the `counterparty_node_id` is an unkown peer in the
11883                 // `ChannelManager::per_peer_state` map.
11884                 let chanmon_cfg = create_chanmon_cfgs(2);
11885                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11886                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11887                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11888
11889                 // Dummy values
11890                 let channel_id = ChannelId::from_bytes([4; 32]);
11891                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11892                 let intercept_id = InterceptId([0; 32]);
11893
11894                 // Test the API functions.
11895                 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);
11896
11897                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11898
11899                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11900
11901                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11902
11903                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11904
11905                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11906
11907                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11908         }
11909
11910         #[test]
11911         fn test_api_calls_with_unavailable_channel() {
11912                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11913                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11914                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11915                 // the given `channel_id`.
11916                 let chanmon_cfg = create_chanmon_cfgs(2);
11917                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11918                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11919                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11920
11921                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11922
11923                 // Dummy values
11924                 let channel_id = ChannelId::from_bytes([4; 32]);
11925
11926                 // Test the API functions.
11927                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11928
11929                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11930
11931                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11932
11933                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11934
11935                 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);
11936
11937                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11938         }
11939
11940         #[test]
11941         fn test_connection_limiting() {
11942                 // Test that we limit un-channel'd peers and un-funded channels properly.
11943                 let chanmon_cfgs = create_chanmon_cfgs(2);
11944                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11945                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11946                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11947
11948                 // Note that create_network connects the nodes together for us
11949
11950                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11951                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11952
11953                 let mut funding_tx = None;
11954                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11955                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11956                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11957
11958                         if idx == 0 {
11959                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11960                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11961                                 funding_tx = Some(tx.clone());
11962                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11963                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11964
11965                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11966                                 check_added_monitors!(nodes[1], 1);
11967                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11968
11969                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11970
11971                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11972                                 check_added_monitors!(nodes[0], 1);
11973                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11974                         }
11975                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11976                 }
11977
11978                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11979                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11980                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11981                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11982                         open_channel_msg.temporary_channel_id);
11983
11984                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11985                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11986                 // limit.
11987                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11988                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11989                         let 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                         peer_pks.push(random_pk);
11992                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11993                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11994                         }, true).unwrap();
11995                 }
11996                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11997                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11998                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11999                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12000                 }, true).unwrap_err();
12001
12002                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
12003                 // them if we have too many un-channel'd peers.
12004                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12005                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
12006                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
12007                 for ev in chan_closed_events {
12008                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
12009                 }
12010                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12011                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12012                 }, true).unwrap();
12013                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12014                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12015                 }, true).unwrap_err();
12016
12017                 // but of course if the connection is outbound its allowed...
12018                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12019                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12020                 }, false).unwrap();
12021                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12022
12023                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
12024                 // Even though we accept one more connection from new peers, we won't actually let them
12025                 // open channels.
12026                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
12027                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12028                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
12029                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
12030                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12031                 }
12032                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12033                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12034                         open_channel_msg.temporary_channel_id);
12035
12036                 // Of course, however, outbound channels are always allowed
12037                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap();
12038                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
12039
12040                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
12041                 // "protected" and can connect again.
12042                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
12043                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12044                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12045                 }, true).unwrap();
12046                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
12047
12048                 // Further, because the first channel was funded, we can open another channel with
12049                 // last_random_pk.
12050                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12051                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12052         }
12053
12054         #[test]
12055         fn test_outbound_chans_unlimited() {
12056                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
12057                 let chanmon_cfgs = create_chanmon_cfgs(2);
12058                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12059                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
12060                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12061
12062                 // Note that create_network connects the nodes together for us
12063
12064                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12065                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12066
12067                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
12068                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12069                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12070                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12071                 }
12072
12073                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
12074                 // rejected.
12075                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12076                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12077                         open_channel_msg.temporary_channel_id);
12078
12079                 // but we can still open an outbound channel.
12080                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12081                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
12082
12083                 // but even with such an outbound channel, additional inbound channels will still fail.
12084                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12085                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12086                         open_channel_msg.temporary_channel_id);
12087         }
12088
12089         #[test]
12090         fn test_0conf_limiting() {
12091                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12092                 // flag set and (sometimes) accept channels as 0conf.
12093                 let chanmon_cfgs = create_chanmon_cfgs(2);
12094                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12095                 let mut settings = test_default_channel_config();
12096                 settings.manually_accept_inbound_channels = true;
12097                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
12098                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12099
12100                 // Note that create_network connects the nodes together for us
12101
12102                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12103                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12104
12105                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
12106                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12107                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12108                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12109                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
12110                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12111                         }, true).unwrap();
12112
12113                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
12114                         let events = nodes[1].node.get_and_clear_pending_events();
12115                         match events[0] {
12116                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
12117                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
12118                                 }
12119                                 _ => panic!("Unexpected event"),
12120                         }
12121                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
12122                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12123                 }
12124
12125                 // If we try to accept a channel from another peer non-0conf it will fail.
12126                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12127                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12128                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12129                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12130                 }, true).unwrap();
12131                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12132                 let events = nodes[1].node.get_and_clear_pending_events();
12133                 match events[0] {
12134                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12135                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
12136                                         Err(APIError::APIMisuseError { err }) =>
12137                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
12138                                         _ => panic!(),
12139                                 }
12140                         }
12141                         _ => panic!("Unexpected event"),
12142                 }
12143                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12144                         open_channel_msg.temporary_channel_id);
12145
12146                 // ...however if we accept the same channel 0conf it should work just fine.
12147                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12148                 let events = nodes[1].node.get_and_clear_pending_events();
12149                 match events[0] {
12150                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12151                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
12152                         }
12153                         _ => panic!("Unexpected event"),
12154                 }
12155                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12156         }
12157
12158         #[test]
12159         fn reject_excessively_underpaying_htlcs() {
12160                 let chanmon_cfg = create_chanmon_cfgs(1);
12161                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12162                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12163                 let node = create_network(1, &node_cfg, &node_chanmgr);
12164                 let sender_intended_amt_msat = 100;
12165                 let extra_fee_msat = 10;
12166                 let hop_data = msgs::InboundOnionPayload::Receive {
12167                         sender_intended_htlc_amt_msat: 100,
12168                         cltv_expiry_height: 42,
12169                         payment_metadata: None,
12170                         keysend_preimage: None,
12171                         payment_data: Some(msgs::FinalOnionHopData {
12172                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12173                         }),
12174                         custom_tlvs: Vec::new(),
12175                 };
12176                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
12177                 // intended amount, we fail the payment.
12178                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12179                 if let Err(crate::ln::channelmanager::InboundHTLCErr { err_code, .. }) =
12180                         create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12181                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
12182                                 current_height, node[0].node.default_configuration.accept_mpp_keysend)
12183                 {
12184                         assert_eq!(err_code, 19);
12185                 } else { panic!(); }
12186
12187                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
12188                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
12189                         sender_intended_htlc_amt_msat: 100,
12190                         cltv_expiry_height: 42,
12191                         payment_metadata: None,
12192                         keysend_preimage: None,
12193                         payment_data: Some(msgs::FinalOnionHopData {
12194                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12195                         }),
12196                         custom_tlvs: Vec::new(),
12197                 };
12198                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12199                 assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12200                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
12201                         current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
12202         }
12203
12204         #[test]
12205         fn test_final_incorrect_cltv(){
12206                 let chanmon_cfg = create_chanmon_cfgs(1);
12207                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12208                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12209                 let node = create_network(1, &node_cfg, &node_chanmgr);
12210
12211                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12212                 let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
12213                         sender_intended_htlc_amt_msat: 100,
12214                         cltv_expiry_height: 22,
12215                         payment_metadata: None,
12216                         keysend_preimage: None,
12217                         payment_data: Some(msgs::FinalOnionHopData {
12218                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
12219                         }),
12220                         custom_tlvs: Vec::new(),
12221                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
12222                         node[0].node.default_configuration.accept_mpp_keysend);
12223
12224                 // Should not return an error as this condition:
12225                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
12226                 // is not satisfied.
12227                 assert!(result.is_ok());
12228         }
12229
12230         #[test]
12231         fn test_inbound_anchors_manual_acceptance() {
12232                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12233                 // flag set and (sometimes) accept channels as 0conf.
12234                 let mut anchors_cfg = test_default_channel_config();
12235                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12236
12237                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
12238                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
12239
12240                 let chanmon_cfgs = create_chanmon_cfgs(3);
12241                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
12242                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
12243                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
12244                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
12245
12246                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12247                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12248
12249                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12250                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12251                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
12252                 match &msg_events[0] {
12253                         MessageSendEvent::HandleError { node_id, action } => {
12254                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
12255                                 match action {
12256                                         ErrorAction::SendErrorMessage { msg } =>
12257                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
12258                                         _ => panic!("Unexpected error action"),
12259                                 }
12260                         }
12261                         _ => panic!("Unexpected event"),
12262                 }
12263
12264                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12265                 let events = nodes[2].node.get_and_clear_pending_events();
12266                 match events[0] {
12267                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
12268                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
12269                         _ => panic!("Unexpected event"),
12270                 }
12271                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12272         }
12273
12274         #[test]
12275         fn test_anchors_zero_fee_htlc_tx_fallback() {
12276                 // Tests that if both nodes support anchors, but the remote node does not want to accept
12277                 // anchor channels at the moment, an error it sent to the local node such that it can retry
12278                 // the channel without the anchors feature.
12279                 let chanmon_cfgs = create_chanmon_cfgs(2);
12280                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12281                 let mut anchors_config = test_default_channel_config();
12282                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12283                 anchors_config.manually_accept_inbound_channels = true;
12284                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
12285                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12286
12287                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None).unwrap();
12288                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12289                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
12290
12291                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12292                 let events = nodes[1].node.get_and_clear_pending_events();
12293                 match events[0] {
12294                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12295                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
12296                         }
12297                         _ => panic!("Unexpected event"),
12298                 }
12299
12300                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
12301                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
12302
12303                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12304                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
12305
12306                 // Since nodes[1] should not have accepted the channel, it should
12307                 // not have generated any events.
12308                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12309         }
12310
12311         #[test]
12312         fn test_update_channel_config() {
12313                 let chanmon_cfg = create_chanmon_cfgs(2);
12314                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12315                 let mut user_config = test_default_channel_config();
12316                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12317                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12318                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
12319                 let channel = &nodes[0].node.list_channels()[0];
12320
12321                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12322                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12323                 assert_eq!(events.len(), 0);
12324
12325                 user_config.channel_config.forwarding_fee_base_msat += 10;
12326                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12327                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
12328                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12329                 assert_eq!(events.len(), 1);
12330                 match &events[0] {
12331                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12332                         _ => panic!("expected BroadcastChannelUpdate event"),
12333                 }
12334
12335                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
12336                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12337                 assert_eq!(events.len(), 0);
12338
12339                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
12340                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12341                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
12342                         ..Default::default()
12343                 }).unwrap();
12344                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12345                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12346                 assert_eq!(events.len(), 1);
12347                 match &events[0] {
12348                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12349                         _ => panic!("expected BroadcastChannelUpdate event"),
12350                 }
12351
12352                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
12353                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12354                         forwarding_fee_proportional_millionths: Some(new_fee),
12355                         ..Default::default()
12356                 }).unwrap();
12357                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12358                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
12359                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12360                 assert_eq!(events.len(), 1);
12361                 match &events[0] {
12362                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12363                         _ => panic!("expected BroadcastChannelUpdate event"),
12364                 }
12365
12366                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
12367                 // should be applied to ensure update atomicity as specified in the API docs.
12368                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
12369                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
12370                 let new_fee = current_fee + 100;
12371                 assert!(
12372                         matches!(
12373                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
12374                                         forwarding_fee_proportional_millionths: Some(new_fee),
12375                                         ..Default::default()
12376                                 }),
12377                                 Err(APIError::ChannelUnavailable { err: _ }),
12378                         )
12379                 );
12380                 // Check that the fee hasn't changed for the channel that exists.
12381                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
12382                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12383                 assert_eq!(events.len(), 0);
12384         }
12385
12386         #[test]
12387         fn test_payment_display() {
12388                 let payment_id = PaymentId([42; 32]);
12389                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12390                 let payment_hash = PaymentHash([42; 32]);
12391                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12392                 let payment_preimage = PaymentPreimage([42; 32]);
12393                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12394         }
12395
12396         #[test]
12397         fn test_trigger_lnd_force_close() {
12398                 let chanmon_cfg = create_chanmon_cfgs(2);
12399                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12400                 let user_config = test_default_channel_config();
12401                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12402                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12403
12404                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
12405                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
12406                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
12407                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12408                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
12409                 check_closed_broadcast(&nodes[0], 1, true);
12410                 check_added_monitors(&nodes[0], 1);
12411                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
12412                 {
12413                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
12414                         assert_eq!(txn.len(), 1);
12415                         check_spends!(txn[0], funding_tx);
12416                 }
12417
12418                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
12419                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
12420                 // their side.
12421                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
12422                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
12423                 }, true).unwrap();
12424                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12425                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12426                 }, false).unwrap();
12427                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
12428                 let channel_reestablish = get_event_msg!(
12429                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
12430                 );
12431                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
12432
12433                 // Alice should respond with an error since the channel isn't known, but a bogus
12434                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
12435                 // close even if it was an lnd node.
12436                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
12437                 assert_eq!(msg_events.len(), 2);
12438                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
12439                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
12440                         assert_eq!(msg.next_local_commitment_number, 0);
12441                         assert_eq!(msg.next_remote_commitment_number, 0);
12442                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
12443                 } else { panic!() };
12444                 check_closed_broadcast(&nodes[1], 1, true);
12445                 check_added_monitors(&nodes[1], 1);
12446                 let expected_close_reason = ClosureReason::ProcessingError {
12447                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
12448                 };
12449                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
12450                 {
12451                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
12452                         assert_eq!(txn.len(), 1);
12453                         check_spends!(txn[0], funding_tx);
12454                 }
12455         }
12456
12457         #[test]
12458         fn test_malformed_forward_htlcs_ser() {
12459                 // Ensure that `HTLCForwardInfo::FailMalformedHTLC`s are (de)serialized properly.
12460                 let chanmon_cfg = create_chanmon_cfgs(1);
12461                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12462                 let persister;
12463                 let chain_monitor;
12464                 let chanmgrs = create_node_chanmgrs(1, &node_cfg, &[None]);
12465                 let deserialized_chanmgr;
12466                 let mut nodes = create_network(1, &node_cfg, &chanmgrs);
12467
12468                 let dummy_failed_htlc = |htlc_id| {
12469                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet: msgs::OnionErrorPacket { data: vec![42] }, }
12470                 };
12471                 let dummy_malformed_htlc = |htlc_id| {
12472                         HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code: 0x4000, sha256_of_onion: [0; 32] }
12473                 };
12474
12475                 let dummy_htlcs_1: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12476                         if htlc_id % 2 == 0 {
12477                                 dummy_failed_htlc(htlc_id)
12478                         } else {
12479                                 dummy_malformed_htlc(htlc_id)
12480                         }
12481                 }).collect();
12482
12483                 let dummy_htlcs_2: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12484                         if htlc_id % 2 == 1 {
12485                                 dummy_failed_htlc(htlc_id)
12486                         } else {
12487                                 dummy_malformed_htlc(htlc_id)
12488                         }
12489                 }).collect();
12490
12491
12492                 let (scid_1, scid_2) = (42, 43);
12493                 let mut forward_htlcs = HashMap::new();
12494                 forward_htlcs.insert(scid_1, dummy_htlcs_1.clone());
12495                 forward_htlcs.insert(scid_2, dummy_htlcs_2.clone());
12496
12497                 let mut chanmgr_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12498                 *chanmgr_fwd_htlcs = forward_htlcs.clone();
12499                 core::mem::drop(chanmgr_fwd_htlcs);
12500
12501                 reload_node!(nodes[0], nodes[0].node.encode(), &[], persister, chain_monitor, deserialized_chanmgr);
12502
12503                 let mut deserialized_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12504                 for scid in [scid_1, scid_2].iter() {
12505                         let deserialized_htlcs = deserialized_fwd_htlcs.remove(scid).unwrap();
12506                         assert_eq!(forward_htlcs.remove(scid).unwrap(), deserialized_htlcs);
12507                 }
12508                 assert!(deserialized_fwd_htlcs.is_empty());
12509                 core::mem::drop(deserialized_fwd_htlcs);
12510
12511                 expect_pending_htlcs_forwardable!(nodes[0]);
12512         }
12513 }
12514
12515 #[cfg(ldk_bench)]
12516 pub mod bench {
12517         use crate::chain::Listen;
12518         use crate::chain::chainmonitor::{ChainMonitor, Persist};
12519         use crate::sign::{KeysManager, InMemorySigner};
12520         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
12521         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
12522         use crate::ln::functional_test_utils::*;
12523         use crate::ln::msgs::{ChannelMessageHandler, Init};
12524         use crate::routing::gossip::NetworkGraph;
12525         use crate::routing::router::{PaymentParameters, RouteParameters};
12526         use crate::util::test_utils;
12527         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
12528
12529         use bitcoin::blockdata::locktime::absolute::LockTime;
12530         use bitcoin::hashes::Hash;
12531         use bitcoin::hashes::sha256::Hash as Sha256;
12532         use bitcoin::{Transaction, TxOut};
12533
12534         use crate::sync::{Arc, Mutex, RwLock};
12535
12536         use criterion::Criterion;
12537
12538         type Manager<'a, P> = ChannelManager<
12539                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
12540                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
12541                         &'a test_utils::TestLogger, &'a P>,
12542                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
12543                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
12544                 &'a test_utils::TestLogger>;
12545
12546         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
12547                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
12548         }
12549         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
12550                 type CM = Manager<'chan_mon_cfg, P>;
12551                 #[inline]
12552                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
12553                 #[inline]
12554                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
12555         }
12556
12557         pub fn bench_sends(bench: &mut Criterion) {
12558                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
12559         }
12560
12561         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
12562                 // Do a simple benchmark of sending a payment back and forth between two nodes.
12563                 // Note that this is unrealistic as each payment send will require at least two fsync
12564                 // calls per node.
12565                 let network = bitcoin::Network::Testnet;
12566                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
12567
12568                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
12569                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
12570                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
12571                 let scorer = RwLock::new(test_utils::TestScorer::new());
12572                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &logger_a, &scorer);
12573
12574                 let mut config: UserConfig = Default::default();
12575                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
12576                 config.channel_handshake_config.minimum_depth = 1;
12577
12578                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
12579                 let seed_a = [1u8; 32];
12580                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
12581                 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 {
12582                         network,
12583                         best_block: BestBlock::from_network(network),
12584                 }, genesis_block.header.time);
12585                 let node_a_holder = ANodeHolder { node: &node_a };
12586
12587                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
12588                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
12589                 let seed_b = [2u8; 32];
12590                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
12591                 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 {
12592                         network,
12593                         best_block: BestBlock::from_network(network),
12594                 }, genesis_block.header.time);
12595                 let node_b_holder = ANodeHolder { node: &node_b };
12596
12597                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
12598                         features: node_b.init_features(), networks: None, remote_network_address: None
12599                 }, true).unwrap();
12600                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
12601                         features: node_a.init_features(), networks: None, remote_network_address: None
12602                 }, false).unwrap();
12603                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None, None).unwrap();
12604                 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()));
12605                 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()));
12606
12607                 let tx;
12608                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
12609                         tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12610                                 value: 8_000_000, script_pubkey: output_script,
12611                         }]};
12612                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
12613                 } else { panic!(); }
12614
12615                 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()));
12616                 let events_b = node_b.get_and_clear_pending_events();
12617                 assert_eq!(events_b.len(), 1);
12618                 match events_b[0] {
12619                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12620                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12621                         },
12622                         _ => panic!("Unexpected event"),
12623                 }
12624
12625                 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()));
12626                 let events_a = node_a.get_and_clear_pending_events();
12627                 assert_eq!(events_a.len(), 1);
12628                 match events_a[0] {
12629                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12630                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12631                         },
12632                         _ => panic!("Unexpected event"),
12633                 }
12634
12635                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
12636
12637                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
12638                 Listen::block_connected(&node_a, &block, 1);
12639                 Listen::block_connected(&node_b, &block, 1);
12640
12641                 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()));
12642                 let msg_events = node_a.get_and_clear_pending_msg_events();
12643                 assert_eq!(msg_events.len(), 2);
12644                 match msg_events[0] {
12645                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
12646                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
12647                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
12648                         },
12649                         _ => panic!(),
12650                 }
12651                 match msg_events[1] {
12652                         MessageSendEvent::SendChannelUpdate { .. } => {},
12653                         _ => panic!(),
12654                 }
12655
12656                 let events_a = node_a.get_and_clear_pending_events();
12657                 assert_eq!(events_a.len(), 1);
12658                 match events_a[0] {
12659                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12660                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12661                         },
12662                         _ => panic!("Unexpected event"),
12663                 }
12664
12665                 let events_b = node_b.get_and_clear_pending_events();
12666                 assert_eq!(events_b.len(), 1);
12667                 match events_b[0] {
12668                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12669                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12670                         },
12671                         _ => panic!("Unexpected event"),
12672                 }
12673
12674                 let mut payment_count: u64 = 0;
12675                 macro_rules! send_payment {
12676                         ($node_a: expr, $node_b: expr) => {
12677                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
12678                                         .with_bolt11_features($node_b.bolt11_invoice_features()).unwrap();
12679                                 let mut payment_preimage = PaymentPreimage([0; 32]);
12680                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
12681                                 payment_count += 1;
12682                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
12683                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
12684
12685                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
12686                                         PaymentId(payment_hash.0),
12687                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12688                                         Retry::Attempts(0)).unwrap();
12689                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12690                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12691                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12692                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12693                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12694                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12695                                 $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()));
12696
12697                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12698                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12699                                 $node_b.claim_funds(payment_preimage);
12700                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12701
12702                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12703                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12704                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12705                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12706                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12707                                         },
12708                                         _ => panic!("Failed to generate claim event"),
12709                                 }
12710
12711                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12712                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12713                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12714                                 $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()));
12715
12716                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12717                         }
12718                 }
12719
12720                 bench.bench_function(bench_name, |b| b.iter(|| {
12721                         send_payment!(node_a, node_b);
12722                         send_payment!(node_b, node_a);
12723                 }));
12724         }
12725 }