Utility for creating and sending Bolt12Invoices
[rust-lightning] / lightning / src / ln / channelmanager.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The top-level channel management and payment tracking stuff lives here.
11 //!
12 //! The [`ChannelManager`] is the main chunk of logic implementing the lightning protocol and is
13 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
14 //! upon reconnect to the relevant peer(s).
15 //!
16 //! It does not manage routing logic (see [`Router`] for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
19
20 use bitcoin::blockdata::block::BlockHeader;
21 use bitcoin::blockdata::transaction::Transaction;
22 use bitcoin::blockdata::constants::ChainHash;
23 use bitcoin::network::constants::Network;
24
25 use bitcoin::hashes::Hash;
26 use bitcoin::hashes::sha256::Hash as Sha256;
27 use bitcoin::hash_types::{BlockHash, Txid};
28
29 use bitcoin::secp256k1::{SecretKey,PublicKey};
30 use bitcoin::secp256k1::Secp256k1;
31 use bitcoin::{LockTime, secp256k1, Sequence};
32
33 use crate::blinded_path::BlindedPath;
34 use crate::blinded_path::payment::{PaymentConstraints, ReceiveTlvs};
35 use crate::chain;
36 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
37 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
38 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
39 use crate::chain::transaction::{OutPoint, TransactionData};
40 use crate::events;
41 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
42 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
43 // construct one themselves.
44 use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
45 use crate::ln::channel::{Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel};
46 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
47 #[cfg(any(feature = "_test_utils", test))]
48 use crate::ln::features::Bolt11InvoiceFeatures;
49 use crate::routing::gossip::NetworkGraph;
50 use crate::routing::router::{BlindedTail, DefaultRouter, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
51 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
52 use crate::ln::msgs;
53 use crate::ln::onion_utils;
54 use crate::ln::onion_utils::HTLCFailReason;
55 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
56 #[cfg(test)]
57 use crate::ln::outbound_payment;
58 use crate::ln::outbound_payment::{OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs, StaleExpiration};
59 use crate::ln::wire::Encode;
60 use crate::offers::invoice::{BlindedPayInfo, DEFAULT_RELATIVE_EXPIRY};
61 use crate::offers::offer::{DerivedMetadata, Offer, OfferBuilder};
62 use crate::offers::parse::Bolt12SemanticError;
63 use crate::offers::refund::{Refund, RefundBuilder};
64 use crate::onion_message::{Destination, OffersMessage, PendingOnionMessage};
65 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, WriteableEcdsaChannelSigner};
66 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
67 use crate::util::wakers::{Future, Notifier};
68 use crate::util::scid_utils::fake_scid;
69 use crate::util::string::UntrustedString;
70 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
71 use crate::util::logger::{Level, Logger};
72 use crate::util::errors::APIError;
73
74 use alloc::collections::{btree_map, BTreeMap};
75
76 use crate::io;
77 use crate::prelude::*;
78 use core::{cmp, mem};
79 use core::cell::RefCell;
80 use crate::io::Read;
81 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
82 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
83 use core::time::Duration;
84 use core::ops::Deref;
85
86 // Re-export this for use in the public API.
87 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
88 use crate::ln::script::ShutdownScript;
89
90 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
91 //
92 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
93 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
94 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
95 //
96 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
97 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
98 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
99 // before we forward it.
100 //
101 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
102 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
103 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
104 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
105 // our payment, which we can use to decode errors or inform the user that the payment was sent.
106
107 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
108 pub(super) enum PendingHTLCRouting {
109         Forward {
110                 onion_packet: msgs::OnionPacket,
111                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
112                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
113                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
114         },
115         Receive {
116                 payment_data: msgs::FinalOnionHopData,
117                 payment_metadata: Option<Vec<u8>>,
118                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
119                 phantom_shared_secret: Option<[u8; 32]>,
120                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
121                 custom_tlvs: Vec<(u64, Vec<u8>)>,
122         },
123         ReceiveKeysend {
124                 /// This was added in 0.0.116 and will break deserialization on downgrades.
125                 payment_data: Option<msgs::FinalOnionHopData>,
126                 payment_preimage: PaymentPreimage,
127                 payment_metadata: Option<Vec<u8>>,
128                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
129                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
130                 custom_tlvs: Vec<(u64, Vec<u8>)>,
131         },
132 }
133
134 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
135 pub(super) struct PendingHTLCInfo {
136         pub(super) routing: PendingHTLCRouting,
137         pub(super) incoming_shared_secret: [u8; 32],
138         payment_hash: PaymentHash,
139         /// Amount received
140         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
141         /// Sender intended amount to forward or receive (actual amount received
142         /// may overshoot this in either case)
143         pub(super) outgoing_amt_msat: u64,
144         pub(super) outgoing_cltv_value: u32,
145         /// The fee being skimmed off the top of this HTLC. If this is a forward, it'll be the fee we are
146         /// skimming. If we're receiving this HTLC, it's the fee that our counterparty skimmed.
147         pub(super) skimmed_fee_msat: Option<u64>,
148 }
149
150 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
151 pub(super) enum HTLCFailureMsg {
152         Relay(msgs::UpdateFailHTLC),
153         Malformed(msgs::UpdateFailMalformedHTLC),
154 }
155
156 /// Stores whether we can't forward an HTLC or relevant forwarding info
157 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
158 pub(super) enum PendingHTLCStatus {
159         Forward(PendingHTLCInfo),
160         Fail(HTLCFailureMsg),
161 }
162
163 pub(super) struct PendingAddHTLCInfo {
164         pub(super) forward_info: PendingHTLCInfo,
165
166         // These fields are produced in `forward_htlcs()` and consumed in
167         // `process_pending_htlc_forwards()` for constructing the
168         // `HTLCSource::PreviousHopData` for failed and forwarded
169         // HTLCs.
170         //
171         // Note that this may be an outbound SCID alias for the associated channel.
172         prev_short_channel_id: u64,
173         prev_htlc_id: u64,
174         prev_funding_outpoint: OutPoint,
175         prev_user_channel_id: u128,
176 }
177
178 pub(super) enum HTLCForwardInfo {
179         AddHTLC(PendingAddHTLCInfo),
180         FailHTLC {
181                 htlc_id: u64,
182                 err_packet: msgs::OnionErrorPacket,
183         },
184 }
185
186 /// Tracks the inbound corresponding to an outbound HTLC
187 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
188 pub(crate) struct HTLCPreviousHopData {
189         // Note that this may be an outbound SCID alias for the associated channel.
190         short_channel_id: u64,
191         user_channel_id: Option<u128>,
192         htlc_id: u64,
193         incoming_packet_shared_secret: [u8; 32],
194         phantom_shared_secret: Option<[u8; 32]>,
195
196         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
197         // channel with a preimage provided by the forward channel.
198         outpoint: OutPoint,
199 }
200
201 enum OnionPayload {
202         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
203         Invoice {
204                 /// This is only here for backwards-compatibility in serialization, in the future it can be
205                 /// removed, breaking clients running 0.0.106 and earlier.
206                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
207         },
208         /// Contains the payer-provided preimage.
209         Spontaneous(PaymentPreimage),
210 }
211
212 /// HTLCs that are to us and can be failed/claimed by the user
213 struct ClaimableHTLC {
214         prev_hop: HTLCPreviousHopData,
215         cltv_expiry: u32,
216         /// The amount (in msats) of this MPP part
217         value: u64,
218         /// The amount (in msats) that the sender intended to be sent in this MPP
219         /// part (used for validating total MPP amount)
220         sender_intended_value: u64,
221         onion_payload: OnionPayload,
222         timer_ticks: u8,
223         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
224         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
225         total_value_received: Option<u64>,
226         /// The sender intended sum total of all MPP parts specified in the onion
227         total_msat: u64,
228         /// The extra fee our counterparty skimmed off the top of this HTLC.
229         counterparty_skimmed_fee_msat: Option<u64>,
230 }
231
232 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
233         fn from(val: &ClaimableHTLC) -> Self {
234                 events::ClaimedHTLC {
235                         channel_id: val.prev_hop.outpoint.to_channel_id(),
236                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
237                         cltv_expiry: val.cltv_expiry,
238                         value_msat: val.value,
239                 }
240         }
241 }
242
243 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
244 /// a payment and ensure idempotency in LDK.
245 ///
246 /// This is not exported to bindings users as we just use [u8; 32] directly
247 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
248 pub struct PaymentId(pub [u8; Self::LENGTH]);
249
250 impl PaymentId {
251         /// Number of bytes in the id.
252         pub const LENGTH: usize = 32;
253 }
254
255 impl Writeable for PaymentId {
256         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
257                 self.0.write(w)
258         }
259 }
260
261 impl Readable for PaymentId {
262         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
263                 let buf: [u8; 32] = Readable::read(r)?;
264                 Ok(PaymentId(buf))
265         }
266 }
267
268 impl core::fmt::Display for PaymentId {
269         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
270                 crate::util::logger::DebugBytes(&self.0).fmt(f)
271         }
272 }
273
274 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
275 ///
276 /// This is not exported to bindings users as we just use [u8; 32] directly
277 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
278 pub struct InterceptId(pub [u8; 32]);
279
280 impl Writeable for InterceptId {
281         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
282                 self.0.write(w)
283         }
284 }
285
286 impl Readable for InterceptId {
287         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
288                 let buf: [u8; 32] = Readable::read(r)?;
289                 Ok(InterceptId(buf))
290         }
291 }
292
293 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
294 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
295 pub(crate) enum SentHTLCId {
296         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
297         OutboundRoute { session_priv: SecretKey },
298 }
299 impl SentHTLCId {
300         pub(crate) fn from_source(source: &HTLCSource) -> Self {
301                 match source {
302                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
303                                 short_channel_id: hop_data.short_channel_id,
304                                 htlc_id: hop_data.htlc_id,
305                         },
306                         HTLCSource::OutboundRoute { session_priv, .. } =>
307                                 Self::OutboundRoute { session_priv: *session_priv },
308                 }
309         }
310 }
311 impl_writeable_tlv_based_enum!(SentHTLCId,
312         (0, PreviousHopData) => {
313                 (0, short_channel_id, required),
314                 (2, htlc_id, required),
315         },
316         (2, OutboundRoute) => {
317                 (0, session_priv, required),
318         };
319 );
320
321
322 /// Tracks the inbound corresponding to an outbound HTLC
323 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
324 #[derive(Clone, Debug, PartialEq, Eq)]
325 pub(crate) enum HTLCSource {
326         PreviousHopData(HTLCPreviousHopData),
327         OutboundRoute {
328                 path: Path,
329                 session_priv: SecretKey,
330                 /// Technically we can recalculate this from the route, but we cache it here to avoid
331                 /// doing a double-pass on route when we get a failure back
332                 first_hop_htlc_msat: u64,
333                 payment_id: PaymentId,
334         },
335 }
336 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
337 impl core::hash::Hash for HTLCSource {
338         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
339                 match self {
340                         HTLCSource::PreviousHopData(prev_hop_data) => {
341                                 0u8.hash(hasher);
342                                 prev_hop_data.hash(hasher);
343                         },
344                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
345                                 1u8.hash(hasher);
346                                 path.hash(hasher);
347                                 session_priv[..].hash(hasher);
348                                 payment_id.hash(hasher);
349                                 first_hop_htlc_msat.hash(hasher);
350                         },
351                 }
352         }
353 }
354 impl HTLCSource {
355         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
356         #[cfg(test)]
357         pub fn dummy() -> Self {
358                 HTLCSource::OutboundRoute {
359                         path: Path { hops: Vec::new(), blinded_tail: None },
360                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
361                         first_hop_htlc_msat: 0,
362                         payment_id: PaymentId([2; 32]),
363                 }
364         }
365
366         #[cfg(debug_assertions)]
367         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
368         /// transaction. Useful to ensure different datastructures match up.
369         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
370                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
371                         *first_hop_htlc_msat == htlc.amount_msat
372                 } else {
373                         // There's nothing we can check for forwarded HTLCs
374                         true
375                 }
376         }
377 }
378
379 struct InboundOnionErr {
380         err_code: u16,
381         err_data: Vec<u8>,
382         msg: &'static str,
383 }
384
385 /// This enum is used to specify which error data to send to peers when failing back an HTLC
386 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
387 ///
388 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
389 #[derive(Clone, Copy)]
390 pub enum FailureCode {
391         /// We had a temporary error processing the payment. Useful if no other error codes fit
392         /// and you want to indicate that the payer may want to retry.
393         TemporaryNodeFailure,
394         /// We have a required feature which was not in this onion. For example, you may require
395         /// some additional metadata that was not provided with this payment.
396         RequiredNodeFeatureMissing,
397         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
398         /// the HTLC is too close to the current block height for safe handling.
399         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
400         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
401         IncorrectOrUnknownPaymentDetails,
402         /// We failed to process the payload after the onion was decrypted. You may wish to
403         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
404         ///
405         /// If available, the tuple data may include the type number and byte offset in the
406         /// decrypted byte stream where the failure occurred.
407         InvalidOnionPayload(Option<(u64, u16)>),
408 }
409
410 impl Into<u16> for FailureCode {
411     fn into(self) -> u16 {
412                 match self {
413                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
414                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
415                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
416                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
417                 }
418         }
419 }
420
421 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
422 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
423 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
424 /// peer_state lock. We then return the set of things that need to be done outside the lock in
425 /// this struct and call handle_error!() on it.
426
427 struct MsgHandleErrInternal {
428         err: msgs::LightningError,
429         chan_id: Option<(ChannelId, u128)>, // If Some a channel of ours has been closed
430         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
431         channel_capacity: Option<u64>,
432 }
433 impl MsgHandleErrInternal {
434         #[inline]
435         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
436                 Self {
437                         err: LightningError {
438                                 err: err.clone(),
439                                 action: msgs::ErrorAction::SendErrorMessage {
440                                         msg: msgs::ErrorMessage {
441                                                 channel_id,
442                                                 data: err
443                                         },
444                                 },
445                         },
446                         chan_id: None,
447                         shutdown_finish: None,
448                         channel_capacity: None,
449                 }
450         }
451         #[inline]
452         fn from_no_close(err: msgs::LightningError) -> Self {
453                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
454         }
455         #[inline]
456         fn from_finish_shutdown(err: String, channel_id: ChannelId, user_channel_id: u128, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>, channel_capacity: u64) -> Self {
457                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
458                 let action = if let (Some(_), ..) = &shutdown_res {
459                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
460                         // should disconnect our peer such that we force them to broadcast their latest
461                         // commitment upon reconnecting.
462                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
463                 } else {
464                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
465                 };
466                 Self {
467                         err: LightningError { err, action },
468                         chan_id: Some((channel_id, user_channel_id)),
469                         shutdown_finish: Some((shutdown_res, channel_update)),
470                         channel_capacity: Some(channel_capacity)
471                 }
472         }
473         #[inline]
474         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
475                 Self {
476                         err: match err {
477                                 ChannelError::Warn(msg) =>  LightningError {
478                                         err: msg.clone(),
479                                         action: msgs::ErrorAction::SendWarningMessage {
480                                                 msg: msgs::WarningMessage {
481                                                         channel_id,
482                                                         data: msg
483                                                 },
484                                                 log_level: Level::Warn,
485                                         },
486                                 },
487                                 ChannelError::Ignore(msg) => LightningError {
488                                         err: msg,
489                                         action: msgs::ErrorAction::IgnoreError,
490                                 },
491                                 ChannelError::Close(msg) => LightningError {
492                                         err: msg.clone(),
493                                         action: msgs::ErrorAction::SendErrorMessage {
494                                                 msg: msgs::ErrorMessage {
495                                                         channel_id,
496                                                         data: msg
497                                                 },
498                                         },
499                                 },
500                         },
501                         chan_id: None,
502                         shutdown_finish: None,
503                         channel_capacity: None,
504                 }
505         }
506
507         fn closes_channel(&self) -> bool {
508                 self.chan_id.is_some()
509         }
510 }
511
512 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
513 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
514 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
515 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
516 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
517
518 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
519 /// be sent in the order they appear in the return value, however sometimes the order needs to be
520 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
521 /// they were originally sent). In those cases, this enum is also returned.
522 #[derive(Clone, PartialEq)]
523 pub(super) enum RAACommitmentOrder {
524         /// Send the CommitmentUpdate messages first
525         CommitmentFirst,
526         /// Send the RevokeAndACK message first
527         RevokeAndACKFirst,
528 }
529
530 /// Information about a payment which is currently being claimed.
531 struct ClaimingPayment {
532         amount_msat: u64,
533         payment_purpose: events::PaymentPurpose,
534         receiver_node_id: PublicKey,
535         htlcs: Vec<events::ClaimedHTLC>,
536         sender_intended_value: Option<u64>,
537 }
538 impl_writeable_tlv_based!(ClaimingPayment, {
539         (0, amount_msat, required),
540         (2, payment_purpose, required),
541         (4, receiver_node_id, required),
542         (5, htlcs, optional_vec),
543         (7, sender_intended_value, option),
544 });
545
546 struct ClaimablePayment {
547         purpose: events::PaymentPurpose,
548         onion_fields: Option<RecipientOnionFields>,
549         htlcs: Vec<ClaimableHTLC>,
550 }
551
552 /// Information about claimable or being-claimed payments
553 struct ClaimablePayments {
554         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
555         /// failed/claimed by the user.
556         ///
557         /// Note that, no consistency guarantees are made about the channels given here actually
558         /// existing anymore by the time you go to read them!
559         ///
560         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
561         /// we don't get a duplicate payment.
562         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
563
564         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
565         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
566         /// as an [`events::Event::PaymentClaimed`].
567         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
568 }
569
570 /// Events which we process internally but cannot be processed immediately at the generation site
571 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
572 /// running normally, and specifically must be processed before any other non-background
573 /// [`ChannelMonitorUpdate`]s are applied.
574 #[derive(Debug)]
575 enum BackgroundEvent {
576         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
577         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
578         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
579         /// channel has been force-closed we do not need the counterparty node_id.
580         ///
581         /// Note that any such events are lost on shutdown, so in general they must be updates which
582         /// are regenerated on startup.
583         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
584         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
585         /// channel to continue normal operation.
586         ///
587         /// In general this should be used rather than
588         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
589         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
590         /// error the other variant is acceptable.
591         ///
592         /// Note that any such events are lost on shutdown, so in general they must be updates which
593         /// are regenerated on startup.
594         MonitorUpdateRegeneratedOnStartup {
595                 counterparty_node_id: PublicKey,
596                 funding_txo: OutPoint,
597                 update: ChannelMonitorUpdate
598         },
599         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
600         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
601         /// on a channel.
602         MonitorUpdatesComplete {
603                 counterparty_node_id: PublicKey,
604                 channel_id: ChannelId,
605         },
606 }
607
608 #[derive(Debug)]
609 pub(crate) enum MonitorUpdateCompletionAction {
610         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
611         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
612         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
613         /// event can be generated.
614         PaymentClaimed { payment_hash: PaymentHash },
615         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
616         /// operation of another channel.
617         ///
618         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
619         /// from completing a monitor update which removes the payment preimage until the inbound edge
620         /// completes a monitor update containing the payment preimage. In that case, after the inbound
621         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
622         /// outbound edge.
623         EmitEventAndFreeOtherChannel {
624                 event: events::Event,
625                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
626         },
627         /// Indicates we should immediately resume the operation of another channel, unless there is
628         /// some other reason why the channel is blocked. In practice this simply means immediately
629         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
630         ///
631         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
632         /// from completing a monitor update which removes the payment preimage until the inbound edge
633         /// completes a monitor update containing the payment preimage. However, we use this variant
634         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
635         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
636         ///
637         /// This variant should thus never be written to disk, as it is processed inline rather than
638         /// stored for later processing.
639         FreeOtherChannelImmediately {
640                 downstream_counterparty_node_id: PublicKey,
641                 downstream_funding_outpoint: OutPoint,
642                 blocking_action: RAAMonitorUpdateBlockingAction,
643         },
644 }
645
646 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
647         (0, PaymentClaimed) => { (0, payment_hash, required) },
648         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
649         // *immediately*. However, for simplicity we implement read/write here.
650         (1, FreeOtherChannelImmediately) => {
651                 (0, downstream_counterparty_node_id, required),
652                 (2, downstream_funding_outpoint, required),
653                 (4, blocking_action, required),
654         },
655         (2, EmitEventAndFreeOtherChannel) => {
656                 (0, event, upgradable_required),
657                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
658                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
659                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
660                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
661                 // downgrades to prior versions.
662                 (1, downstream_counterparty_and_funding_outpoint, option),
663         },
664 );
665
666 #[derive(Clone, Debug, PartialEq, Eq)]
667 pub(crate) enum EventCompletionAction {
668         ReleaseRAAChannelMonitorUpdate {
669                 counterparty_node_id: PublicKey,
670                 channel_funding_outpoint: OutPoint,
671         },
672 }
673 impl_writeable_tlv_based_enum!(EventCompletionAction,
674         (0, ReleaseRAAChannelMonitorUpdate) => {
675                 (0, channel_funding_outpoint, required),
676                 (2, counterparty_node_id, required),
677         };
678 );
679
680 #[derive(Clone, PartialEq, Eq, Debug)]
681 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
682 /// the blocked action here. See enum variants for more info.
683 pub(crate) enum RAAMonitorUpdateBlockingAction {
684         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
685         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
686         /// durably to disk.
687         ForwardedPaymentInboundClaim {
688                 /// The upstream channel ID (i.e. the inbound edge).
689                 channel_id: ChannelId,
690                 /// The HTLC ID on the inbound edge.
691                 htlc_id: u64,
692         },
693 }
694
695 impl RAAMonitorUpdateBlockingAction {
696         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
697                 Self::ForwardedPaymentInboundClaim {
698                         channel_id: prev_hop.outpoint.to_channel_id(),
699                         htlc_id: prev_hop.htlc_id,
700                 }
701         }
702 }
703
704 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
705         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
706 ;);
707
708
709 /// State we hold per-peer.
710 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
711         /// `channel_id` -> `ChannelPhase`
712         ///
713         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
714         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
715         /// `temporary_channel_id` -> `InboundChannelRequest`.
716         ///
717         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
718         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
719         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
720         /// the channel is rejected, then the entry is simply removed.
721         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
722         /// The latest `InitFeatures` we heard from the peer.
723         latest_features: InitFeatures,
724         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
725         /// for broadcast messages, where ordering isn't as strict).
726         pub(super) pending_msg_events: Vec<MessageSendEvent>,
727         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
728         /// user but which have not yet completed.
729         ///
730         /// Note that the channel may no longer exist. For example if the channel was closed but we
731         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
732         /// for a missing channel.
733         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
734         /// Map from a specific channel to some action(s) that should be taken when all pending
735         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
736         ///
737         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
738         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
739         /// channels with a peer this will just be one allocation and will amount to a linear list of
740         /// channels to walk, avoiding the whole hashing rigmarole.
741         ///
742         /// Note that the channel may no longer exist. For example, if a channel was closed but we
743         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
744         /// for a missing channel. While a malicious peer could construct a second channel with the
745         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
746         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
747         /// duplicates do not occur, so such channels should fail without a monitor update completing.
748         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
749         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
750         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
751         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
752         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
753         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
754         /// The peer is currently connected (i.e. we've seen a
755         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
756         /// [`ChannelMessageHandler::peer_disconnected`].
757         is_connected: bool,
758 }
759
760 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
761         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
762         /// If true is passed for `require_disconnected`, the function will return false if we haven't
763         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
764         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
765                 if require_disconnected && self.is_connected {
766                         return false
767                 }
768                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
769                         && self.monitor_update_blocked_actions.is_empty()
770                         && self.in_flight_monitor_updates.is_empty()
771         }
772
773         // Returns a count of all channels we have with this peer, including unfunded channels.
774         fn total_channel_count(&self) -> usize {
775                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
776         }
777
778         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
779         fn has_channel(&self, channel_id: &ChannelId) -> bool {
780                 self.channel_by_id.contains_key(channel_id) ||
781                         self.inbound_channel_request_by_id.contains_key(channel_id)
782         }
783 }
784
785 /// A not-yet-accepted inbound (from counterparty) channel. Once
786 /// accepted, the parameters will be used to construct a channel.
787 pub(super) struct InboundChannelRequest {
788         /// The original OpenChannel message.
789         pub open_channel_msg: msgs::OpenChannel,
790         /// The number of ticks remaining before the request expires.
791         pub ticks_remaining: i32,
792 }
793
794 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
795 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
796 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
797
798 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
799 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
800 ///
801 /// For users who don't want to bother doing their own payment preimage storage, we also store that
802 /// here.
803 ///
804 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
805 /// and instead encoding it in the payment secret.
806 struct PendingInboundPayment {
807         /// The payment secret that the sender must use for us to accept this payment
808         payment_secret: PaymentSecret,
809         /// Time at which this HTLC expires - blocks with a header time above this value will result in
810         /// this payment being removed.
811         expiry_time: u64,
812         /// Arbitrary identifier the user specifies (or not)
813         user_payment_id: u64,
814         // Other required attributes of the payment, optionally enforced:
815         payment_preimage: Option<PaymentPreimage>,
816         min_value_msat: Option<u64>,
817 }
818
819 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
820 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
821 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
822 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
823 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
824 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
825 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
826 /// of [`KeysManager`] and [`DefaultRouter`].
827 ///
828 /// This is not exported to bindings users as Arcs don't make sense in bindings
829 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
830         Arc<M>,
831         Arc<T>,
832         Arc<KeysManager>,
833         Arc<KeysManager>,
834         Arc<KeysManager>,
835         Arc<F>,
836         Arc<DefaultRouter<
837                 Arc<NetworkGraph<Arc<L>>>,
838                 Arc<L>,
839                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
840                 ProbabilisticScoringFeeParameters,
841                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
842         >>,
843         Arc<L>
844 >;
845
846 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
847 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
848 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
849 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
850 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
851 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
852 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
853 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
854 /// of [`KeysManager`] and [`DefaultRouter`].
855 ///
856 /// This is not exported to bindings users as Arcs don't make sense in bindings
857 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
858         ChannelManager<
859                 &'a M,
860                 &'b T,
861                 &'c KeysManager,
862                 &'c KeysManager,
863                 &'c KeysManager,
864                 &'d F,
865                 &'e DefaultRouter<
866                         &'f NetworkGraph<&'g L>,
867                         &'g L,
868                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
869                         ProbabilisticScoringFeeParameters,
870                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
871                 >,
872                 &'g L
873         >;
874
875 /// A trivial trait which describes any [`ChannelManager`].
876 ///
877 /// This is not exported to bindings users as general cover traits aren't useful in other
878 /// languages.
879 pub trait AChannelManager {
880         /// A type implementing [`chain::Watch`].
881         type Watch: chain::Watch<Self::Signer> + ?Sized;
882         /// A type that may be dereferenced to [`Self::Watch`].
883         type M: Deref<Target = Self::Watch>;
884         /// A type implementing [`BroadcasterInterface`].
885         type Broadcaster: BroadcasterInterface + ?Sized;
886         /// A type that may be dereferenced to [`Self::Broadcaster`].
887         type T: Deref<Target = Self::Broadcaster>;
888         /// A type implementing [`EntropySource`].
889         type EntropySource: EntropySource + ?Sized;
890         /// A type that may be dereferenced to [`Self::EntropySource`].
891         type ES: Deref<Target = Self::EntropySource>;
892         /// A type implementing [`NodeSigner`].
893         type NodeSigner: NodeSigner + ?Sized;
894         /// A type that may be dereferenced to [`Self::NodeSigner`].
895         type NS: Deref<Target = Self::NodeSigner>;
896         /// A type implementing [`WriteableEcdsaChannelSigner`].
897         type Signer: WriteableEcdsaChannelSigner + Sized;
898         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
899         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
900         /// A type that may be dereferenced to [`Self::SignerProvider`].
901         type SP: Deref<Target = Self::SignerProvider>;
902         /// A type implementing [`FeeEstimator`].
903         type FeeEstimator: FeeEstimator + ?Sized;
904         /// A type that may be dereferenced to [`Self::FeeEstimator`].
905         type F: Deref<Target = Self::FeeEstimator>;
906         /// A type implementing [`Router`].
907         type Router: Router + ?Sized;
908         /// A type that may be dereferenced to [`Self::Router`].
909         type R: Deref<Target = Self::Router>;
910         /// A type implementing [`Logger`].
911         type Logger: Logger + ?Sized;
912         /// A type that may be dereferenced to [`Self::Logger`].
913         type L: Deref<Target = Self::Logger>;
914         /// Returns a reference to the actual [`ChannelManager`] object.
915         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
916 }
917
918 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
919 for ChannelManager<M, T, ES, NS, SP, F, R, L>
920 where
921         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
922         T::Target: BroadcasterInterface,
923         ES::Target: EntropySource,
924         NS::Target: NodeSigner,
925         SP::Target: SignerProvider,
926         F::Target: FeeEstimator,
927         R::Target: Router,
928         L::Target: Logger,
929 {
930         type Watch = M::Target;
931         type M = M;
932         type Broadcaster = T::Target;
933         type T = T;
934         type EntropySource = ES::Target;
935         type ES = ES;
936         type NodeSigner = NS::Target;
937         type NS = NS;
938         type Signer = <SP::Target as SignerProvider>::Signer;
939         type SignerProvider = SP::Target;
940         type SP = SP;
941         type FeeEstimator = F::Target;
942         type F = F;
943         type Router = R::Target;
944         type R = R;
945         type Logger = L::Target;
946         type L = L;
947         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
948 }
949
950 /// Manager which keeps track of a number of channels and sends messages to the appropriate
951 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
952 ///
953 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
954 /// to individual Channels.
955 ///
956 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
957 /// all peers during write/read (though does not modify this instance, only the instance being
958 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
959 /// called [`funding_transaction_generated`] for outbound channels) being closed.
960 ///
961 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
962 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
963 /// [`ChannelMonitorUpdate`] before returning from
964 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
965 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
966 /// `ChannelManager` operations from occurring during the serialization process). If the
967 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
968 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
969 /// will be lost (modulo on-chain transaction fees).
970 ///
971 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
972 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
973 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
974 ///
975 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
976 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
977 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
978 /// offline for a full minute. In order to track this, you must call
979 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
980 ///
981 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
982 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
983 /// not have a channel with being unable to connect to us or open new channels with us if we have
984 /// many peers with unfunded channels.
985 ///
986 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
987 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
988 /// never limited. Please ensure you limit the count of such channels yourself.
989 ///
990 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
991 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
992 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
993 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
994 /// you're using lightning-net-tokio.
995 ///
996 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
997 /// [`funding_created`]: msgs::FundingCreated
998 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
999 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1000 /// [`update_channel`]: chain::Watch::update_channel
1001 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1002 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1003 /// [`read`]: ReadableArgs::read
1004 //
1005 // Lock order:
1006 // The tree structure below illustrates the lock order requirements for the different locks of the
1007 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1008 // and should then be taken in the order of the lowest to the highest level in the tree.
1009 // Note that locks on different branches shall not be taken at the same time, as doing so will
1010 // create a new lock order for those specific locks in the order they were taken.
1011 //
1012 // Lock order tree:
1013 //
1014 // `pending_offers_messages`
1015 //
1016 // `total_consistency_lock`
1017 //  |
1018 //  |__`forward_htlcs`
1019 //  |   |
1020 //  |   |__`pending_intercepted_htlcs`
1021 //  |
1022 //  |__`per_peer_state`
1023 //      |
1024 //      |__`pending_inbound_payments`
1025 //          |
1026 //          |__`claimable_payments`
1027 //          |
1028 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1029 //              |
1030 //              |__`peer_state`
1031 //                  |
1032 //                  |__`id_to_peer`
1033 //                  |
1034 //                  |__`short_to_chan_info`
1035 //                  |
1036 //                  |__`outbound_scid_aliases`
1037 //                  |
1038 //                  |__`best_block`
1039 //                  |
1040 //                  |__`pending_events`
1041 //                      |
1042 //                      |__`pending_background_events`
1043 //
1044 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1045 where
1046         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1047         T::Target: BroadcasterInterface,
1048         ES::Target: EntropySource,
1049         NS::Target: NodeSigner,
1050         SP::Target: SignerProvider,
1051         F::Target: FeeEstimator,
1052         R::Target: Router,
1053         L::Target: Logger,
1054 {
1055         default_configuration: UserConfig,
1056         chain_hash: ChainHash,
1057         fee_estimator: LowerBoundedFeeEstimator<F>,
1058         chain_monitor: M,
1059         tx_broadcaster: T,
1060         #[allow(unused)]
1061         router: R,
1062
1063         /// See `ChannelManager` struct-level documentation for lock order requirements.
1064         #[cfg(test)]
1065         pub(super) best_block: RwLock<BestBlock>,
1066         #[cfg(not(test))]
1067         best_block: RwLock<BestBlock>,
1068         secp_ctx: Secp256k1<secp256k1::All>,
1069
1070         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1071         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1072         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1073         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1074         ///
1075         /// See `ChannelManager` struct-level documentation for lock order requirements.
1076         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1077
1078         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1079         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1080         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1081         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1082         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1083         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1084         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1085         /// after reloading from disk while replaying blocks against ChannelMonitors.
1086         ///
1087         /// See `PendingOutboundPayment` documentation for more info.
1088         ///
1089         /// See `ChannelManager` struct-level documentation for lock order requirements.
1090         pending_outbound_payments: OutboundPayments,
1091
1092         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1093         ///
1094         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1095         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1096         /// and via the classic SCID.
1097         ///
1098         /// Note that no consistency guarantees are made about the existence of a channel with the
1099         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1100         ///
1101         /// See `ChannelManager` struct-level documentation for lock order requirements.
1102         #[cfg(test)]
1103         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1104         #[cfg(not(test))]
1105         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1106         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1107         /// until the user tells us what we should do with them.
1108         ///
1109         /// See `ChannelManager` struct-level documentation for lock order requirements.
1110         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1111
1112         /// The sets of payments which are claimable or currently being claimed. See
1113         /// [`ClaimablePayments`]' individual field docs for more info.
1114         ///
1115         /// See `ChannelManager` struct-level documentation for lock order requirements.
1116         claimable_payments: Mutex<ClaimablePayments>,
1117
1118         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1119         /// and some closed channels which reached a usable state prior to being closed. This is used
1120         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1121         /// active channel list on load.
1122         ///
1123         /// See `ChannelManager` struct-level documentation for lock order requirements.
1124         outbound_scid_aliases: Mutex<HashSet<u64>>,
1125
1126         /// `channel_id` -> `counterparty_node_id`.
1127         ///
1128         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1129         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1130         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1131         ///
1132         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1133         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1134         /// the handling of the events.
1135         ///
1136         /// Note that no consistency guarantees are made about the existence of a peer with the
1137         /// `counterparty_node_id` in our other maps.
1138         ///
1139         /// TODO:
1140         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1141         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1142         /// would break backwards compatability.
1143         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1144         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1145         /// required to access the channel with the `counterparty_node_id`.
1146         ///
1147         /// See `ChannelManager` struct-level documentation for lock order requirements.
1148         id_to_peer: Mutex<HashMap<ChannelId, PublicKey>>,
1149
1150         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1151         ///
1152         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1153         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1154         /// confirmation depth.
1155         ///
1156         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1157         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1158         /// channel with the `channel_id` in our other maps.
1159         ///
1160         /// See `ChannelManager` struct-level documentation for lock order requirements.
1161         #[cfg(test)]
1162         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1163         #[cfg(not(test))]
1164         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1165
1166         our_network_pubkey: PublicKey,
1167
1168         inbound_payment_key: inbound_payment::ExpandedKey,
1169
1170         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1171         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1172         /// we encrypt the namespace identifier using these bytes.
1173         ///
1174         /// [fake scids]: crate::util::scid_utils::fake_scid
1175         fake_scid_rand_bytes: [u8; 32],
1176
1177         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1178         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1179         /// keeping additional state.
1180         probing_cookie_secret: [u8; 32],
1181
1182         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1183         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1184         /// very far in the past, and can only ever be up to two hours in the future.
1185         highest_seen_timestamp: AtomicUsize,
1186
1187         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1188         /// basis, as well as the peer's latest features.
1189         ///
1190         /// If we are connected to a peer we always at least have an entry here, even if no channels
1191         /// are currently open with that peer.
1192         ///
1193         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1194         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1195         /// channels.
1196         ///
1197         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1198         ///
1199         /// See `ChannelManager` struct-level documentation for lock order requirements.
1200         #[cfg(not(any(test, feature = "_test_utils")))]
1201         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1202         #[cfg(any(test, feature = "_test_utils"))]
1203         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1204
1205         /// The set of events which we need to give to the user to handle. In some cases an event may
1206         /// require some further action after the user handles it (currently only blocking a monitor
1207         /// update from being handed to the user to ensure the included changes to the channel state
1208         /// are handled by the user before they're persisted durably to disk). In that case, the second
1209         /// element in the tuple is set to `Some` with further details of the action.
1210         ///
1211         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1212         /// could be in the middle of being processed without the direct mutex held.
1213         ///
1214         /// See `ChannelManager` struct-level documentation for lock order requirements.
1215         #[cfg(not(any(test, feature = "_test_utils")))]
1216         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1217         #[cfg(any(test, feature = "_test_utils"))]
1218         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1219
1220         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1221         pending_events_processor: AtomicBool,
1222
1223         /// If we are running during init (either directly during the deserialization method or in
1224         /// block connection methods which run after deserialization but before normal operation) we
1225         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1226         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1227         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1228         ///
1229         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1230         ///
1231         /// See `ChannelManager` struct-level documentation for lock order requirements.
1232         ///
1233         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1234         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1235         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1236         /// Essentially just when we're serializing ourselves out.
1237         /// Taken first everywhere where we are making changes before any other locks.
1238         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1239         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1240         /// Notifier the lock contains sends out a notification when the lock is released.
1241         total_consistency_lock: RwLock<()>,
1242         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1243         /// received and the monitor has been persisted.
1244         ///
1245         /// This information does not need to be persisted as funding nodes can forget
1246         /// unfunded channels upon disconnection.
1247         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1248
1249         background_events_processed_since_startup: AtomicBool,
1250
1251         event_persist_notifier: Notifier,
1252         needs_persist_flag: AtomicBool,
1253
1254         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1255
1256         entropy_source: ES,
1257         node_signer: NS,
1258         signer_provider: SP,
1259
1260         logger: L,
1261 }
1262
1263 /// Chain-related parameters used to construct a new `ChannelManager`.
1264 ///
1265 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1266 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1267 /// are not needed when deserializing a previously constructed `ChannelManager`.
1268 #[derive(Clone, Copy, PartialEq)]
1269 pub struct ChainParameters {
1270         /// The network for determining the `chain_hash` in Lightning messages.
1271         pub network: Network,
1272
1273         /// The hash and height of the latest block successfully connected.
1274         ///
1275         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1276         pub best_block: BestBlock,
1277 }
1278
1279 #[derive(Copy, Clone, PartialEq)]
1280 #[must_use]
1281 enum NotifyOption {
1282         DoPersist,
1283         SkipPersistHandleEvents,
1284         SkipPersistNoEvents,
1285 }
1286
1287 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1288 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1289 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1290 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1291 /// sending the aforementioned notification (since the lock being released indicates that the
1292 /// updates are ready for persistence).
1293 ///
1294 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1295 /// notify or not based on whether relevant changes have been made, providing a closure to
1296 /// `optionally_notify` which returns a `NotifyOption`.
1297 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1298         event_persist_notifier: &'a Notifier,
1299         needs_persist_flag: &'a AtomicBool,
1300         should_persist: F,
1301         // We hold onto this result so the lock doesn't get released immediately.
1302         _read_guard: RwLockReadGuard<'a, ()>,
1303 }
1304
1305 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1306         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1307         /// events to handle.
1308         ///
1309         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1310         /// other cases where losing the changes on restart may result in a force-close or otherwise
1311         /// isn't ideal.
1312         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1313                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1314         }
1315
1316         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1317         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1318                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1319                 let force_notify = cm.get_cm().process_background_events();
1320
1321                 PersistenceNotifierGuard {
1322                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1323                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1324                         should_persist: move || {
1325                                 // Pick the "most" action between `persist_check` and the background events
1326                                 // processing and return that.
1327                                 let notify = persist_check();
1328                                 match (notify, force_notify) {
1329                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1330                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1331                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1332                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1333                                         _ => NotifyOption::SkipPersistNoEvents,
1334                                 }
1335                         },
1336                         _read_guard: read_guard,
1337                 }
1338         }
1339
1340         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1341         /// [`ChannelManager::process_background_events`] MUST be called first (or
1342         /// [`Self::optionally_notify`] used).
1343         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1344         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1345                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1346
1347                 PersistenceNotifierGuard {
1348                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1349                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1350                         should_persist: persist_check,
1351                         _read_guard: read_guard,
1352                 }
1353         }
1354 }
1355
1356 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1357         fn drop(&mut self) {
1358                 match (self.should_persist)() {
1359                         NotifyOption::DoPersist => {
1360                                 self.needs_persist_flag.store(true, Ordering::Release);
1361                                 self.event_persist_notifier.notify()
1362                         },
1363                         NotifyOption::SkipPersistHandleEvents =>
1364                                 self.event_persist_notifier.notify(),
1365                         NotifyOption::SkipPersistNoEvents => {},
1366                 }
1367         }
1368 }
1369
1370 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1371 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1372 ///
1373 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1374 ///
1375 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1376 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1377 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1378 /// the maximum required amount in lnd as of March 2021.
1379 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1380
1381 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1382 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1383 ///
1384 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1385 ///
1386 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1387 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1388 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1389 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1390 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1391 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1392 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1393 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1394 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1395 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1396 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1397 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1398 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1399
1400 /// Minimum CLTV difference between the current block height and received inbound payments.
1401 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1402 /// this value.
1403 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1404 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1405 // a payment was being routed, so we add an extra block to be safe.
1406 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1407
1408 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1409 // ie that if the next-hop peer fails the HTLC within
1410 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1411 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1412 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1413 // LATENCY_GRACE_PERIOD_BLOCKS.
1414 #[deny(const_err)]
1415 #[allow(dead_code)]
1416 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;
1417
1418 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1419 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1420 #[deny(const_err)]
1421 #[allow(dead_code)]
1422 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1423
1424 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1425 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1426
1427 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1428 /// until we mark the channel disabled and gossip the update.
1429 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1430
1431 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1432 /// we mark the channel enabled and gossip the update.
1433 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1434
1435 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1436 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1437 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1438 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1439
1440 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1441 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1442 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1443
1444 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1445 /// many peers we reject new (inbound) connections.
1446 const MAX_NO_CHANNEL_PEERS: usize = 250;
1447
1448 /// Information needed for constructing an invoice route hint for this channel.
1449 #[derive(Clone, Debug, PartialEq)]
1450 pub struct CounterpartyForwardingInfo {
1451         /// Base routing fee in millisatoshis.
1452         pub fee_base_msat: u32,
1453         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1454         pub fee_proportional_millionths: u32,
1455         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1456         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1457         /// `cltv_expiry_delta` for more details.
1458         pub cltv_expiry_delta: u16,
1459 }
1460
1461 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1462 /// to better separate parameters.
1463 #[derive(Clone, Debug, PartialEq)]
1464 pub struct ChannelCounterparty {
1465         /// The node_id of our counterparty
1466         pub node_id: PublicKey,
1467         /// The Features the channel counterparty provided upon last connection.
1468         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1469         /// many routing-relevant features are present in the init context.
1470         pub features: InitFeatures,
1471         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1472         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1473         /// claiming at least this value on chain.
1474         ///
1475         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1476         ///
1477         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1478         pub unspendable_punishment_reserve: u64,
1479         /// Information on the fees and requirements that the counterparty requires when forwarding
1480         /// payments to us through this channel.
1481         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1482         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1483         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1484         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1485         pub outbound_htlc_minimum_msat: Option<u64>,
1486         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1487         pub outbound_htlc_maximum_msat: Option<u64>,
1488 }
1489
1490 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1491 #[derive(Clone, Debug, PartialEq)]
1492 pub struct ChannelDetails {
1493         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1494         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1495         /// Note that this means this value is *not* persistent - it can change once during the
1496         /// lifetime of the channel.
1497         pub channel_id: ChannelId,
1498         /// Parameters which apply to our counterparty. See individual fields for more information.
1499         pub counterparty: ChannelCounterparty,
1500         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1501         /// our counterparty already.
1502         ///
1503         /// Note that, if this has been set, `channel_id` will be equivalent to
1504         /// `funding_txo.unwrap().to_channel_id()`.
1505         pub funding_txo: Option<OutPoint>,
1506         /// The features which this channel operates with. See individual features for more info.
1507         ///
1508         /// `None` until negotiation completes and the channel type is finalized.
1509         pub channel_type: Option<ChannelTypeFeatures>,
1510         /// The position of the funding transaction in the chain. None if the funding transaction has
1511         /// not yet been confirmed and the channel fully opened.
1512         ///
1513         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1514         /// payments instead of this. See [`get_inbound_payment_scid`].
1515         ///
1516         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1517         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1518         ///
1519         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1520         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1521         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1522         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1523         /// [`confirmations_required`]: Self::confirmations_required
1524         pub short_channel_id: Option<u64>,
1525         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1526         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1527         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1528         /// `Some(0)`).
1529         ///
1530         /// This will be `None` as long as the channel is not available for routing outbound payments.
1531         ///
1532         /// [`short_channel_id`]: Self::short_channel_id
1533         /// [`confirmations_required`]: Self::confirmations_required
1534         pub outbound_scid_alias: Option<u64>,
1535         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1536         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1537         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1538         /// when they see a payment to be routed to us.
1539         ///
1540         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1541         /// previous values for inbound payment forwarding.
1542         ///
1543         /// [`short_channel_id`]: Self::short_channel_id
1544         pub inbound_scid_alias: Option<u64>,
1545         /// The value, in satoshis, of this channel as appears in the funding output
1546         pub channel_value_satoshis: u64,
1547         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1548         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1549         /// this value on chain.
1550         ///
1551         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1552         ///
1553         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1554         ///
1555         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1556         pub unspendable_punishment_reserve: Option<u64>,
1557         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1558         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1559         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1560         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1561         /// serialized with LDK versions prior to 0.0.113.
1562         ///
1563         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1564         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1565         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1566         pub user_channel_id: u128,
1567         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1568         /// which is applied to commitment and HTLC transactions.
1569         ///
1570         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1571         pub feerate_sat_per_1000_weight: Option<u32>,
1572         /// Our total balance.  This is the amount we would get if we close the channel.
1573         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1574         /// amount is not likely to be recoverable on close.
1575         ///
1576         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1577         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1578         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1579         /// This does not consider any on-chain fees.
1580         ///
1581         /// See also [`ChannelDetails::outbound_capacity_msat`]
1582         pub balance_msat: u64,
1583         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1584         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1585         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1586         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1587         ///
1588         /// See also [`ChannelDetails::balance_msat`]
1589         ///
1590         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1591         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1592         /// should be able to spend nearly this amount.
1593         pub outbound_capacity_msat: u64,
1594         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1595         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1596         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1597         /// to use a limit as close as possible to the HTLC limit we can currently send.
1598         ///
1599         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1600         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1601         pub next_outbound_htlc_limit_msat: u64,
1602         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1603         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1604         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1605         /// route which is valid.
1606         pub next_outbound_htlc_minimum_msat: u64,
1607         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1608         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1609         /// available for inclusion in new inbound HTLCs).
1610         /// Note that there are some corner cases not fully handled here, so the actual available
1611         /// inbound capacity may be slightly higher than this.
1612         ///
1613         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1614         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1615         /// However, our counterparty should be able to spend nearly this amount.
1616         pub inbound_capacity_msat: u64,
1617         /// The number of required confirmations on the funding transaction before the funding will be
1618         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1619         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1620         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1621         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1622         ///
1623         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1624         ///
1625         /// [`is_outbound`]: ChannelDetails::is_outbound
1626         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1627         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1628         pub confirmations_required: Option<u32>,
1629         /// The current number of confirmations on the funding transaction.
1630         ///
1631         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1632         pub confirmations: Option<u32>,
1633         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1634         /// until we can claim our funds after we force-close the channel. During this time our
1635         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1636         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1637         /// time to claim our non-HTLC-encumbered funds.
1638         ///
1639         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1640         pub force_close_spend_delay: Option<u16>,
1641         /// True if the channel was initiated (and thus funded) by us.
1642         pub is_outbound: bool,
1643         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1644         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1645         /// required confirmation count has been reached (and we were connected to the peer at some
1646         /// point after the funding transaction received enough confirmations). The required
1647         /// confirmation count is provided in [`confirmations_required`].
1648         ///
1649         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1650         pub is_channel_ready: bool,
1651         /// The stage of the channel's shutdown.
1652         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1653         pub channel_shutdown_state: Option<ChannelShutdownState>,
1654         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1655         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1656         ///
1657         /// This is a strict superset of `is_channel_ready`.
1658         pub is_usable: bool,
1659         /// True if this channel is (or will be) publicly-announced.
1660         pub is_public: bool,
1661         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1662         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1663         pub inbound_htlc_minimum_msat: Option<u64>,
1664         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1665         pub inbound_htlc_maximum_msat: Option<u64>,
1666         /// Set of configurable parameters that affect channel operation.
1667         ///
1668         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1669         pub config: Option<ChannelConfig>,
1670 }
1671
1672 impl ChannelDetails {
1673         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1674         /// This should be used for providing invoice hints or in any other context where our
1675         /// counterparty will forward a payment to us.
1676         ///
1677         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1678         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1679         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1680                 self.inbound_scid_alias.or(self.short_channel_id)
1681         }
1682
1683         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1684         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1685         /// we're sending or forwarding a payment outbound over this channel.
1686         ///
1687         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1688         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1689         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1690                 self.short_channel_id.or(self.outbound_scid_alias)
1691         }
1692
1693         fn from_channel_context<SP: Deref, F: Deref>(
1694                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1695                 fee_estimator: &LowerBoundedFeeEstimator<F>
1696         ) -> Self
1697         where
1698                 SP::Target: SignerProvider,
1699                 F::Target: FeeEstimator
1700         {
1701                 let balance = context.get_available_balances(fee_estimator);
1702                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1703                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1704                 ChannelDetails {
1705                         channel_id: context.channel_id(),
1706                         counterparty: ChannelCounterparty {
1707                                 node_id: context.get_counterparty_node_id(),
1708                                 features: latest_features,
1709                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1710                                 forwarding_info: context.counterparty_forwarding_info(),
1711                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1712                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1713                                 // message (as they are always the first message from the counterparty).
1714                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1715                                 // default `0` value set by `Channel::new_outbound`.
1716                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1717                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1718                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1719                         },
1720                         funding_txo: context.get_funding_txo(),
1721                         // Note that accept_channel (or open_channel) is always the first message, so
1722                         // `have_received_message` indicates that type negotiation has completed.
1723                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1724                         short_channel_id: context.get_short_channel_id(),
1725                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1726                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1727                         channel_value_satoshis: context.get_value_satoshis(),
1728                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1729                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1730                         balance_msat: balance.balance_msat,
1731                         inbound_capacity_msat: balance.inbound_capacity_msat,
1732                         outbound_capacity_msat: balance.outbound_capacity_msat,
1733                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1734                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1735                         user_channel_id: context.get_user_id(),
1736                         confirmations_required: context.minimum_depth(),
1737                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1738                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1739                         is_outbound: context.is_outbound(),
1740                         is_channel_ready: context.is_usable(),
1741                         is_usable: context.is_live(),
1742                         is_public: context.should_announce(),
1743                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1744                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1745                         config: Some(context.config()),
1746                         channel_shutdown_state: Some(context.shutdown_state()),
1747                 }
1748         }
1749 }
1750
1751 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1752 /// Further information on the details of the channel shutdown.
1753 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1754 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1755 /// the channel will be removed shortly.
1756 /// Also note, that in normal operation, peers could disconnect at any of these states
1757 /// and require peer re-connection before making progress onto other states
1758 pub enum ChannelShutdownState {
1759         /// Channel has not sent or received a shutdown message.
1760         NotShuttingDown,
1761         /// Local node has sent a shutdown message for this channel.
1762         ShutdownInitiated,
1763         /// Shutdown message exchanges have concluded and the channels are in the midst of
1764         /// resolving all existing open HTLCs before closing can continue.
1765         ResolvingHTLCs,
1766         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1767         NegotiatingClosingFee,
1768         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1769         /// to drop the channel.
1770         ShutdownComplete,
1771 }
1772
1773 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1774 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1775 #[derive(Debug, PartialEq)]
1776 pub enum RecentPaymentDetails {
1777         /// When an invoice was requested and thus a payment has not yet been sent.
1778         AwaitingInvoice {
1779                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1780                 /// a payment and ensure idempotency in LDK.
1781                 payment_id: PaymentId,
1782         },
1783         /// When a payment is still being sent and awaiting successful delivery.
1784         Pending {
1785                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1786                 /// a payment and ensure idempotency in LDK.
1787                 payment_id: PaymentId,
1788                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1789                 /// abandoned.
1790                 payment_hash: PaymentHash,
1791                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1792                 /// not just the amount currently inflight.
1793                 total_msat: u64,
1794         },
1795         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1796         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1797         /// payment is removed from tracking.
1798         Fulfilled {
1799                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1800                 /// a payment and ensure idempotency in LDK.
1801                 payment_id: PaymentId,
1802                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1803                 /// made before LDK version 0.0.104.
1804                 payment_hash: Option<PaymentHash>,
1805         },
1806         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1807         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1808         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1809         Abandoned {
1810                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1811                 /// a payment and ensure idempotency in LDK.
1812                 payment_id: PaymentId,
1813                 /// Hash of the payment that we have given up trying to send.
1814                 payment_hash: PaymentHash,
1815         },
1816 }
1817
1818 /// Route hints used in constructing invoices for [phantom node payents].
1819 ///
1820 /// [phantom node payments]: crate::sign::PhantomKeysManager
1821 #[derive(Clone)]
1822 pub struct PhantomRouteHints {
1823         /// The list of channels to be included in the invoice route hints.
1824         pub channels: Vec<ChannelDetails>,
1825         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1826         /// route hints.
1827         pub phantom_scid: u64,
1828         /// The pubkey of the real backing node that would ultimately receive the payment.
1829         pub real_node_pubkey: PublicKey,
1830 }
1831
1832 macro_rules! handle_error {
1833         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1834                 // In testing, ensure there are no deadlocks where the lock is already held upon
1835                 // entering the macro.
1836                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1837                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1838
1839                 match $internal {
1840                         Ok(msg) => Ok(msg),
1841                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1842                                 let mut msg_events = Vec::with_capacity(2);
1843
1844                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1845                                         $self.finish_close_channel(shutdown_res);
1846                                         if let Some(update) = update_option {
1847                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1848                                                         msg: update
1849                                                 });
1850                                         }
1851                                         if let Some((channel_id, user_channel_id)) = chan_id {
1852                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1853                                                         channel_id, user_channel_id,
1854                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1855                                                         counterparty_node_id: Some($counterparty_node_id),
1856                                                         channel_capacity_sats: channel_capacity,
1857                                                 }, None));
1858                                         }
1859                                 }
1860
1861                                 log_error!($self.logger, "{}", err.err);
1862                                 if let msgs::ErrorAction::IgnoreError = err.action {
1863                                 } else {
1864                                         msg_events.push(events::MessageSendEvent::HandleError {
1865                                                 node_id: $counterparty_node_id,
1866                                                 action: err.action.clone()
1867                                         });
1868                                 }
1869
1870                                 if !msg_events.is_empty() {
1871                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1872                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1873                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1874                                                 peer_state.pending_msg_events.append(&mut msg_events);
1875                                         }
1876                                 }
1877
1878                                 // Return error in case higher-API need one
1879                                 Err(err)
1880                         },
1881                 }
1882         } };
1883         ($self: ident, $internal: expr) => {
1884                 match $internal {
1885                         Ok(res) => Ok(res),
1886                         Err((chan, msg_handle_err)) => {
1887                                 let counterparty_node_id = chan.get_counterparty_node_id();
1888                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1889                         },
1890                 }
1891         };
1892 }
1893
1894 macro_rules! update_maps_on_chan_removal {
1895         ($self: expr, $channel_context: expr) => {{
1896                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1897                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1898                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1899                         short_to_chan_info.remove(&short_id);
1900                 } else {
1901                         // If the channel was never confirmed on-chain prior to its closure, remove the
1902                         // outbound SCID alias we used for it from the collision-prevention set. While we
1903                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1904                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1905                         // opening a million channels with us which are closed before we ever reach the funding
1906                         // stage.
1907                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1908                         debug_assert!(alias_removed);
1909                 }
1910                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1911         }}
1912 }
1913
1914 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1915 macro_rules! convert_chan_phase_err {
1916         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
1917                 match $err {
1918                         ChannelError::Warn(msg) => {
1919                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
1920                         },
1921                         ChannelError::Ignore(msg) => {
1922                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
1923                         },
1924                         ChannelError::Close(msg) => {
1925                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
1926                                 update_maps_on_chan_removal!($self, $channel.context);
1927                                 let shutdown_res = $channel.context.force_shutdown(true);
1928                                 let user_id = $channel.context.get_user_id();
1929                                 let channel_capacity_satoshis = $channel.context.get_value_satoshis();
1930
1931                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, user_id,
1932                                         shutdown_res, $channel_update, channel_capacity_satoshis))
1933                         },
1934                 }
1935         };
1936         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
1937                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
1938         };
1939         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
1940                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
1941         };
1942         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
1943                 match $channel_phase {
1944                         ChannelPhase::Funded(channel) => {
1945                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
1946                         },
1947                         ChannelPhase::UnfundedOutboundV1(channel) => {
1948                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1949                         },
1950                         ChannelPhase::UnfundedInboundV1(channel) => {
1951                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1952                         },
1953                 }
1954         };
1955 }
1956
1957 macro_rules! break_chan_phase_entry {
1958         ($self: ident, $res: expr, $entry: expr) => {
1959                 match $res {
1960                         Ok(res) => res,
1961                         Err(e) => {
1962                                 let key = *$entry.key();
1963                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1964                                 if drop {
1965                                         $entry.remove_entry();
1966                                 }
1967                                 break Err(res);
1968                         }
1969                 }
1970         }
1971 }
1972
1973 macro_rules! try_chan_phase_entry {
1974         ($self: ident, $res: expr, $entry: expr) => {
1975                 match $res {
1976                         Ok(res) => res,
1977                         Err(e) => {
1978                                 let key = *$entry.key();
1979                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1980                                 if drop {
1981                                         $entry.remove_entry();
1982                                 }
1983                                 return Err(res);
1984                         }
1985                 }
1986         }
1987 }
1988
1989 macro_rules! remove_channel_phase {
1990         ($self: expr, $entry: expr) => {
1991                 {
1992                         let channel = $entry.remove_entry().1;
1993                         update_maps_on_chan_removal!($self, &channel.context());
1994                         channel
1995                 }
1996         }
1997 }
1998
1999 macro_rules! send_channel_ready {
2000         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2001                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2002                         node_id: $channel.context.get_counterparty_node_id(),
2003                         msg: $channel_ready_msg,
2004                 });
2005                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2006                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2007                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2008                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2009                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2010                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2011                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2012                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2013                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2014                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2015                 }
2016         }}
2017 }
2018
2019 macro_rules! emit_channel_pending_event {
2020         ($locked_events: expr, $channel: expr) => {
2021                 if $channel.context.should_emit_channel_pending_event() {
2022                         $locked_events.push_back((events::Event::ChannelPending {
2023                                 channel_id: $channel.context.channel_id(),
2024                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2025                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2026                                 user_channel_id: $channel.context.get_user_id(),
2027                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2028                         }, None));
2029                         $channel.context.set_channel_pending_event_emitted();
2030                 }
2031         }
2032 }
2033
2034 macro_rules! emit_channel_ready_event {
2035         ($locked_events: expr, $channel: expr) => {
2036                 if $channel.context.should_emit_channel_ready_event() {
2037                         debug_assert!($channel.context.channel_pending_event_emitted());
2038                         $locked_events.push_back((events::Event::ChannelReady {
2039                                 channel_id: $channel.context.channel_id(),
2040                                 user_channel_id: $channel.context.get_user_id(),
2041                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2042                                 channel_type: $channel.context.get_channel_type().clone(),
2043                         }, None));
2044                         $channel.context.set_channel_ready_event_emitted();
2045                 }
2046         }
2047 }
2048
2049 macro_rules! handle_monitor_update_completion {
2050         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2051                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
2052                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2053                         $self.best_block.read().unwrap().height());
2054                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2055                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2056                         // We only send a channel_update in the case where we are just now sending a
2057                         // channel_ready and the channel is in a usable state. We may re-send a
2058                         // channel_update later through the announcement_signatures process for public
2059                         // channels, but there's no reason not to just inform our counterparty of our fees
2060                         // now.
2061                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2062                                 Some(events::MessageSendEvent::SendChannelUpdate {
2063                                         node_id: counterparty_node_id,
2064                                         msg,
2065                                 })
2066                         } else { None }
2067                 } else { None };
2068
2069                 let update_actions = $peer_state.monitor_update_blocked_actions
2070                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2071
2072                 let htlc_forwards = $self.handle_channel_resumption(
2073                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2074                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2075                         updates.funding_broadcastable, updates.channel_ready,
2076                         updates.announcement_sigs);
2077                 if let Some(upd) = channel_update {
2078                         $peer_state.pending_msg_events.push(upd);
2079                 }
2080
2081                 let channel_id = $chan.context.channel_id();
2082                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2083                 core::mem::drop($peer_state_lock);
2084                 core::mem::drop($per_peer_state_lock);
2085
2086                 // If the channel belongs to a batch funding transaction, the progress of the batch
2087                 // should be updated as we have received funding_signed and persisted the monitor.
2088                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2089                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2090                         let mut batch_completed = false;
2091                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2092                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2093                                         *chan_id == channel_id &&
2094                                         *pubkey == counterparty_node_id
2095                                 ));
2096                                 if let Some(channel_state) = channel_state {
2097                                         channel_state.2 = true;
2098                                 } else {
2099                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2100                                 }
2101                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2102                         } else {
2103                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2104                         }
2105
2106                         // When all channels in a batched funding transaction have become ready, it is not necessary
2107                         // to track the progress of the batch anymore and the state of the channels can be updated.
2108                         if batch_completed {
2109                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2110                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2111                                 let mut batch_funding_tx = None;
2112                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2113                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2114                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2115                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2116                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2117                                                         chan.set_batch_ready();
2118                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2119                                                         emit_channel_pending_event!(pending_events, chan);
2120                                                 }
2121                                         }
2122                                 }
2123                                 if let Some(tx) = batch_funding_tx {
2124                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2125                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2126                                 }
2127                         }
2128                 }
2129
2130                 $self.handle_monitor_update_completion_actions(update_actions);
2131
2132                 if let Some(forwards) = htlc_forwards {
2133                         $self.forward_htlcs(&mut [forwards][..]);
2134                 }
2135                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2136                 for failure in updates.failed_htlcs.drain(..) {
2137                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2138                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2139                 }
2140         } }
2141 }
2142
2143 macro_rules! handle_new_monitor_update {
2144         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2145                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2146                 match $update_res {
2147                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2148                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2149                                 log_error!($self.logger, "{}", err_str);
2150                                 panic!("{}", err_str);
2151                         },
2152                         ChannelMonitorUpdateStatus::InProgress => {
2153                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2154                                         &$chan.context.channel_id());
2155                                 false
2156                         },
2157                         ChannelMonitorUpdateStatus::Completed => {
2158                                 $completed;
2159                                 true
2160                         },
2161                 }
2162         } };
2163         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2164                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2165                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2166         };
2167         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2168                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2169                         .or_insert_with(Vec::new);
2170                 // During startup, we push monitor updates as background events through to here in
2171                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2172                 // filter for uniqueness here.
2173                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2174                         .unwrap_or_else(|| {
2175                                 in_flight_updates.push($update);
2176                                 in_flight_updates.len() - 1
2177                         });
2178                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2179                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2180                         {
2181                                 let _ = in_flight_updates.remove(idx);
2182                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2183                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2184                                 }
2185                         })
2186         } };
2187 }
2188
2189 macro_rules! process_events_body {
2190         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2191                 let mut processed_all_events = false;
2192                 while !processed_all_events {
2193                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2194                                 return;
2195                         }
2196
2197                         let mut result;
2198
2199                         {
2200                                 // We'll acquire our total consistency lock so that we can be sure no other
2201                                 // persists happen while processing monitor events.
2202                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2203
2204                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2205                                 // ensure any startup-generated background events are handled first.
2206                                 result = $self.process_background_events();
2207
2208                                 // TODO: This behavior should be documented. It's unintuitive that we query
2209                                 // ChannelMonitors when clearing other events.
2210                                 if $self.process_pending_monitor_events() {
2211                                         result = NotifyOption::DoPersist;
2212                                 }
2213                         }
2214
2215                         let pending_events = $self.pending_events.lock().unwrap().clone();
2216                         let num_events = pending_events.len();
2217                         if !pending_events.is_empty() {
2218                                 result = NotifyOption::DoPersist;
2219                         }
2220
2221                         let mut post_event_actions = Vec::new();
2222
2223                         for (event, action_opt) in pending_events {
2224                                 $event_to_handle = event;
2225                                 $handle_event;
2226                                 if let Some(action) = action_opt {
2227                                         post_event_actions.push(action);
2228                                 }
2229                         }
2230
2231                         {
2232                                 let mut pending_events = $self.pending_events.lock().unwrap();
2233                                 pending_events.drain(..num_events);
2234                                 processed_all_events = pending_events.is_empty();
2235                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2236                                 // updated here with the `pending_events` lock acquired.
2237                                 $self.pending_events_processor.store(false, Ordering::Release);
2238                         }
2239
2240                         if !post_event_actions.is_empty() {
2241                                 $self.handle_post_event_actions(post_event_actions);
2242                                 // If we had some actions, go around again as we may have more events now
2243                                 processed_all_events = false;
2244                         }
2245
2246                         match result {
2247                                 NotifyOption::DoPersist => {
2248                                         $self.needs_persist_flag.store(true, Ordering::Release);
2249                                         $self.event_persist_notifier.notify();
2250                                 },
2251                                 NotifyOption::SkipPersistHandleEvents =>
2252                                         $self.event_persist_notifier.notify(),
2253                                 NotifyOption::SkipPersistNoEvents => {},
2254                         }
2255                 }
2256         }
2257 }
2258
2259 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>
2260 where
2261         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2262         T::Target: BroadcasterInterface,
2263         ES::Target: EntropySource,
2264         NS::Target: NodeSigner,
2265         SP::Target: SignerProvider,
2266         F::Target: FeeEstimator,
2267         R::Target: Router,
2268         L::Target: Logger,
2269 {
2270         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2271         ///
2272         /// The current time or latest block header time can be provided as the `current_timestamp`.
2273         ///
2274         /// This is the main "logic hub" for all channel-related actions, and implements
2275         /// [`ChannelMessageHandler`].
2276         ///
2277         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2278         ///
2279         /// Users need to notify the new `ChannelManager` when a new block is connected or
2280         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2281         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2282         /// more details.
2283         ///
2284         /// [`block_connected`]: chain::Listen::block_connected
2285         /// [`block_disconnected`]: chain::Listen::block_disconnected
2286         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2287         pub fn new(
2288                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2289                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2290                 current_timestamp: u32,
2291         ) -> Self {
2292                 let mut secp_ctx = Secp256k1::new();
2293                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2294                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2295                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2296                 ChannelManager {
2297                         default_configuration: config.clone(),
2298                         chain_hash: ChainHash::using_genesis_block(params.network),
2299                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2300                         chain_monitor,
2301                         tx_broadcaster,
2302                         router,
2303
2304                         best_block: RwLock::new(params.best_block),
2305
2306                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2307                         pending_inbound_payments: Mutex::new(HashMap::new()),
2308                         pending_outbound_payments: OutboundPayments::new(),
2309                         forward_htlcs: Mutex::new(HashMap::new()),
2310                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2311                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2312                         id_to_peer: Mutex::new(HashMap::new()),
2313                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2314
2315                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2316                         secp_ctx,
2317
2318                         inbound_payment_key: expanded_inbound_key,
2319                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2320
2321                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2322
2323                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2324
2325                         per_peer_state: FairRwLock::new(HashMap::new()),
2326
2327                         pending_events: Mutex::new(VecDeque::new()),
2328                         pending_events_processor: AtomicBool::new(false),
2329                         pending_background_events: Mutex::new(Vec::new()),
2330                         total_consistency_lock: RwLock::new(()),
2331                         background_events_processed_since_startup: AtomicBool::new(false),
2332                         event_persist_notifier: Notifier::new(),
2333                         needs_persist_flag: AtomicBool::new(false),
2334                         funding_batch_states: Mutex::new(BTreeMap::new()),
2335
2336                         pending_offers_messages: Mutex::new(Vec::new()),
2337
2338                         entropy_source,
2339                         node_signer,
2340                         signer_provider,
2341
2342                         logger,
2343                 }
2344         }
2345
2346         /// Gets the current configuration applied to all new channels.
2347         pub fn get_current_default_configuration(&self) -> &UserConfig {
2348                 &self.default_configuration
2349         }
2350
2351         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2352                 let height = self.best_block.read().unwrap().height();
2353                 let mut outbound_scid_alias = 0;
2354                 let mut i = 0;
2355                 loop {
2356                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2357                                 outbound_scid_alias += 1;
2358                         } else {
2359                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2360                         }
2361                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2362                                 break;
2363                         }
2364                         i += 1;
2365                         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"); }
2366                 }
2367                 outbound_scid_alias
2368         }
2369
2370         /// Creates a new outbound channel to the given remote node and with the given value.
2371         ///
2372         /// `user_channel_id` will be provided back as in
2373         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2374         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2375         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2376         /// is simply copied to events and otherwise ignored.
2377         ///
2378         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2379         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2380         ///
2381         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2382         /// generate a shutdown scriptpubkey or destination script set by
2383         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2384         ///
2385         /// Note that we do not check if you are currently connected to the given peer. If no
2386         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2387         /// the channel eventually being silently forgotten (dropped on reload).
2388         ///
2389         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2390         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2391         /// [`ChannelDetails::channel_id`] until after
2392         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2393         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2394         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2395         ///
2396         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2397         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2398         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2399         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_channel_id: u128, override_config: Option<UserConfig>) -> Result<ChannelId, APIError> {
2400                 if channel_value_satoshis < 1000 {
2401                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2402                 }
2403
2404                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2405                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2406                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2407
2408                 let per_peer_state = self.per_peer_state.read().unwrap();
2409
2410                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2411                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2412
2413                 let mut peer_state = peer_state_mutex.lock().unwrap();
2414                 let channel = {
2415                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2416                         let their_features = &peer_state.latest_features;
2417                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2418                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2419                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2420                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2421                         {
2422                                 Ok(res) => res,
2423                                 Err(e) => {
2424                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2425                                         return Err(e);
2426                                 },
2427                         }
2428                 };
2429                 let res = channel.get_open_channel(self.chain_hash);
2430
2431                 let temporary_channel_id = channel.context.channel_id();
2432                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2433                         hash_map::Entry::Occupied(_) => {
2434                                 if cfg!(fuzzing) {
2435                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2436                                 } else {
2437                                         panic!("RNG is bad???");
2438                                 }
2439                         },
2440                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2441                 }
2442
2443                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2444                         node_id: their_network_key,
2445                         msg: res,
2446                 });
2447                 Ok(temporary_channel_id)
2448         }
2449
2450         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2451                 // Allocate our best estimate of the number of channels we have in the `res`
2452                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2453                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2454                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2455                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2456                 // the same channel.
2457                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2458                 {
2459                         let best_block_height = self.best_block.read().unwrap().height();
2460                         let per_peer_state = self.per_peer_state.read().unwrap();
2461                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2462                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2463                                 let peer_state = &mut *peer_state_lock;
2464                                 res.extend(peer_state.channel_by_id.iter()
2465                                         .filter_map(|(chan_id, phase)| match phase {
2466                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2467                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2468                                                 _ => None,
2469                                         })
2470                                         .filter(f)
2471                                         .map(|(_channel_id, channel)| {
2472                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2473                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2474                                         })
2475                                 );
2476                         }
2477                 }
2478                 res
2479         }
2480
2481         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2482         /// more information.
2483         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2484                 // Allocate our best estimate of the number of channels we have in the `res`
2485                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2486                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2487                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2488                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2489                 // the same channel.
2490                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2491                 {
2492                         let best_block_height = self.best_block.read().unwrap().height();
2493                         let per_peer_state = self.per_peer_state.read().unwrap();
2494                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2495                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2496                                 let peer_state = &mut *peer_state_lock;
2497                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2498                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2499                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2500                                         res.push(details);
2501                                 }
2502                         }
2503                 }
2504                 res
2505         }
2506
2507         /// Gets the list of usable channels, in random order. Useful as an argument to
2508         /// [`Router::find_route`] to ensure non-announced channels are used.
2509         ///
2510         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2511         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2512         /// are.
2513         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2514                 // Note we use is_live here instead of usable which leads to somewhat confused
2515                 // internal/external nomenclature, but that's ok cause that's probably what the user
2516                 // really wanted anyway.
2517                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2518         }
2519
2520         /// Gets the list of channels we have with a given counterparty, in random order.
2521         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2522                 let best_block_height = self.best_block.read().unwrap().height();
2523                 let per_peer_state = self.per_peer_state.read().unwrap();
2524
2525                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2526                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2527                         let peer_state = &mut *peer_state_lock;
2528                         let features = &peer_state.latest_features;
2529                         let context_to_details = |context| {
2530                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2531                         };
2532                         return peer_state.channel_by_id
2533                                 .iter()
2534                                 .map(|(_, phase)| phase.context())
2535                                 .map(context_to_details)
2536                                 .collect();
2537                 }
2538                 vec![]
2539         }
2540
2541         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2542         /// successful path, or have unresolved HTLCs.
2543         ///
2544         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2545         /// result of a crash. If such a payment exists, is not listed here, and an
2546         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2547         ///
2548         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2549         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2550                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2551                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2552                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2553                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2554                                 },
2555                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2556                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2557                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2558                                 },
2559                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2560                                         Some(RecentPaymentDetails::Pending {
2561                                                 payment_id: *payment_id,
2562                                                 payment_hash: *payment_hash,
2563                                                 total_msat: *total_msat,
2564                                         })
2565                                 },
2566                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2567                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2568                                 },
2569                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2570                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2571                                 },
2572                                 PendingOutboundPayment::Legacy { .. } => None
2573                         })
2574                         .collect()
2575         }
2576
2577         /// Helper function that issues the channel close events
2578         fn issue_channel_close_events(&self, context: &ChannelContext<SP>, closure_reason: ClosureReason) {
2579                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2580                 match context.unbroadcasted_funding() {
2581                         Some(transaction) => {
2582                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2583                                         channel_id: context.channel_id(), transaction
2584                                 }, None));
2585                         },
2586                         None => {},
2587                 }
2588                 pending_events_lock.push_back((events::Event::ChannelClosed {
2589                         channel_id: context.channel_id(),
2590                         user_channel_id: context.get_user_id(),
2591                         reason: closure_reason,
2592                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2593                         channel_capacity_sats: Some(context.get_value_satoshis()),
2594                 }, None));
2595         }
2596
2597         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> {
2598                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2599
2600                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2601                 let mut shutdown_result = None;
2602                 loop {
2603                         let per_peer_state = self.per_peer_state.read().unwrap();
2604
2605                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2606                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2607
2608                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2609                         let peer_state = &mut *peer_state_lock;
2610
2611                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2612                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2613                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2614                                                 let funding_txo_opt = chan.context.get_funding_txo();
2615                                                 let their_features = &peer_state.latest_features;
2616                                                 let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
2617                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2618                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2619                                                 failed_htlcs = htlcs;
2620
2621                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2622                                                 // here as we don't need the monitor update to complete until we send a
2623                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2624                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2625                                                         node_id: *counterparty_node_id,
2626                                                         msg: shutdown_msg,
2627                                                 });
2628
2629                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2630                                                         "We can't both complete shutdown and generate a monitor update");
2631
2632                                                 // Update the monitor with the shutdown script if necessary.
2633                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2634                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2635                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2636                                                         break;
2637                                                 }
2638
2639                                                 if chan.is_shutdown() {
2640                                                         if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2641                                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2642                                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2643                                                                                 msg: channel_update
2644                                                                         });
2645                                                                 }
2646                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2647                                                                 shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
2648                                                         }
2649                                                 }
2650                                                 break;
2651                                         }
2652                                 },
2653                                 hash_map::Entry::Vacant(_) => {
2654                                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2655                                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2656                                         //
2657                                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2658                                         mem::drop(peer_state_lock);
2659                                         mem::drop(per_peer_state);
2660                                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2661                                 },
2662                         }
2663                 }
2664
2665                 for htlc_source in failed_htlcs.drain(..) {
2666                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2667                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2668                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2669                 }
2670
2671                 if let Some(shutdown_result) = shutdown_result {
2672                         self.finish_close_channel(shutdown_result);
2673                 }
2674
2675                 Ok(())
2676         }
2677
2678         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2679         /// will be accepted on the given channel, and after additional timeout/the closing of all
2680         /// pending HTLCs, the channel will be closed on chain.
2681         ///
2682         ///  * If we are the channel initiator, we will pay between our [`Background`] and
2683         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2684         ///    estimate.
2685         ///  * If our counterparty is the channel initiator, we will require a channel closing
2686         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
2687         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2688         ///    counterparty to pay as much fee as they'd like, however.
2689         ///
2690         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2691         ///
2692         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2693         /// generate a shutdown scriptpubkey or destination script set by
2694         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2695         /// channel.
2696         ///
2697         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2698         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2699         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2700         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2701         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2702                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2703         }
2704
2705         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2706         /// will be accepted on the given channel, and after additional timeout/the closing of all
2707         /// pending HTLCs, the channel will be closed on chain.
2708         ///
2709         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2710         /// the channel being closed or not:
2711         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2712         ///    transaction. The upper-bound is set by
2713         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2714         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2715         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2716         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2717         ///    will appear on a force-closure transaction, whichever is lower).
2718         ///
2719         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2720         /// Will fail if a shutdown script has already been set for this channel by
2721         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2722         /// also be compatible with our and the counterparty's features.
2723         ///
2724         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2725         ///
2726         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2727         /// generate a shutdown scriptpubkey or destination script set by
2728         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2729         /// channel.
2730         ///
2731         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2732         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2733         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2734         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2735         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> {
2736                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2737         }
2738
2739         fn finish_close_channel(&self, shutdown_res: ShutdownResult) {
2740                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2741                 #[cfg(debug_assertions)]
2742                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2743                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2744                 }
2745
2746                 let (monitor_update_option, mut failed_htlcs, unbroadcasted_batch_funding_txid) = shutdown_res;
2747                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
2748                 for htlc_source in failed_htlcs.drain(..) {
2749                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2750                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2751                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2752                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2753                 }
2754                 if let Some((_, funding_txo, monitor_update)) = monitor_update_option {
2755                         // There isn't anything we can do if we get an update failure - we're already
2756                         // force-closing. The monitor update on the required in-memory copy should broadcast
2757                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2758                         // ignore the result here.
2759                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2760                 }
2761                 let mut shutdown_results = Vec::new();
2762                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2763                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2764                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2765                         let per_peer_state = self.per_peer_state.read().unwrap();
2766                         let mut has_uncompleted_channel = None;
2767                         for (channel_id, counterparty_node_id, state) in affected_channels {
2768                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2769                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2770                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2771                                                 update_maps_on_chan_removal!(self, &chan.context());
2772                                                 self.issue_channel_close_events(&chan.context(), ClosureReason::FundingBatchClosure);
2773                                                 shutdown_results.push(chan.context_mut().force_shutdown(false));
2774                                         }
2775                                 }
2776                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2777                         }
2778                         debug_assert!(
2779                                 has_uncompleted_channel.unwrap_or(true),
2780                                 "Closing a batch where all channels have completed initial monitor update",
2781                         );
2782                 }
2783                 for shutdown_result in shutdown_results.drain(..) {
2784                         self.finish_close_channel(shutdown_result);
2785                 }
2786         }
2787
2788         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2789         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2790         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2791         -> Result<PublicKey, APIError> {
2792                 let per_peer_state = self.per_peer_state.read().unwrap();
2793                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2794                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2795                 let (update_opt, counterparty_node_id) = {
2796                         let mut peer_state = peer_state_mutex.lock().unwrap();
2797                         let closure_reason = if let Some(peer_msg) = peer_msg {
2798                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2799                         } else {
2800                                 ClosureReason::HolderForceClosed
2801                         };
2802                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2803                                 log_error!(self.logger, "Force-closing channel {}", channel_id);
2804                                 self.issue_channel_close_events(&chan_phase_entry.get().context(), closure_reason);
2805                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2806                                 mem::drop(peer_state);
2807                                 mem::drop(per_peer_state);
2808                                 match chan_phase {
2809                                         ChannelPhase::Funded(mut chan) => {
2810                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast));
2811                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2812                                         },
2813                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2814                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false));
2815                                                 // Unfunded channel has no update
2816                                                 (None, chan_phase.context().get_counterparty_node_id())
2817                                         },
2818                                 }
2819                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2820                                 log_error!(self.logger, "Force-closing channel {}", &channel_id);
2821                                 // N.B. that we don't send any channel close event here: we
2822                                 // don't have a user_channel_id, and we never sent any opening
2823                                 // events anyway.
2824                                 (None, *peer_node_id)
2825                         } else {
2826                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2827                         }
2828                 };
2829                 if let Some(update) = update_opt {
2830                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2831                         // not try to broadcast it via whatever peer we have.
2832                         let per_peer_state = self.per_peer_state.read().unwrap();
2833                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2834                                 .ok_or(per_peer_state.values().next());
2835                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2836                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2837                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2838                                         msg: update
2839                                 });
2840                         }
2841                 }
2842
2843                 Ok(counterparty_node_id)
2844         }
2845
2846         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2847                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2848                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2849                         Ok(counterparty_node_id) => {
2850                                 let per_peer_state = self.per_peer_state.read().unwrap();
2851                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2852                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2853                                         peer_state.pending_msg_events.push(
2854                                                 events::MessageSendEvent::HandleError {
2855                                                         node_id: counterparty_node_id,
2856                                                         action: msgs::ErrorAction::DisconnectPeer {
2857                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2858                                                         },
2859                                                 }
2860                                         );
2861                                 }
2862                                 Ok(())
2863                         },
2864                         Err(e) => Err(e)
2865                 }
2866         }
2867
2868         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2869         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2870         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2871         /// channel.
2872         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2873         -> Result<(), APIError> {
2874                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2875         }
2876
2877         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2878         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2879         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2880         ///
2881         /// You can always get the latest local transaction(s) to broadcast from
2882         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2883         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2884         -> Result<(), APIError> {
2885                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2886         }
2887
2888         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2889         /// for each to the chain and rejecting new HTLCs on each.
2890         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2891                 for chan in self.list_channels() {
2892                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2893                 }
2894         }
2895
2896         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2897         /// local transaction(s).
2898         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2899                 for chan in self.list_channels() {
2900                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2901                 }
2902         }
2903
2904         fn construct_fwd_pending_htlc_info(
2905                 &self, msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
2906                 new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
2907                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
2908         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2909                 debug_assert!(next_packet_pubkey_opt.is_some());
2910                 let outgoing_packet = msgs::OnionPacket {
2911                         version: 0,
2912                         public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
2913                         hop_data: new_packet_bytes,
2914                         hmac: hop_hmac,
2915                 };
2916
2917                 let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
2918                         msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
2919                                 (short_channel_id, amt_to_forward, outgoing_cltv_value),
2920                         msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
2921                                 return Err(InboundOnionErr {
2922                                         msg: "Final Node OnionHopData provided for us as an intermediary node",
2923                                         err_code: 0x4000 | 22,
2924                                         err_data: Vec::new(),
2925                                 }),
2926                 };
2927
2928                 Ok(PendingHTLCInfo {
2929                         routing: PendingHTLCRouting::Forward {
2930                                 onion_packet: outgoing_packet,
2931                                 short_channel_id,
2932                         },
2933                         payment_hash: msg.payment_hash,
2934                         incoming_shared_secret: shared_secret,
2935                         incoming_amt_msat: Some(msg.amount_msat),
2936                         outgoing_amt_msat: amt_to_forward,
2937                         outgoing_cltv_value,
2938                         skimmed_fee_msat: None,
2939                 })
2940         }
2941
2942         fn construct_recv_pending_htlc_info(
2943                 &self, hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
2944                 amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
2945                 counterparty_skimmed_fee_msat: Option<u64>,
2946         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2947                 let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
2948                         msgs::InboundOnionPayload::Receive {
2949                                 payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
2950                         } =>
2951                                 (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
2952                         msgs::InboundOnionPayload::BlindedReceive {
2953                                 amt_msat, total_msat, outgoing_cltv_value, payment_secret, ..
2954                         } => {
2955                                 let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
2956                                 (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
2957                         }
2958                         msgs::InboundOnionPayload::Forward { .. } => {
2959                                 return Err(InboundOnionErr {
2960                                         err_code: 0x4000|22,
2961                                         err_data: Vec::new(),
2962                                         msg: "Got non final data with an HMAC of 0",
2963                                 })
2964                         },
2965                 };
2966                 // final_incorrect_cltv_expiry
2967                 if outgoing_cltv_value > cltv_expiry {
2968                         return Err(InboundOnionErr {
2969                                 msg: "Upstream node set CLTV to less than the CLTV set by the sender",
2970                                 err_code: 18,
2971                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2972                         })
2973                 }
2974                 // final_expiry_too_soon
2975                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2976                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2977                 //
2978                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2979                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2980                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2981                 let current_height: u32 = self.best_block.read().unwrap().height();
2982                 if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
2983                         let mut err_data = Vec::with_capacity(12);
2984                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2985                         err_data.extend_from_slice(&current_height.to_be_bytes());
2986                         return Err(InboundOnionErr {
2987                                 err_code: 0x4000 | 15, err_data,
2988                                 msg: "The final CLTV expiry is too soon to handle",
2989                         });
2990                 }
2991                 if (!allow_underpay && onion_amt_msat > amt_msat) ||
2992                         (allow_underpay && onion_amt_msat >
2993                          amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
2994                 {
2995                         return Err(InboundOnionErr {
2996                                 err_code: 19,
2997                                 err_data: amt_msat.to_be_bytes().to_vec(),
2998                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2999                         });
3000                 }
3001
3002                 let routing = if let Some(payment_preimage) = keysend_preimage {
3003                         // We need to check that the sender knows the keysend preimage before processing this
3004                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
3005                         // could discover the final destination of X, by probing the adjacent nodes on the route
3006                         // with a keysend payment of identical payment hash to X and observing the processing
3007                         // time discrepancies due to a hash collision with X.
3008                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
3009                         if hashed_preimage != payment_hash {
3010                                 return Err(InboundOnionErr {
3011                                         err_code: 0x4000|22,
3012                                         err_data: Vec::new(),
3013                                         msg: "Payment preimage didn't match payment hash",
3014                                 });
3015                         }
3016                         if !self.default_configuration.accept_mpp_keysend && payment_data.is_some() {
3017                                 return Err(InboundOnionErr {
3018                                         err_code: 0x4000|22,
3019                                         err_data: Vec::new(),
3020                                         msg: "We don't support MPP keysend payments",
3021                                 });
3022                         }
3023                         PendingHTLCRouting::ReceiveKeysend {
3024                                 payment_data,
3025                                 payment_preimage,
3026                                 payment_metadata,
3027                                 incoming_cltv_expiry: outgoing_cltv_value,
3028                                 custom_tlvs,
3029                         }
3030                 } else if let Some(data) = payment_data {
3031                         PendingHTLCRouting::Receive {
3032                                 payment_data: data,
3033                                 payment_metadata,
3034                                 incoming_cltv_expiry: outgoing_cltv_value,
3035                                 phantom_shared_secret,
3036                                 custom_tlvs,
3037                         }
3038                 } else {
3039                         return Err(InboundOnionErr {
3040                                 err_code: 0x4000|0x2000|3,
3041                                 err_data: Vec::new(),
3042                                 msg: "We require payment_secrets",
3043                         });
3044                 };
3045                 Ok(PendingHTLCInfo {
3046                         routing,
3047                         payment_hash,
3048                         incoming_shared_secret: shared_secret,
3049                         incoming_amt_msat: Some(amt_msat),
3050                         outgoing_amt_msat: onion_amt_msat,
3051                         outgoing_cltv_value,
3052                         skimmed_fee_msat: counterparty_skimmed_fee_msat,
3053                 })
3054         }
3055
3056         fn decode_update_add_htlc_onion(
3057                 &self, msg: &msgs::UpdateAddHTLC
3058         ) -> Result<(onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg> {
3059                 macro_rules! return_malformed_err {
3060                         ($msg: expr, $err_code: expr) => {
3061                                 {
3062                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3063                                         return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3064                                                 channel_id: msg.channel_id,
3065                                                 htlc_id: msg.htlc_id,
3066                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
3067                                                 failure_code: $err_code,
3068                                         }));
3069                                 }
3070                         }
3071                 }
3072
3073                 if let Err(_) = msg.onion_routing_packet.public_key {
3074                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
3075                 }
3076
3077                 let shared_secret = self.node_signer.ecdh(
3078                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
3079                 ).unwrap().secret_bytes();
3080
3081                 if msg.onion_routing_packet.version != 0 {
3082                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
3083                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
3084                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
3085                         //receiving node would have to brute force to figure out which version was put in the
3086                         //packet by the node that send us the message, in the case of hashing the hop_data, the
3087                         //node knows the HMAC matched, so they already know what is there...
3088                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
3089                 }
3090                 macro_rules! return_err {
3091                         ($msg: expr, $err_code: expr, $data: expr) => {
3092                                 {
3093                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3094                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3095                                                 channel_id: msg.channel_id,
3096                                                 htlc_id: msg.htlc_id,
3097                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3098                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3099                                         }));
3100                                 }
3101                         }
3102                 }
3103
3104                 let next_hop = match onion_utils::decode_next_payment_hop(
3105                         shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
3106                         msg.payment_hash, &self.node_signer
3107                 ) {
3108                         Ok(res) => res,
3109                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3110                                 return_malformed_err!(err_msg, err_code);
3111                         },
3112                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3113                                 return_err!(err_msg, err_code, &[0; 0]);
3114                         },
3115                 };
3116                 let (outgoing_scid, outgoing_amt_msat, outgoing_cltv_value, next_packet_pk_opt) = match next_hop {
3117                         onion_utils::Hop::Forward {
3118                                 next_hop_data: msgs::InboundOnionPayload::Forward {
3119                                         short_channel_id, amt_to_forward, outgoing_cltv_value
3120                                 }, ..
3121                         } => {
3122                                 let next_packet_pk = onion_utils::next_hop_pubkey(&self.secp_ctx,
3123                                         msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
3124                                 (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(next_packet_pk))
3125                         },
3126                         // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
3127                         // inbound channel's state.
3128                         onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
3129                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
3130                                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
3131                         {
3132                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
3133                         }
3134                 };
3135
3136                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3137                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3138                 if let Some((err, mut code, chan_update)) = loop {
3139                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3140                         let forwarding_chan_info_opt = match id_option {
3141                                 None => { // unknown_next_peer
3142                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3143                                         // phantom or an intercept.
3144                                         if (self.default_configuration.accept_intercept_htlcs &&
3145                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3146                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3147                                         {
3148                                                 None
3149                                         } else {
3150                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3151                                         }
3152                                 },
3153                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3154                         };
3155                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3156                                 let per_peer_state = self.per_peer_state.read().unwrap();
3157                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3158                                 if peer_state_mutex_opt.is_none() {
3159                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3160                                 }
3161                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3162                                 let peer_state = &mut *peer_state_lock;
3163                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3164                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3165                                 ).flatten() {
3166                                         None => {
3167                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3168                                                 // have no consistency guarantees.
3169                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3170                                         },
3171                                         Some(chan) => chan
3172                                 };
3173                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3174                                         // Note that the behavior here should be identical to the above block - we
3175                                         // should NOT reveal the existence or non-existence of a private channel if
3176                                         // we don't allow forwards outbound over them.
3177                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3178                                 }
3179                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3180                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3181                                         // "refuse to forward unless the SCID alias was used", so we pretend
3182                                         // we don't have the channel here.
3183                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3184                                 }
3185                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3186
3187                                 // Note that we could technically not return an error yet here and just hope
3188                                 // that the connection is reestablished or monitor updated by the time we get
3189                                 // around to doing the actual forward, but better to fail early if we can and
3190                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3191                                 // on a small/per-node/per-channel scale.
3192                                 if !chan.context.is_live() { // channel_disabled
3193                                         // If the channel_update we're going to return is disabled (i.e. the
3194                                         // peer has been disabled for some time), return `channel_disabled`,
3195                                         // otherwise return `temporary_channel_failure`.
3196                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3197                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3198                                         } else {
3199                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3200                                         }
3201                                 }
3202                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3203                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3204                                 }
3205                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3206                                         break Some((err, code, chan_update_opt));
3207                                 }
3208                                 chan_update_opt
3209                         } else {
3210                                 if (msg.cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
3211                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3212                                         // forwarding over a real channel we can't generate a channel_update
3213                                         // for it. Instead we just return a generic temporary_node_failure.
3214                                         break Some((
3215                                                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
3216                                                         0x2000 | 2, None,
3217                                         ));
3218                                 }
3219                                 None
3220                         };
3221
3222                         let cur_height = self.best_block.read().unwrap().height() + 1;
3223                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
3224                         // but we want to be robust wrt to counterparty packet sanitization (see
3225                         // HTLC_FAIL_BACK_BUFFER rationale).
3226                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
3227                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
3228                         }
3229                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
3230                                 break Some(("CLTV expiry is too far in the future", 21, None));
3231                         }
3232                         // If the HTLC expires ~now, don't bother trying to forward it to our
3233                         // counterparty. They should fail it anyway, but we don't want to bother with
3234                         // the round-trips or risk them deciding they definitely want the HTLC and
3235                         // force-closing to ensure they get it if we're offline.
3236                         // We previously had a much more aggressive check here which tried to ensure
3237                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
3238                         // but there is no need to do that, and since we're a bit conservative with our
3239                         // risk threshold it just results in failing to forward payments.
3240                         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
3241                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
3242                         }
3243
3244                         break None;
3245                 }
3246                 {
3247                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3248                         if let Some(chan_update) = chan_update {
3249                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3250                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3251                                 }
3252                                 else if code == 0x1000 | 13 {
3253                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3254                                 }
3255                                 else if code == 0x1000 | 20 {
3256                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3257                                         0u16.write(&mut res).expect("Writes cannot fail");
3258                                 }
3259                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3260                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3261                                 chan_update.write(&mut res).expect("Writes cannot fail");
3262                         } else if code & 0x1000 == 0x1000 {
3263                                 // If we're trying to return an error that requires a `channel_update` but
3264                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3265                                 // generate an update), just use the generic "temporary_node_failure"
3266                                 // instead.
3267                                 code = 0x2000 | 2;
3268                         }
3269                         return_err!(err, code, &res.0[..]);
3270                 }
3271                 Ok((next_hop, shared_secret, next_packet_pk_opt))
3272         }
3273
3274         fn construct_pending_htlc_status<'a>(
3275                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3276                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3277         ) -> PendingHTLCStatus {
3278                 macro_rules! return_err {
3279                         ($msg: expr, $err_code: expr, $data: expr) => {
3280                                 {
3281                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3282                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3283                                                 channel_id: msg.channel_id,
3284                                                 htlc_id: msg.htlc_id,
3285                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3286                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3287                                         }));
3288                                 }
3289                         }
3290                 }
3291                 match decoded_hop {
3292                         onion_utils::Hop::Receive(next_hop_data) => {
3293                                 // OUR PAYMENT!
3294                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3295                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat)
3296                                 {
3297                                         Ok(info) => {
3298                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3299                                                 // message, however that would leak that we are the recipient of this payment, so
3300                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3301                                                 // delay) once they've send us a commitment_signed!
3302                                                 PendingHTLCStatus::Forward(info)
3303                                         },
3304                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3305                                 }
3306                         },
3307                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3308                                 match self.construct_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3309                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3310                                         Ok(info) => PendingHTLCStatus::Forward(info),
3311                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3312                                 }
3313                         }
3314                 }
3315         }
3316
3317         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3318         /// public, and thus should be called whenever the result is going to be passed out in a
3319         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3320         ///
3321         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3322         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3323         /// storage and the `peer_state` lock has been dropped.
3324         ///
3325         /// [`channel_update`]: msgs::ChannelUpdate
3326         /// [`internal_closing_signed`]: Self::internal_closing_signed
3327         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3328                 if !chan.context.should_announce() {
3329                         return Err(LightningError {
3330                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3331                                 action: msgs::ErrorAction::IgnoreError
3332                         });
3333                 }
3334                 if chan.context.get_short_channel_id().is_none() {
3335                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3336                 }
3337                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3338                 self.get_channel_update_for_unicast(chan)
3339         }
3340
3341         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3342         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3343         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3344         /// provided evidence that they know about the existence of the channel.
3345         ///
3346         /// Note that through [`internal_closing_signed`], this function is called without the
3347         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3348         /// removed from the storage and the `peer_state` lock has been dropped.
3349         ///
3350         /// [`channel_update`]: msgs::ChannelUpdate
3351         /// [`internal_closing_signed`]: Self::internal_closing_signed
3352         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3353                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", &chan.context.channel_id());
3354                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3355                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3356                         Some(id) => id,
3357                 };
3358
3359                 self.get_channel_update_for_onion(short_channel_id, chan)
3360         }
3361
3362         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3363                 log_trace!(self.logger, "Generating channel update for channel {}", &chan.context.channel_id());
3364                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3365
3366                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3367                         ChannelUpdateStatus::Enabled => true,
3368                         ChannelUpdateStatus::DisabledStaged(_) => true,
3369                         ChannelUpdateStatus::Disabled => false,
3370                         ChannelUpdateStatus::EnabledStaged(_) => false,
3371                 };
3372
3373                 let unsigned = msgs::UnsignedChannelUpdate {
3374                         chain_hash: self.chain_hash,
3375                         short_channel_id,
3376                         timestamp: chan.context.get_update_time_counter(),
3377                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3378                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3379                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3380                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3381                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3382                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3383                         excess_data: Vec::new(),
3384                 };
3385                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3386                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3387                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3388                 // channel.
3389                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3390
3391                 Ok(msgs::ChannelUpdate {
3392                         signature: sig,
3393                         contents: unsigned
3394                 })
3395         }
3396
3397         #[cfg(test)]
3398         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> {
3399                 let _lck = self.total_consistency_lock.read().unwrap();
3400                 self.send_payment_along_path(SendAlongPathArgs {
3401                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3402                         session_priv_bytes
3403                 })
3404         }
3405
3406         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3407                 let SendAlongPathArgs {
3408                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3409                         session_priv_bytes
3410                 } = args;
3411                 // The top-level caller should hold the total_consistency_lock read lock.
3412                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3413
3414                 log_trace!(self.logger,
3415                         "Attempting to send payment with payment hash {} along path with next hop {}",
3416                         payment_hash, path.hops.first().unwrap().short_channel_id);
3417                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3418                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3419
3420                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3421                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3422                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3423
3424                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3425                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3426
3427                 let err: Result<(), _> = loop {
3428                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3429                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3430                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3431                         };
3432
3433                         let per_peer_state = self.per_peer_state.read().unwrap();
3434                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3435                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3436                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3437                         let peer_state = &mut *peer_state_lock;
3438                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3439                                 match chan_phase_entry.get_mut() {
3440                                         ChannelPhase::Funded(chan) => {
3441                                                 if !chan.context.is_live() {
3442                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3443                                                 }
3444                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3445                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3446                                                         htlc_cltv, HTLCSource::OutboundRoute {
3447                                                                 path: path.clone(),
3448                                                                 session_priv: session_priv.clone(),
3449                                                                 first_hop_htlc_msat: htlc_msat,
3450                                                                 payment_id,
3451                                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3452                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3453                                                         Some(monitor_update) => {
3454                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3455                                                                         false => {
3456                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3457                                                                                 // docs) that we will resend the commitment update once monitor
3458                                                                                 // updating completes. Therefore, we must return an error
3459                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3460                                                                                 // which we do in the send_payment check for
3461                                                                                 // MonitorUpdateInProgress, below.
3462                                                                                 return Err(APIError::MonitorUpdateInProgress);
3463                                                                         },
3464                                                                         true => {},
3465                                                                 }
3466                                                         },
3467                                                         None => {},
3468                                                 }
3469                                         },
3470                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3471                                 };
3472                         } else {
3473                                 // The channel was likely removed after we fetched the id from the
3474                                 // `short_to_chan_info` map, but before we successfully locked the
3475                                 // `channel_by_id` map.
3476                                 // This can occur as no consistency guarantees exists between the two maps.
3477                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3478                         }
3479                         return Ok(());
3480                 };
3481
3482                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3483                         Ok(_) => unreachable!(),
3484                         Err(e) => {
3485                                 Err(APIError::ChannelUnavailable { err: e.err })
3486                         },
3487                 }
3488         }
3489
3490         /// Sends a payment along a given route.
3491         ///
3492         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3493         /// fields for more info.
3494         ///
3495         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3496         /// [`PeerManager::process_events`]).
3497         ///
3498         /// # Avoiding Duplicate Payments
3499         ///
3500         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3501         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3502         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3503         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3504         /// second payment with the same [`PaymentId`].
3505         ///
3506         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3507         /// tracking of payments, including state to indicate once a payment has completed. Because you
3508         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3509         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3510         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3511         ///
3512         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3513         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3514         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3515         /// [`ChannelManager::list_recent_payments`] for more information.
3516         ///
3517         /// # Possible Error States on [`PaymentSendFailure`]
3518         ///
3519         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3520         /// each entry matching the corresponding-index entry in the route paths, see
3521         /// [`PaymentSendFailure`] for more info.
3522         ///
3523         /// In general, a path may raise:
3524         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3525         ///    node public key) is specified.
3526         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3527         ///    closed, doesn't exist, or the peer is currently disconnected.
3528         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3529         ///    relevant updates.
3530         ///
3531         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3532         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3533         /// different route unless you intend to pay twice!
3534         ///
3535         /// [`RouteHop`]: crate::routing::router::RouteHop
3536         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3537         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3538         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3539         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3540         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3541         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3542                 let best_block_height = self.best_block.read().unwrap().height();
3543                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3544                 self.pending_outbound_payments
3545                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3546                                 &self.entropy_source, &self.node_signer, best_block_height,
3547                                 |args| self.send_payment_along_path(args))
3548         }
3549
3550         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3551         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3552         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3553                 let best_block_height = self.best_block.read().unwrap().height();
3554                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3555                 self.pending_outbound_payments
3556                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3557                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3558                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3559                                 &self.pending_events, |args| self.send_payment_along_path(args))
3560         }
3561
3562         #[cfg(test)]
3563         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> {
3564                 let best_block_height = self.best_block.read().unwrap().height();
3565                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3566                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3567                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3568                         best_block_height, |args| self.send_payment_along_path(args))
3569         }
3570
3571         #[cfg(test)]
3572         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> {
3573                 let best_block_height = self.best_block.read().unwrap().height();
3574                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3575         }
3576
3577         #[cfg(test)]
3578         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3579                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3580         }
3581
3582
3583         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3584         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3585         /// retries are exhausted.
3586         ///
3587         /// # Event Generation
3588         ///
3589         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3590         /// as there are no remaining pending HTLCs for this payment.
3591         ///
3592         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3593         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3594         /// determine the ultimate status of a payment.
3595         ///
3596         /// # Restart Behavior
3597         ///
3598         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3599         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated.
3600         pub fn abandon_payment(&self, payment_id: PaymentId) {
3601                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3602                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3603         }
3604
3605         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3606         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3607         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3608         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3609         /// never reach the recipient.
3610         ///
3611         /// See [`send_payment`] documentation for more details on the return value of this function
3612         /// and idempotency guarantees provided by the [`PaymentId`] key.
3613         ///
3614         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3615         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3616         ///
3617         /// [`send_payment`]: Self::send_payment
3618         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3619                 let best_block_height = self.best_block.read().unwrap().height();
3620                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3621                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3622                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3623                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3624         }
3625
3626         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3627         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3628         ///
3629         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3630         /// payments.
3631         ///
3632         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3633         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> {
3634                 let best_block_height = self.best_block.read().unwrap().height();
3635                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3636                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3637                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3638                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3639                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3640         }
3641
3642         /// Send a payment that is probing the given route for liquidity. We calculate the
3643         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3644         /// us to easily discern them from real payments.
3645         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3646                 let best_block_height = self.best_block.read().unwrap().height();
3647                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3648                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3649                         &self.entropy_source, &self.node_signer, best_block_height,
3650                         |args| self.send_payment_along_path(args))
3651         }
3652
3653         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3654         /// payment probe.
3655         #[cfg(test)]
3656         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3657                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3658         }
3659
3660         /// Sends payment probes over all paths of a route that would be used to pay the given
3661         /// amount to the given `node_id`.
3662         ///
3663         /// See [`ChannelManager::send_preflight_probes`] for more information.
3664         pub fn send_spontaneous_preflight_probes(
3665                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3666                 liquidity_limit_multiplier: Option<u64>,
3667         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3668                 let payment_params =
3669                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3670
3671                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3672
3673                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3674         }
3675
3676         /// Sends payment probes over all paths of a route that would be used to pay a route found
3677         /// according to the given [`RouteParameters`].
3678         ///
3679         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3680         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3681         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3682         /// confirmation in a wallet UI.
3683         ///
3684         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3685         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3686         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3687         /// payment. To mitigate this issue, channels with available liquidity less than the required
3688         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3689         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3690         pub fn send_preflight_probes(
3691                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3692         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3693                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3694
3695                 let payer = self.get_our_node_id();
3696                 let usable_channels = self.list_usable_channels();
3697                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3698                 let inflight_htlcs = self.compute_inflight_htlcs();
3699
3700                 let route = self
3701                         .router
3702                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3703                         .map_err(|e| {
3704                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3705                                 ProbeSendFailure::RouteNotFound
3706                         })?;
3707
3708                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3709
3710                 let mut res = Vec::new();
3711
3712                 for mut path in route.paths {
3713                         // If the last hop is probably an unannounced channel we refrain from probing all the
3714                         // way through to the end and instead probe up to the second-to-last channel.
3715                         while let Some(last_path_hop) = path.hops.last() {
3716                                 if last_path_hop.maybe_announced_channel {
3717                                         // We found a potentially announced last hop.
3718                                         break;
3719                                 } else {
3720                                         // Drop the last hop, as it's likely unannounced.
3721                                         log_debug!(
3722                                                 self.logger,
3723                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3724                                                 last_path_hop.short_channel_id
3725                                         );
3726                                         let final_value_msat = path.final_value_msat();
3727                                         path.hops.pop();
3728                                         if let Some(new_last) = path.hops.last_mut() {
3729                                                 new_last.fee_msat += final_value_msat;
3730                                         }
3731                                 }
3732                         }
3733
3734                         if path.hops.len() < 2 {
3735                                 log_debug!(
3736                                         self.logger,
3737                                         "Skipped sending payment probe over path with less than two hops."
3738                                 );
3739                                 continue;
3740                         }
3741
3742                         if let Some(first_path_hop) = path.hops.first() {
3743                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3744                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3745                                 }) {
3746                                         let path_value = path.final_value_msat() + path.fee_msat();
3747                                         let used_liquidity =
3748                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3749
3750                                         if first_hop.next_outbound_htlc_limit_msat
3751                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3752                                         {
3753                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3754                                                 continue;
3755                                         } else {
3756                                                 *used_liquidity += path_value;
3757                                         }
3758                                 }
3759                         }
3760
3761                         res.push(self.send_probe(path).map_err(|e| {
3762                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3763                                 ProbeSendFailure::SendingFailed(e)
3764                         })?);
3765                 }
3766
3767                 Ok(res)
3768         }
3769
3770         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3771         /// which checks the correctness of the funding transaction given the associated channel.
3772         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3773                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3774                 mut find_funding_output: FundingOutput,
3775         ) -> Result<(), APIError> {
3776                 let per_peer_state = self.per_peer_state.read().unwrap();
3777                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3778                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3779
3780                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3781                 let peer_state = &mut *peer_state_lock;
3782                 let (chan, msg) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3783                         Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
3784                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3785
3786                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &self.logger)
3787                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3788                                                 let channel_id = chan.context.channel_id();
3789                                                 let user_id = chan.context.get_user_id();
3790                                                 let shutdown_res = chan.context.force_shutdown(false);
3791                                                 let channel_capacity = chan.context.get_value_satoshis();
3792                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3793                                         } else { unreachable!(); });
3794                                 match funding_res {
3795                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3796                                         Err((chan, err)) => {
3797                                                 mem::drop(peer_state_lock);
3798                                                 mem::drop(per_peer_state);
3799
3800                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3801                                                 return Err(APIError::ChannelUnavailable {
3802                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3803                                                 });
3804                                         },
3805                                 }
3806                         },
3807                         Some(phase) => {
3808                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3809                                 return Err(APIError::APIMisuseError {
3810                                         err: format!(
3811                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3812                                                 temporary_channel_id, counterparty_node_id),
3813                                 })
3814                         },
3815                         None => return Err(APIError::ChannelUnavailable {err: format!(
3816                                 "Channel with id {} not found for the passed counterparty node_id {}",
3817                                 temporary_channel_id, counterparty_node_id),
3818                                 }),
3819                 };
3820
3821                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3822                         node_id: chan.context.get_counterparty_node_id(),
3823                         msg,
3824                 });
3825                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3826                         hash_map::Entry::Occupied(_) => {
3827                                 panic!("Generated duplicate funding txid?");
3828                         },
3829                         hash_map::Entry::Vacant(e) => {
3830                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3831                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3832                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3833                                 }
3834                                 e.insert(ChannelPhase::Funded(chan));
3835                         }
3836                 }
3837                 Ok(())
3838         }
3839
3840         #[cfg(test)]
3841         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3842                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3843                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3844                 })
3845         }
3846
3847         /// Call this upon creation of a funding transaction for the given channel.
3848         ///
3849         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3850         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3851         ///
3852         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3853         /// across the p2p network.
3854         ///
3855         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3856         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3857         ///
3858         /// May panic if the output found in the funding transaction is duplicative with some other
3859         /// channel (note that this should be trivially prevented by using unique funding transaction
3860         /// keys per-channel).
3861         ///
3862         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3863         /// counterparty's signature the funding transaction will automatically be broadcast via the
3864         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3865         ///
3866         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3867         /// not currently support replacing a funding transaction on an existing channel. Instead,
3868         /// create a new channel with a conflicting funding transaction.
3869         ///
3870         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3871         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3872         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3873         /// for more details.
3874         ///
3875         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3876         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3877         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3878                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3879         }
3880
3881         /// Call this upon creation of a batch funding transaction for the given channels.
3882         ///
3883         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3884         /// each individual channel and transaction output.
3885         ///
3886         /// Do NOT broadcast the funding transaction yourself. This batch funding transcaction
3887         /// will only be broadcast when we have safely received and persisted the counterparty's
3888         /// signature for each channel.
3889         ///
3890         /// If there is an error, all channels in the batch are to be considered closed.
3891         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3892                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3893                 let mut result = Ok(());
3894
3895                 if !funding_transaction.is_coin_base() {
3896                         for inp in funding_transaction.input.iter() {
3897                                 if inp.witness.is_empty() {
3898                                         result = result.and(Err(APIError::APIMisuseError {
3899                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3900                                         }));
3901                                 }
3902                         }
3903                 }
3904                 if funding_transaction.output.len() > u16::max_value() as usize {
3905                         result = result.and(Err(APIError::APIMisuseError {
3906                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3907                         }));
3908                 }
3909                 {
3910                         let height = self.best_block.read().unwrap().height();
3911                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3912                         // lower than the next block height. However, the modules constituting our Lightning
3913                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3914                         // module is ahead of LDK, only allow one more block of headroom.
3915                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) && LockTime::from(funding_transaction.lock_time).is_block_height() && funding_transaction.lock_time.0 > height + 1 {
3916                                 result = result.and(Err(APIError::APIMisuseError {
3917                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3918                                 }));
3919                         }
3920                 }
3921
3922                 let txid = funding_transaction.txid();
3923                 let is_batch_funding = temporary_channels.len() > 1;
3924                 let mut funding_batch_states = if is_batch_funding {
3925                         Some(self.funding_batch_states.lock().unwrap())
3926                 } else {
3927                         None
3928                 };
3929                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3930                         match states.entry(txid) {
3931                                 btree_map::Entry::Occupied(_) => {
3932                                         result = result.clone().and(Err(APIError::APIMisuseError {
3933                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3934                                         }));
3935                                         None
3936                                 },
3937                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3938                         }
3939                 });
3940                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels.iter() {
3941                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3942                                 temporary_channel_id,
3943                                 counterparty_node_id,
3944                                 funding_transaction.clone(),
3945                                 is_batch_funding,
3946                                 |chan, tx| {
3947                                         let mut output_index = None;
3948                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3949                                         for (idx, outp) in tx.output.iter().enumerate() {
3950                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3951                                                         if output_index.is_some() {
3952                                                                 return Err(APIError::APIMisuseError {
3953                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3954                                                                 });
3955                                                         }
3956                                                         output_index = Some(idx as u16);
3957                                                 }
3958                                         }
3959                                         if output_index.is_none() {
3960                                                 return Err(APIError::APIMisuseError {
3961                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3962                                                 });
3963                                         }
3964                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3965                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3966                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3967                                         }
3968                                         Ok(outpoint)
3969                                 })
3970                         );
3971                 }
3972                 if let Err(ref e) = result {
3973                         // Remaining channels need to be removed on any error.
3974                         let e = format!("Error in transaction funding: {:?}", e);
3975                         let mut channels_to_remove = Vec::new();
3976                         channels_to_remove.extend(funding_batch_states.as_mut()
3977                                 .and_then(|states| states.remove(&txid))
3978                                 .into_iter().flatten()
3979                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3980                         );
3981                         channels_to_remove.extend(temporary_channels.iter()
3982                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3983                         );
3984                         let mut shutdown_results = Vec::new();
3985                         {
3986                                 let per_peer_state = self.per_peer_state.read().unwrap();
3987                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3988                                         per_peer_state.get(&counterparty_node_id)
3989                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3990                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3991                                                 .map(|mut chan| {
3992                                                         update_maps_on_chan_removal!(self, &chan.context());
3993                                                         self.issue_channel_close_events(&chan.context(), ClosureReason::ProcessingError { err: e.clone() });
3994                                                         shutdown_results.push(chan.context_mut().force_shutdown(false));
3995                                                 });
3996                                 }
3997                         }
3998                         for shutdown_result in shutdown_results.drain(..) {
3999                                 self.finish_close_channel(shutdown_result);
4000                         }
4001                 }
4002                 result
4003         }
4004
4005         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
4006         ///
4007         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4008         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4009         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4010         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4011         ///
4012         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4013         /// `counterparty_node_id` is provided.
4014         ///
4015         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4016         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4017         ///
4018         /// If an error is returned, none of the updates should be considered applied.
4019         ///
4020         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4021         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4022         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4023         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4024         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4025         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4026         /// [`APIMisuseError`]: APIError::APIMisuseError
4027         pub fn update_partial_channel_config(
4028                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
4029         ) -> Result<(), APIError> {
4030                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
4031                         return Err(APIError::APIMisuseError {
4032                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
4033                         });
4034                 }
4035
4036                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4037                 let per_peer_state = self.per_peer_state.read().unwrap();
4038                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4039                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4040                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4041                 let peer_state = &mut *peer_state_lock;
4042                 for channel_id in channel_ids {
4043                         if !peer_state.has_channel(channel_id) {
4044                                 return Err(APIError::ChannelUnavailable {
4045                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4046                                 });
4047                         };
4048                 }
4049                 for channel_id in channel_ids {
4050                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4051                                 let mut config = channel_phase.context().config();
4052                                 config.apply(config_update);
4053                                 if !channel_phase.context_mut().update_config(&config) {
4054                                         continue;
4055                                 }
4056                                 if let ChannelPhase::Funded(channel) = channel_phase {
4057                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4058                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4059                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4060                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4061                                                         node_id: channel.context.get_counterparty_node_id(),
4062                                                         msg,
4063                                                 });
4064                                         }
4065                                 }
4066                                 continue;
4067                         } else {
4068                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4069                                 debug_assert!(false);
4070                                 return Err(APIError::ChannelUnavailable {
4071                                         err: format!(
4072                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4073                                                 channel_id, counterparty_node_id),
4074                                 });
4075                         };
4076                 }
4077                 Ok(())
4078         }
4079
4080         /// Atomically updates the [`ChannelConfig`] for the given channels.
4081         ///
4082         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4083         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4084         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4085         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4086         ///
4087         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4088         /// `counterparty_node_id` is provided.
4089         ///
4090         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4091         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4092         ///
4093         /// If an error is returned, none of the updates should be considered applied.
4094         ///
4095         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4096         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4097         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4098         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4099         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4100         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4101         /// [`APIMisuseError`]: APIError::APIMisuseError
4102         pub fn update_channel_config(
4103                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4104         ) -> Result<(), APIError> {
4105                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4106         }
4107
4108         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4109         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4110         ///
4111         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4112         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4113         ///
4114         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4115         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4116         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4117         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4118         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4119         ///
4120         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4121         /// you from forwarding more than you received. See
4122         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4123         /// than expected.
4124         ///
4125         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4126         /// backwards.
4127         ///
4128         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4129         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4130         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4131         // TODO: when we move to deciding the best outbound channel at forward time, only take
4132         // `next_node_id` and not `next_hop_channel_id`
4133         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> {
4134                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4135
4136                 let next_hop_scid = {
4137                         let peer_state_lock = self.per_peer_state.read().unwrap();
4138                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4139                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4140                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4141                         let peer_state = &mut *peer_state_lock;
4142                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4143                                 Some(ChannelPhase::Funded(chan)) => {
4144                                         if !chan.context.is_usable() {
4145                                                 return Err(APIError::ChannelUnavailable {
4146                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4147                                                 })
4148                                         }
4149                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4150                                 },
4151                                 Some(_) => return Err(APIError::ChannelUnavailable {
4152                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4153                                                 next_hop_channel_id, next_node_id)
4154                                 }),
4155                                 None => return Err(APIError::ChannelUnavailable {
4156                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}",
4157                                                 next_hop_channel_id, next_node_id)
4158                                 })
4159                         }
4160                 };
4161
4162                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4163                         .ok_or_else(|| APIError::APIMisuseError {
4164                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4165                         })?;
4166
4167                 let routing = match payment.forward_info.routing {
4168                         PendingHTLCRouting::Forward { onion_packet, .. } => {
4169                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
4170                         },
4171                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4172                 };
4173                 let skimmed_fee_msat =
4174                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4175                 let pending_htlc_info = PendingHTLCInfo {
4176                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4177                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4178                 };
4179
4180                 let mut per_source_pending_forward = [(
4181                         payment.prev_short_channel_id,
4182                         payment.prev_funding_outpoint,
4183                         payment.prev_user_channel_id,
4184                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4185                 )];
4186                 self.forward_htlcs(&mut per_source_pending_forward);
4187                 Ok(())
4188         }
4189
4190         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4191         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4192         ///
4193         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4194         /// backwards.
4195         ///
4196         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4197         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4198                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4199
4200                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4201                         .ok_or_else(|| APIError::APIMisuseError {
4202                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4203                         })?;
4204
4205                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4206                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4207                                 short_channel_id: payment.prev_short_channel_id,
4208                                 user_channel_id: Some(payment.prev_user_channel_id),
4209                                 outpoint: payment.prev_funding_outpoint,
4210                                 htlc_id: payment.prev_htlc_id,
4211                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4212                                 phantom_shared_secret: None,
4213                         });
4214
4215                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4216                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4217                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4218                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4219
4220                 Ok(())
4221         }
4222
4223         /// Processes HTLCs which are pending waiting on random forward delay.
4224         ///
4225         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4226         /// Will likely generate further events.
4227         pub fn process_pending_htlc_forwards(&self) {
4228                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4229
4230                 let mut new_events = VecDeque::new();
4231                 let mut failed_forwards = Vec::new();
4232                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4233                 {
4234                         let mut forward_htlcs = HashMap::new();
4235                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4236
4237                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4238                                 if short_chan_id != 0 {
4239                                         macro_rules! forwarding_channel_not_found {
4240                                                 () => {
4241                                                         for forward_info in pending_forwards.drain(..) {
4242                                                                 match forward_info {
4243                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4244                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4245                                                                                 forward_info: PendingHTLCInfo {
4246                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4247                                                                                         outgoing_cltv_value, ..
4248                                                                                 }
4249                                                                         }) => {
4250                                                                                 macro_rules! failure_handler {
4251                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4252                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4253
4254                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4255                                                                                                         short_channel_id: prev_short_channel_id,
4256                                                                                                         user_channel_id: Some(prev_user_channel_id),
4257                                                                                                         outpoint: prev_funding_outpoint,
4258                                                                                                         htlc_id: prev_htlc_id,
4259                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4260                                                                                                         phantom_shared_secret: $phantom_ss,
4261                                                                                                 });
4262
4263                                                                                                 let reason = if $next_hop_unknown {
4264                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4265                                                                                                 } else {
4266                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4267                                                                                                 };
4268
4269                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4270                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4271                                                                                                         reason
4272                                                                                                 ));
4273                                                                                                 continue;
4274                                                                                         }
4275                                                                                 }
4276                                                                                 macro_rules! fail_forward {
4277                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4278                                                                                                 {
4279                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4280                                                                                                 }
4281                                                                                         }
4282                                                                                 }
4283                                                                                 macro_rules! failed_payment {
4284                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4285                                                                                                 {
4286                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4287                                                                                                 }
4288                                                                                         }
4289                                                                                 }
4290                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
4291                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4292                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4293                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4294                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4295                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4296                                                                                                         payment_hash, &self.node_signer
4297                                                                                                 ) {
4298                                                                                                         Ok(res) => res,
4299                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4300                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
4301                                                                                                                 // In this scenario, the phantom would have sent us an
4302                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4303                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4304                                                                                                                 // of the onion.
4305                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4306                                                                                                         },
4307                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4308                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4309                                                                                                         },
4310                                                                                                 };
4311                                                                                                 match next_hop {
4312                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4313                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data,
4314                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4315                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None)
4316                                                                                                                 {
4317                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4318                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4319                                                                                                                 }
4320                                                                                                         },
4321                                                                                                         _ => panic!(),
4322                                                                                                 }
4323                                                                                         } else {
4324                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4325                                                                                         }
4326                                                                                 } else {
4327                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4328                                                                                 }
4329                                                                         },
4330                                                                         HTLCForwardInfo::FailHTLC { .. } => {
4331                                                                                 // Channel went away before we could fail it. This implies
4332                                                                                 // the channel is now on chain and our counterparty is
4333                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4334                                                                                 // problem, not ours.
4335                                                                         }
4336                                                                 }
4337                                                         }
4338                                                 }
4339                                         }
4340                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4341                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4342                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4343                                                 None => {
4344                                                         forwarding_channel_not_found!();
4345                                                         continue;
4346                                                 }
4347                                         };
4348                                         let per_peer_state = self.per_peer_state.read().unwrap();
4349                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4350                                         if peer_state_mutex_opt.is_none() {
4351                                                 forwarding_channel_not_found!();
4352                                                 continue;
4353                                         }
4354                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4355                                         let peer_state = &mut *peer_state_lock;
4356                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4357                                                 for forward_info in pending_forwards.drain(..) {
4358                                                         match forward_info {
4359                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4360                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4361                                                                         forward_info: PendingHTLCInfo {
4362                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4363                                                                                 routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
4364                                                                         },
4365                                                                 }) => {
4366                                                                         log_trace!(self.logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", prev_short_channel_id, &payment_hash, short_chan_id);
4367                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4368                                                                                 short_channel_id: prev_short_channel_id,
4369                                                                                 user_channel_id: Some(prev_user_channel_id),
4370                                                                                 outpoint: prev_funding_outpoint,
4371                                                                                 htlc_id: prev_htlc_id,
4372                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4373                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4374                                                                                 phantom_shared_secret: None,
4375                                                                         });
4376                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4377                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4378                                                                                 onion_packet, skimmed_fee_msat, &self.fee_estimator,
4379                                                                                 &self.logger)
4380                                                                         {
4381                                                                                 if let ChannelError::Ignore(msg) = e {
4382                                                                                         log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4383                                                                                 } else {
4384                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4385                                                                                 }
4386                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4387                                                                                 failed_forwards.push((htlc_source, payment_hash,
4388                                                                                         HTLCFailReason::reason(failure_code, data),
4389                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4390                                                                                 ));
4391                                                                                 continue;
4392                                                                         }
4393                                                                 },
4394                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4395                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4396                                                                 },
4397                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4398                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4399                                                                         if let Err(e) = chan.queue_fail_htlc(
4400                                                                                 htlc_id, err_packet, &self.logger
4401                                                                         ) {
4402                                                                                 if let ChannelError::Ignore(msg) = e {
4403                                                                                         log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4404                                                                                 } else {
4405                                                                                         panic!("Stated return value requirements in queue_fail_htlc() were not met");
4406                                                                                 }
4407                                                                                 // fail-backs are best-effort, we probably already have one
4408                                                                                 // pending, and if not that's OK, if not, the channel is on
4409                                                                                 // the chain and sending the HTLC-Timeout is their problem.
4410                                                                                 continue;
4411                                                                         }
4412                                                                 },
4413                                                         }
4414                                                 }
4415                                         } else {
4416                                                 forwarding_channel_not_found!();
4417                                                 continue;
4418                                         }
4419                                 } else {
4420                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4421                                                 match forward_info {
4422                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4423                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4424                                                                 forward_info: PendingHTLCInfo {
4425                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4426                                                                         skimmed_fee_msat, ..
4427                                                                 }
4428                                                         }) => {
4429                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4430                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4431                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4432                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4433                                                                                                 payment_metadata, custom_tlvs };
4434                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4435                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4436                                                                         },
4437                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4438                                                                                 let onion_fields = RecipientOnionFields {
4439                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4440                                                                                         payment_metadata,
4441                                                                                         custom_tlvs,
4442                                                                                 };
4443                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4444                                                                                         payment_data, None, onion_fields)
4445                                                                         },
4446                                                                         _ => {
4447                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4448                                                                         }
4449                                                                 };
4450                                                                 let claimable_htlc = ClaimableHTLC {
4451                                                                         prev_hop: HTLCPreviousHopData {
4452                                                                                 short_channel_id: prev_short_channel_id,
4453                                                                                 user_channel_id: Some(prev_user_channel_id),
4454                                                                                 outpoint: prev_funding_outpoint,
4455                                                                                 htlc_id: prev_htlc_id,
4456                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4457                                                                                 phantom_shared_secret,
4458                                                                         },
4459                                                                         // We differentiate the received value from the sender intended value
4460                                                                         // if possible so that we don't prematurely mark MPP payments complete
4461                                                                         // if routing nodes overpay
4462                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4463                                                                         sender_intended_value: outgoing_amt_msat,
4464                                                                         timer_ticks: 0,
4465                                                                         total_value_received: None,
4466                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4467                                                                         cltv_expiry,
4468                                                                         onion_payload,
4469                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4470                                                                 };
4471
4472                                                                 let mut committed_to_claimable = false;
4473
4474                                                                 macro_rules! fail_htlc {
4475                                                                         ($htlc: expr, $payment_hash: expr) => {
4476                                                                                 debug_assert!(!committed_to_claimable);
4477                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4478                                                                                 htlc_msat_height_data.extend_from_slice(
4479                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4480                                                                                 );
4481                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4482                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4483                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4484                                                                                                 outpoint: prev_funding_outpoint,
4485                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4486                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4487                                                                                                 phantom_shared_secret,
4488                                                                                         }), payment_hash,
4489                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4490                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4491                                                                                 ));
4492                                                                                 continue 'next_forwardable_htlc;
4493                                                                         }
4494                                                                 }
4495                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4496                                                                 let mut receiver_node_id = self.our_network_pubkey;
4497                                                                 if phantom_shared_secret.is_some() {
4498                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4499                                                                                 .expect("Failed to get node_id for phantom node recipient");
4500                                                                 }
4501
4502                                                                 macro_rules! check_total_value {
4503                                                                         ($purpose: expr) => {{
4504                                                                                 let mut payment_claimable_generated = false;
4505                                                                                 let is_keysend = match $purpose {
4506                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4507                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4508                                                                                 };
4509                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4510                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4511                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4512                                                                                 }
4513                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4514                                                                                         .entry(payment_hash)
4515                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4516                                                                                         .or_insert_with(|| {
4517                                                                                                 committed_to_claimable = true;
4518                                                                                                 ClaimablePayment {
4519                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4520                                                                                                 }
4521                                                                                         });
4522                                                                                 if $purpose != claimable_payment.purpose {
4523                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4524                                                                                         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));
4525                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4526                                                                                 }
4527                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4528                                                                                         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);
4529                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4530                                                                                 }
4531                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4532                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4533                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4534                                                                                         }
4535                                                                                 } else {
4536                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4537                                                                                 }
4538                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4539                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4540                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4541                                                                                 for htlc in htlcs.iter() {
4542                                                                                         total_value += htlc.sender_intended_value;
4543                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4544                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4545                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4546                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4547                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4548                                                                                         }
4549                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4550                                                                                 }
4551                                                                                 // The condition determining whether an MPP is complete must
4552                                                                                 // match exactly the condition used in `timer_tick_occurred`
4553                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4554                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4555                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4556                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4557                                                                                                 &payment_hash);
4558                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4559                                                                                 } else if total_value >= claimable_htlc.total_msat {
4560                                                                                         #[allow(unused_assignments)] {
4561                                                                                                 committed_to_claimable = true;
4562                                                                                         }
4563                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4564                                                                                         htlcs.push(claimable_htlc);
4565                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4566                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4567                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4568                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4569                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4570                                                                                                 counterparty_skimmed_fee_msat);
4571                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4572                                                                                                 receiver_node_id: Some(receiver_node_id),
4573                                                                                                 payment_hash,
4574                                                                                                 purpose: $purpose,
4575                                                                                                 amount_msat,
4576                                                                                                 counterparty_skimmed_fee_msat,
4577                                                                                                 via_channel_id: Some(prev_channel_id),
4578                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4579                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4580                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4581                                                                                         }, None));
4582                                                                                         payment_claimable_generated = true;
4583                                                                                 } else {
4584                                                                                         // Nothing to do - we haven't reached the total
4585                                                                                         // payment value yet, wait until we receive more
4586                                                                                         // MPP parts.
4587                                                                                         htlcs.push(claimable_htlc);
4588                                                                                         #[allow(unused_assignments)] {
4589                                                                                                 committed_to_claimable = true;
4590                                                                                         }
4591                                                                                 }
4592                                                                                 payment_claimable_generated
4593                                                                         }}
4594                                                                 }
4595
4596                                                                 // Check that the payment hash and secret are known. Note that we
4597                                                                 // MUST take care to handle the "unknown payment hash" and
4598                                                                 // "incorrect payment secret" cases here identically or we'd expose
4599                                                                 // that we are the ultimate recipient of the given payment hash.
4600                                                                 // Further, we must not expose whether we have any other HTLCs
4601                                                                 // associated with the same payment_hash pending or not.
4602                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4603                                                                 match payment_secrets.entry(payment_hash) {
4604                                                                         hash_map::Entry::Vacant(_) => {
4605                                                                                 match claimable_htlc.onion_payload {
4606                                                                                         OnionPayload::Invoice { .. } => {
4607                                                                                                 let payment_data = payment_data.unwrap();
4608                                                                                                 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) {
4609                                                                                                         Ok(result) => result,
4610                                                                                                         Err(()) => {
4611                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4612                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4613                                                                                                         }
4614                                                                                                 };
4615                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4616                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4617                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4618                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4619                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4620                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4621                                                                                                         }
4622                                                                                                 }
4623                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4624                                                                                                         payment_preimage: payment_preimage.clone(),
4625                                                                                                         payment_secret: payment_data.payment_secret,
4626                                                                                                 };
4627                                                                                                 check_total_value!(purpose);
4628                                                                                         },
4629                                                                                         OnionPayload::Spontaneous(preimage) => {
4630                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4631                                                                                                 check_total_value!(purpose);
4632                                                                                         }
4633                                                                                 }
4634                                                                         },
4635                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4636                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4637                                                                                         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);
4638                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4639                                                                                 }
4640                                                                                 let payment_data = payment_data.unwrap();
4641                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4642                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4643                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4644                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4645                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4646                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4647                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4648                                                                                 } else {
4649                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4650                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4651                                                                                                 payment_secret: payment_data.payment_secret,
4652                                                                                         };
4653                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4654                                                                                         if payment_claimable_generated {
4655                                                                                                 inbound_payment.remove_entry();
4656                                                                                         }
4657                                                                                 }
4658                                                                         },
4659                                                                 };
4660                                                         },
4661                                                         HTLCForwardInfo::FailHTLC { .. } => {
4662                                                                 panic!("Got pending fail of our own HTLC");
4663                                                         }
4664                                                 }
4665                                         }
4666                                 }
4667                         }
4668                 }
4669
4670                 let best_block_height = self.best_block.read().unwrap().height();
4671                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4672                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4673                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4674
4675                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4676                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4677                 }
4678                 self.forward_htlcs(&mut phantom_receives);
4679
4680                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4681                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4682                 // nice to do the work now if we can rather than while we're trying to get messages in the
4683                 // network stack.
4684                 self.check_free_holding_cells();
4685
4686                 if new_events.is_empty() { return }
4687                 let mut events = self.pending_events.lock().unwrap();
4688                 events.append(&mut new_events);
4689         }
4690
4691         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4692         ///
4693         /// Expects the caller to have a total_consistency_lock read lock.
4694         fn process_background_events(&self) -> NotifyOption {
4695                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4696
4697                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4698
4699                 let mut background_events = Vec::new();
4700                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4701                 if background_events.is_empty() {
4702                         return NotifyOption::SkipPersistNoEvents;
4703                 }
4704
4705                 for event in background_events.drain(..) {
4706                         match event {
4707                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4708                                         // The channel has already been closed, so no use bothering to care about the
4709                                         // monitor updating completing.
4710                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4711                                 },
4712                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4713                                         let mut updated_chan = false;
4714                                         {
4715                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4716                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4717                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4718                                                         let peer_state = &mut *peer_state_lock;
4719                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4720                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4721                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4722                                                                                 updated_chan = true;
4723                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4724                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4725                                                                         } else {
4726                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4727                                                                         }
4728                                                                 },
4729                                                                 hash_map::Entry::Vacant(_) => {},
4730                                                         }
4731                                                 }
4732                                         }
4733                                         if !updated_chan {
4734                                                 // TODO: Track this as in-flight even though the channel is closed.
4735                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4736                                         }
4737                                 },
4738                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4739                                         let per_peer_state = self.per_peer_state.read().unwrap();
4740                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4741                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4742                                                 let peer_state = &mut *peer_state_lock;
4743                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4744                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4745                                                 } else {
4746                                                         let update_actions = peer_state.monitor_update_blocked_actions
4747                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4748                                                         mem::drop(peer_state_lock);
4749                                                         mem::drop(per_peer_state);
4750                                                         self.handle_monitor_update_completion_actions(update_actions);
4751                                                 }
4752                                         }
4753                                 },
4754                         }
4755                 }
4756                 NotifyOption::DoPersist
4757         }
4758
4759         #[cfg(any(test, feature = "_test_utils"))]
4760         /// Process background events, for functional testing
4761         pub fn test_process_background_events(&self) {
4762                 let _lck = self.total_consistency_lock.read().unwrap();
4763                 let _ = self.process_background_events();
4764         }
4765
4766         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4767                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4768                 // If the feerate has decreased by less than half, don't bother
4769                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4770                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4771                                 log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4772                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4773                         }
4774                         return NotifyOption::SkipPersistNoEvents;
4775                 }
4776                 if !chan.context.is_live() {
4777                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
4778                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4779                         return NotifyOption::SkipPersistNoEvents;
4780                 }
4781                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4782                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4783
4784                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4785                 NotifyOption::DoPersist
4786         }
4787
4788         #[cfg(fuzzing)]
4789         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4790         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4791         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4792         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4793         pub fn maybe_update_chan_fees(&self) {
4794                 PersistenceNotifierGuard::optionally_notify(self, || {
4795                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4796
4797                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4798                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4799
4800                         let per_peer_state = self.per_peer_state.read().unwrap();
4801                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4802                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4803                                 let peer_state = &mut *peer_state_lock;
4804                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4805                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4806                                 ) {
4807                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4808                                                 min_mempool_feerate
4809                                         } else {
4810                                                 normal_feerate
4811                                         };
4812                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4813                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4814                                 }
4815                         }
4816
4817                         should_persist
4818                 });
4819         }
4820
4821         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4822         ///
4823         /// This currently includes:
4824         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4825         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4826         ///    than a minute, informing the network that they should no longer attempt to route over
4827         ///    the channel.
4828         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4829         ///    with the current [`ChannelConfig`].
4830         ///  * Removing peers which have disconnected but and no longer have any channels.
4831         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4832         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4833         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4834         ///    The latter is determined using the system clock in `std` and the highest seen block time
4835         ///    minus two hours in `no-std`.
4836         ///
4837         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4838         /// estimate fetches.
4839         ///
4840         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4841         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4842         pub fn timer_tick_occurred(&self) {
4843                 PersistenceNotifierGuard::optionally_notify(self, || {
4844                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4845
4846                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4847                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4848
4849                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4850                         let mut timed_out_mpp_htlcs = Vec::new();
4851                         let mut pending_peers_awaiting_removal = Vec::new();
4852                         let mut shutdown_channels = Vec::new();
4853
4854                         let mut process_unfunded_channel_tick = |
4855                                 chan_id: &ChannelId,
4856                                 context: &mut ChannelContext<SP>,
4857                                 unfunded_context: &mut UnfundedChannelContext,
4858                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4859                                 counterparty_node_id: PublicKey,
4860                         | {
4861                                 context.maybe_expire_prev_config();
4862                                 if unfunded_context.should_expire_unfunded_channel() {
4863                                         log_error!(self.logger,
4864                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4865                                         update_maps_on_chan_removal!(self, &context);
4866                                         self.issue_channel_close_events(&context, ClosureReason::HolderForceClosed);
4867                                         shutdown_channels.push(context.force_shutdown(false));
4868                                         pending_msg_events.push(MessageSendEvent::HandleError {
4869                                                 node_id: counterparty_node_id,
4870                                                 action: msgs::ErrorAction::SendErrorMessage {
4871                                                         msg: msgs::ErrorMessage {
4872                                                                 channel_id: *chan_id,
4873                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4874                                                         },
4875                                                 },
4876                                         });
4877                                         false
4878                                 } else {
4879                                         true
4880                                 }
4881                         };
4882
4883                         {
4884                                 let per_peer_state = self.per_peer_state.read().unwrap();
4885                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4886                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4887                                         let peer_state = &mut *peer_state_lock;
4888                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4889                                         let counterparty_node_id = *counterparty_node_id;
4890                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4891                                                 match phase {
4892                                                         ChannelPhase::Funded(chan) => {
4893                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4894                                                                         min_mempool_feerate
4895                                                                 } else {
4896                                                                         normal_feerate
4897                                                                 };
4898                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4899                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4900
4901                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4902                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4903                                                                         handle_errors.push((Err(err), counterparty_node_id));
4904                                                                         if needs_close { return false; }
4905                                                                 }
4906
4907                                                                 match chan.channel_update_status() {
4908                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4909                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4910                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4911                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4912                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4913                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4914                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4915                                                                                 n += 1;
4916                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4917                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4918                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4919                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4920                                                                                                         msg: update
4921                                                                                                 });
4922                                                                                         }
4923                                                                                         should_persist = NotifyOption::DoPersist;
4924                                                                                 } else {
4925                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4926                                                                                 }
4927                                                                         },
4928                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4929                                                                                 n += 1;
4930                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4931                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4932                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4933                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4934                                                                                                         msg: update
4935                                                                                                 });
4936                                                                                         }
4937                                                                                         should_persist = NotifyOption::DoPersist;
4938                                                                                 } else {
4939                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4940                                                                                 }
4941                                                                         },
4942                                                                         _ => {},
4943                                                                 }
4944
4945                                                                 chan.context.maybe_expire_prev_config();
4946
4947                                                                 if chan.should_disconnect_peer_awaiting_response() {
4948                                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4949                                                                                         counterparty_node_id, chan_id);
4950                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4951                                                                                 node_id: counterparty_node_id,
4952                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4953                                                                                         msg: msgs::WarningMessage {
4954                                                                                                 channel_id: *chan_id,
4955                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4956                                                                                         },
4957                                                                                 },
4958                                                                         });
4959                                                                 }
4960
4961                                                                 true
4962                                                         },
4963                                                         ChannelPhase::UnfundedInboundV1(chan) => {
4964                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4965                                                                         pending_msg_events, counterparty_node_id)
4966                                                         },
4967                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
4968                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4969                                                                         pending_msg_events, counterparty_node_id)
4970                                                         },
4971                                                 }
4972                                         });
4973
4974                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4975                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4976                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
4977                                                         peer_state.pending_msg_events.push(
4978                                                                 events::MessageSendEvent::HandleError {
4979                                                                         node_id: counterparty_node_id,
4980                                                                         action: msgs::ErrorAction::SendErrorMessage {
4981                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4982                                                                         },
4983                                                                 }
4984                                                         );
4985                                                 }
4986                                         }
4987                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4988
4989                                         if peer_state.ok_to_remove(true) {
4990                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4991                                         }
4992                                 }
4993                         }
4994
4995                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4996                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4997                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4998                         // we therefore need to remove the peer from `peer_state` separately.
4999                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
5000                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
5001                         // negative effects on parallelism as much as possible.
5002                         if pending_peers_awaiting_removal.len() > 0 {
5003                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
5004                                 for counterparty_node_id in pending_peers_awaiting_removal {
5005                                         match per_peer_state.entry(counterparty_node_id) {
5006                                                 hash_map::Entry::Occupied(entry) => {
5007                                                         // Remove the entry if the peer is still disconnected and we still
5008                                                         // have no channels to the peer.
5009                                                         let remove_entry = {
5010                                                                 let peer_state = entry.get().lock().unwrap();
5011                                                                 peer_state.ok_to_remove(true)
5012                                                         };
5013                                                         if remove_entry {
5014                                                                 entry.remove_entry();
5015                                                         }
5016                                                 },
5017                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
5018                                         }
5019                                 }
5020                         }
5021
5022                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
5023                                 if payment.htlcs.is_empty() {
5024                                         // This should be unreachable
5025                                         debug_assert!(false);
5026                                         return false;
5027                                 }
5028                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
5029                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
5030                                         // In this case we're not going to handle any timeouts of the parts here.
5031                                         // This condition determining whether the MPP is complete here must match
5032                                         // exactly the condition used in `process_pending_htlc_forwards`.
5033                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5034                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5035                                         {
5036                                                 return true;
5037                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5038                                                 htlc.timer_ticks += 1;
5039                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5040                                         }) {
5041                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5042                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5043                                                 return false;
5044                                         }
5045                                 }
5046                                 true
5047                         });
5048
5049                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5050                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5051                                 let reason = HTLCFailReason::from_failure_code(23);
5052                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5053                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5054                         }
5055
5056                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5057                                 let _ = handle_error!(self, err, counterparty_node_id);
5058                         }
5059
5060                         for shutdown_res in shutdown_channels {
5061                                 self.finish_close_channel(shutdown_res);
5062                         }
5063
5064                         #[cfg(feature = "std")]
5065                         let duration_since_epoch = std::time::SystemTime::now()
5066                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5067                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5068                         #[cfg(not(feature = "std"))]
5069                         let duration_since_epoch = Duration::from_secs(
5070                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5071                         );
5072
5073                         self.pending_outbound_payments.remove_stale_payments(
5074                                 duration_since_epoch, &self.pending_events
5075                         );
5076
5077                         // Technically we don't need to do this here, but if we have holding cell entries in a
5078                         // channel that need freeing, it's better to do that here and block a background task
5079                         // than block the message queueing pipeline.
5080                         if self.check_free_holding_cells() {
5081                                 should_persist = NotifyOption::DoPersist;
5082                         }
5083
5084                         should_persist
5085                 });
5086         }
5087
5088         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5089         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5090         /// along the path (including in our own channel on which we received it).
5091         ///
5092         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5093         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5094         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5095         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5096         ///
5097         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5098         /// [`ChannelManager::claim_funds`]), you should still monitor for
5099         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5100         /// startup during which time claims that were in-progress at shutdown may be replayed.
5101         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5102                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5103         }
5104
5105         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5106         /// reason for the failure.
5107         ///
5108         /// See [`FailureCode`] for valid failure codes.
5109         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5110                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5111
5112                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5113                 if let Some(payment) = removed_source {
5114                         for htlc in payment.htlcs {
5115                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5116                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5117                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5118                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5119                         }
5120                 }
5121         }
5122
5123         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5124         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5125                 match failure_code {
5126                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5127                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5128                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5129                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5130                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5131                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5132                         },
5133                         FailureCode::InvalidOnionPayload(data) => {
5134                                 let fail_data = match data {
5135                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5136                                         None => Vec::new(),
5137                                 };
5138                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5139                         }
5140                 }
5141         }
5142
5143         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5144         /// that we want to return and a channel.
5145         ///
5146         /// This is for failures on the channel on which the HTLC was *received*, not failures
5147         /// forwarding
5148         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5149                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5150                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5151                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5152                 // an inbound SCID alias before the real SCID.
5153                 let scid_pref = if chan.context.should_announce() {
5154                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5155                 } else {
5156                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5157                 };
5158                 if let Some(scid) = scid_pref {
5159                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5160                 } else {
5161                         (0x4000|10, Vec::new())
5162                 }
5163         }
5164
5165
5166         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5167         /// that we want to return and a channel.
5168         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5169                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5170                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5171                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5172                         if desired_err_code == 0x1000 | 20 {
5173                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5174                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5175                                 0u16.write(&mut enc).expect("Writes cannot fail");
5176                         }
5177                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5178                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5179                         upd.write(&mut enc).expect("Writes cannot fail");
5180                         (desired_err_code, enc.0)
5181                 } else {
5182                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5183                         // which means we really shouldn't have gotten a payment to be forwarded over this
5184                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5185                         // PERM|no_such_channel should be fine.
5186                         (0x4000|10, Vec::new())
5187                 }
5188         }
5189
5190         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5191         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5192         // be surfaced to the user.
5193         fn fail_holding_cell_htlcs(
5194                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5195                 counterparty_node_id: &PublicKey
5196         ) {
5197                 let (failure_code, onion_failure_data) = {
5198                         let per_peer_state = self.per_peer_state.read().unwrap();
5199                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5200                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5201                                 let peer_state = &mut *peer_state_lock;
5202                                 match peer_state.channel_by_id.entry(channel_id) {
5203                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5204                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5205                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5206                                                 } else {
5207                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5208                                                         debug_assert!(false);
5209                                                         (0x4000|10, Vec::new())
5210                                                 }
5211                                         },
5212                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5213                                 }
5214                         } else { (0x4000|10, Vec::new()) }
5215                 };
5216
5217                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5218                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5219                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5220                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5221                 }
5222         }
5223
5224         /// Fails an HTLC backwards to the sender of it to us.
5225         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5226         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5227                 // Ensure that no peer state channel storage lock is held when calling this function.
5228                 // This ensures that future code doesn't introduce a lock-order requirement for
5229                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5230                 // this function with any `per_peer_state` peer lock acquired would.
5231                 #[cfg(debug_assertions)]
5232                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5233                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5234                 }
5235
5236                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5237                 //identify whether we sent it or not based on the (I presume) very different runtime
5238                 //between the branches here. We should make this async and move it into the forward HTLCs
5239                 //timer handling.
5240
5241                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5242                 // from block_connected which may run during initialization prior to the chain_monitor
5243                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5244                 match source {
5245                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5246                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5247                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5248                                         &self.pending_events, &self.logger)
5249                                 { self.push_pending_forwards_ev(); }
5250                         },
5251                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint, .. }) => {
5252                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", &payment_hash, onion_error);
5253                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
5254
5255                                 let mut push_forward_ev = false;
5256                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5257                                 if forward_htlcs.is_empty() {
5258                                         push_forward_ev = true;
5259                                 }
5260                                 match forward_htlcs.entry(*short_channel_id) {
5261                                         hash_map::Entry::Occupied(mut entry) => {
5262                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
5263                                         },
5264                                         hash_map::Entry::Vacant(entry) => {
5265                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
5266                                         }
5267                                 }
5268                                 mem::drop(forward_htlcs);
5269                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5270                                 let mut pending_events = self.pending_events.lock().unwrap();
5271                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5272                                         prev_channel_id: outpoint.to_channel_id(),
5273                                         failed_next_destination: destination,
5274                                 }, None));
5275                         },
5276                 }
5277         }
5278
5279         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5280         /// [`MessageSendEvent`]s needed to claim the payment.
5281         ///
5282         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5283         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5284         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5285         /// successful. It will generally be available in the next [`process_pending_events`] call.
5286         ///
5287         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5288         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5289         /// event matches your expectation. If you fail to do so and call this method, you may provide
5290         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5291         ///
5292         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5293         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5294         /// [`claim_funds_with_known_custom_tlvs`].
5295         ///
5296         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5297         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5298         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5299         /// [`process_pending_events`]: EventsProvider::process_pending_events
5300         /// [`create_inbound_payment`]: Self::create_inbound_payment
5301         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5302         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5303         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5304                 self.claim_payment_internal(payment_preimage, false);
5305         }
5306
5307         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5308         /// even type numbers.
5309         ///
5310         /// # Note
5311         ///
5312         /// You MUST check you've understood all even TLVs before using this to
5313         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5314         ///
5315         /// [`claim_funds`]: Self::claim_funds
5316         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5317                 self.claim_payment_internal(payment_preimage, true);
5318         }
5319
5320         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5321                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5322
5323                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5324
5325                 let mut sources = {
5326                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5327                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5328                                 let mut receiver_node_id = self.our_network_pubkey;
5329                                 for htlc in payment.htlcs.iter() {
5330                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5331                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5332                                                         .expect("Failed to get node_id for phantom node recipient");
5333                                                 receiver_node_id = phantom_pubkey;
5334                                                 break;
5335                                         }
5336                                 }
5337
5338                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5339                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5340                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5341                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5342                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5343                                 });
5344                                 if dup_purpose.is_some() {
5345                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5346                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5347                                                 &payment_hash);
5348                                 }
5349
5350                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5351                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5352                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5353                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5354                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5355                                                 mem::drop(claimable_payments);
5356                                                 for htlc in payment.htlcs {
5357                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5358                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5359                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5360                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5361                                                 }
5362                                                 return;
5363                                         }
5364                                 }
5365
5366                                 payment.htlcs
5367                         } else { return; }
5368                 };
5369                 debug_assert!(!sources.is_empty());
5370
5371                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5372                 // and when we got here we need to check that the amount we're about to claim matches the
5373                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5374                 // the MPP parts all have the same `total_msat`.
5375                 let mut claimable_amt_msat = 0;
5376                 let mut prev_total_msat = None;
5377                 let mut expected_amt_msat = None;
5378                 let mut valid_mpp = true;
5379                 let mut errs = Vec::new();
5380                 let per_peer_state = self.per_peer_state.read().unwrap();
5381                 for htlc in sources.iter() {
5382                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5383                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5384                                 debug_assert!(false);
5385                                 valid_mpp = false;
5386                                 break;
5387                         }
5388                         prev_total_msat = Some(htlc.total_msat);
5389
5390                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5391                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5392                                 debug_assert!(false);
5393                                 valid_mpp = false;
5394                                 break;
5395                         }
5396                         expected_amt_msat = htlc.total_value_received;
5397                         claimable_amt_msat += htlc.value;
5398                 }
5399                 mem::drop(per_peer_state);
5400                 if sources.is_empty() || expected_amt_msat.is_none() {
5401                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5402                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5403                         return;
5404                 }
5405                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5406                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5407                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5408                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5409                         return;
5410                 }
5411                 if valid_mpp {
5412                         for htlc in sources.drain(..) {
5413                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5414                                         htlc.prev_hop, payment_preimage,
5415                                         |_, definitely_duplicate| {
5416                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5417                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5418                                         }
5419                                 ) {
5420                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5421                                                 // We got a temporary failure updating monitor, but will claim the
5422                                                 // HTLC when the monitor updating is restored (or on chain).
5423                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5424                                         } else { errs.push((pk, err)); }
5425                                 }
5426                         }
5427                 }
5428                 if !valid_mpp {
5429                         for htlc in sources.drain(..) {
5430                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5431                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5432                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5433                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5434                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5435                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5436                         }
5437                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5438                 }
5439
5440                 // Now we can handle any errors which were generated.
5441                 for (counterparty_node_id, err) in errs.drain(..) {
5442                         let res: Result<(), _> = Err(err);
5443                         let _ = handle_error!(self, res, counterparty_node_id);
5444                 }
5445         }
5446
5447         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5448                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5449         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5450                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5451
5452                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5453                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5454                 // `BackgroundEvent`s.
5455                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5456
5457                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5458                 // the required mutexes are not held before we start.
5459                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5460                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5461
5462                 {
5463                         let per_peer_state = self.per_peer_state.read().unwrap();
5464                         let chan_id = prev_hop.outpoint.to_channel_id();
5465                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5466                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5467                                 None => None
5468                         };
5469
5470                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5471                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5472                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5473                         ).unwrap_or(None);
5474
5475                         if peer_state_opt.is_some() {
5476                                 let mut peer_state_lock = peer_state_opt.unwrap();
5477                                 let peer_state = &mut *peer_state_lock;
5478                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5479                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5480                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5481                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5482
5483                                                 match fulfill_res {
5484                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5485                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5486                                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5487                                                                                 chan_id, action);
5488                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5489                                                                 }
5490                                                                 if !during_init {
5491                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5492                                                                                 peer_state, per_peer_state, chan);
5493                                                                 } else {
5494                                                                         // If we're running during init we cannot update a monitor directly -
5495                                                                         // they probably haven't actually been loaded yet. Instead, push the
5496                                                                         // monitor update as a background event.
5497                                                                         self.pending_background_events.lock().unwrap().push(
5498                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5499                                                                                         counterparty_node_id,
5500                                                                                         funding_txo: prev_hop.outpoint,
5501                                                                                         update: monitor_update.clone(),
5502                                                                                 });
5503                                                                 }
5504                                                         }
5505                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5506                                                                 let action = if let Some(action) = completion_action(None, true) {
5507                                                                         action
5508                                                                 } else {
5509                                                                         return Ok(());
5510                                                                 };
5511                                                                 mem::drop(peer_state_lock);
5512
5513                                                                 log_trace!(self.logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5514                                                                         chan_id, action);
5515                                                                 let (node_id, funding_outpoint, blocker) =
5516                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5517                                                                         downstream_counterparty_node_id: node_id,
5518                                                                         downstream_funding_outpoint: funding_outpoint,
5519                                                                         blocking_action: blocker,
5520                                                                 } = action {
5521                                                                         (node_id, funding_outpoint, blocker)
5522                                                                 } else {
5523                                                                         debug_assert!(false,
5524                                                                                 "Duplicate claims should always free another channel immediately");
5525                                                                         return Ok(());
5526                                                                 };
5527                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5528                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5529                                                                         if let Some(blockers) = peer_state
5530                                                                                 .actions_blocking_raa_monitor_updates
5531                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5532                                                                         {
5533                                                                                 let mut found_blocker = false;
5534                                                                                 blockers.retain(|iter| {
5535                                                                                         // Note that we could actually be blocked, in
5536                                                                                         // which case we need to only remove the one
5537                                                                                         // blocker which was added duplicatively.
5538                                                                                         let first_blocker = !found_blocker;
5539                                                                                         if *iter == blocker { found_blocker = true; }
5540                                                                                         *iter != blocker || !first_blocker
5541                                                                                 });
5542                                                                                 debug_assert!(found_blocker);
5543                                                                         }
5544                                                                 } else {
5545                                                                         debug_assert!(false);
5546                                                                 }
5547                                                         }
5548                                                 }
5549                                         }
5550                                         return Ok(());
5551                                 }
5552                         }
5553                 }
5554                 let preimage_update = ChannelMonitorUpdate {
5555                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5556                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5557                                 payment_preimage,
5558                         }],
5559                 };
5560
5561                 if !during_init {
5562                         // We update the ChannelMonitor on the backward link, after
5563                         // receiving an `update_fulfill_htlc` from the forward link.
5564                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5565                         if update_res != ChannelMonitorUpdateStatus::Completed {
5566                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5567                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5568                                 // channel, or we must have an ability to receive the same event and try
5569                                 // again on restart.
5570                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5571                                         payment_preimage, update_res);
5572                         }
5573                 } else {
5574                         // If we're running during init we cannot update a monitor directly - they probably
5575                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5576                         // event.
5577                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5578                         // channel is already closed) we need to ultimately handle the monitor update
5579                         // completion action only after we've completed the monitor update. This is the only
5580                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5581                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5582                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5583                         // complete the monitor update completion action from `completion_action`.
5584                         self.pending_background_events.lock().unwrap().push(
5585                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5586                                         prev_hop.outpoint, preimage_update,
5587                                 )));
5588                 }
5589                 // Note that we do process the completion action here. This totally could be a
5590                 // duplicate claim, but we have no way of knowing without interrogating the
5591                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5592                 // generally always allowed to be duplicative (and it's specifically noted in
5593                 // `PaymentForwarded`).
5594                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5595                 Ok(())
5596         }
5597
5598         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5599                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5600         }
5601
5602         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5603                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5604                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5605         ) {
5606                 match source {
5607                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5608                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5609                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5610                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5611                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5612                                 }
5613                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5614                                         channel_funding_outpoint: next_channel_outpoint,
5615                                         counterparty_node_id: path.hops[0].pubkey,
5616                                 };
5617                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5618                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5619                                         &self.logger);
5620                         },
5621                         HTLCSource::PreviousHopData(hop_data) => {
5622                                 let prev_outpoint = hop_data.outpoint;
5623                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5624                                 #[cfg(debug_assertions)]
5625                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5626                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5627                                         |htlc_claim_value_msat, definitely_duplicate| {
5628                                                 let chan_to_release =
5629                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5630                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5631                                                         } else {
5632                                                                 // We can only get `None` here if we are processing a
5633                                                                 // `ChannelMonitor`-originated event, in which case we
5634                                                                 // don't care about ensuring we wake the downstream
5635                                                                 // channel's monitor updating - the channel is already
5636                                                                 // closed.
5637                                                                 None
5638                                                         };
5639
5640                                                 if definitely_duplicate && startup_replay {
5641                                                         // On startup we may get redundant claims which are related to
5642                                                         // monitor updates still in flight. In that case, we shouldn't
5643                                                         // immediately free, but instead let that monitor update complete
5644                                                         // in the background.
5645                                                         #[cfg(debug_assertions)] {
5646                                                                 let background_events = self.pending_background_events.lock().unwrap();
5647                                                                 // There should be a `BackgroundEvent` pending...
5648                                                                 assert!(background_events.iter().any(|ev| {
5649                                                                         match ev {
5650                                                                                 // to apply a monitor update that blocked the claiming channel,
5651                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5652                                                                                         funding_txo, update, ..
5653                                                                                 } => {
5654                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5655                                                                                                 assert!(update.updates.iter().any(|upd|
5656                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5657                                                                                                                 payment_preimage: update_preimage
5658                                                                                                         } = upd {
5659                                                                                                                 payment_preimage == *update_preimage
5660                                                                                                         } else { false }
5661                                                                                                 ), "{:?}", update);
5662                                                                                                 true
5663                                                                                         } else { false }
5664                                                                                 },
5665                                                                                 // or the channel we'd unblock is already closed,
5666                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5667                                                                                         (funding_txo, monitor_update)
5668                                                                                 ) => {
5669                                                                                         if *funding_txo == next_channel_outpoint {
5670                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5671                                                                                                 assert!(matches!(
5672                                                                                                         monitor_update.updates[0],
5673                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5674                                                                                                 ));
5675                                                                                                 true
5676                                                                                         } else { false }
5677                                                                                 },
5678                                                                                 // or the monitor update has completed and will unblock
5679                                                                                 // immediately once we get going.
5680                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5681                                                                                         channel_id, ..
5682                                                                                 } =>
5683                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5684                                                                         }
5685                                                                 }), "{:?}", *background_events);
5686                                                         }
5687                                                         None
5688                                                 } else if definitely_duplicate {
5689                                                         if let Some(other_chan) = chan_to_release {
5690                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5691                                                                         downstream_counterparty_node_id: other_chan.0,
5692                                                                         downstream_funding_outpoint: other_chan.1,
5693                                                                         blocking_action: other_chan.2,
5694                                                                 })
5695                                                         } else { None }
5696                                                 } else {
5697                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5698                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5699                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5700                                                                 } else { None }
5701                                                         } else { None };
5702                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5703                                                                 event: events::Event::PaymentForwarded {
5704                                                                         fee_earned_msat,
5705                                                                         claim_from_onchain_tx: from_onchain,
5706                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5707                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5708                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5709                                                                 },
5710                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5711                                                         })
5712                                                 }
5713                                         });
5714                                 if let Err((pk, err)) = res {
5715                                         let result: Result<(), _> = Err(err);
5716                                         let _ = handle_error!(self, result, pk);
5717                                 }
5718                         },
5719                 }
5720         }
5721
5722         /// Gets the node_id held by this ChannelManager
5723         pub fn get_our_node_id(&self) -> PublicKey {
5724                 self.our_network_pubkey.clone()
5725         }
5726
5727         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5728                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5729                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5730                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5731
5732                 for action in actions.into_iter() {
5733                         match action {
5734                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5735                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5736                                         if let Some(ClaimingPayment {
5737                                                 amount_msat,
5738                                                 payment_purpose: purpose,
5739                                                 receiver_node_id,
5740                                                 htlcs,
5741                                                 sender_intended_value: sender_intended_total_msat,
5742                                         }) = payment {
5743                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5744                                                         payment_hash,
5745                                                         purpose,
5746                                                         amount_msat,
5747                                                         receiver_node_id: Some(receiver_node_id),
5748                                                         htlcs,
5749                                                         sender_intended_total_msat,
5750                                                 }, None));
5751                                         }
5752                                 },
5753                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5754                                         event, downstream_counterparty_and_funding_outpoint
5755                                 } => {
5756                                         self.pending_events.lock().unwrap().push_back((event, None));
5757                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5758                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5759                                         }
5760                                 },
5761                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5762                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5763                                 } => {
5764                                         self.handle_monitor_update_release(
5765                                                 downstream_counterparty_node_id,
5766                                                 downstream_funding_outpoint,
5767                                                 Some(blocking_action),
5768                                         );
5769                                 },
5770                         }
5771                 }
5772         }
5773
5774         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5775         /// update completion.
5776         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5777                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5778                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5779                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5780                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5781         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5782                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5783                         &channel.context.channel_id(),
5784                         if raa.is_some() { "an" } else { "no" },
5785                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5786                         if funding_broadcastable.is_some() { "" } else { "not " },
5787                         if channel_ready.is_some() { "sending" } else { "without" },
5788                         if announcement_sigs.is_some() { "sending" } else { "without" });
5789
5790                 let mut htlc_forwards = None;
5791
5792                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5793                 if !pending_forwards.is_empty() {
5794                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5795                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5796                 }
5797
5798                 if let Some(msg) = channel_ready {
5799                         send_channel_ready!(self, pending_msg_events, channel, msg);
5800                 }
5801                 if let Some(msg) = announcement_sigs {
5802                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5803                                 node_id: counterparty_node_id,
5804                                 msg,
5805                         });
5806                 }
5807
5808                 macro_rules! handle_cs { () => {
5809                         if let Some(update) = commitment_update {
5810                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5811                                         node_id: counterparty_node_id,
5812                                         updates: update,
5813                                 });
5814                         }
5815                 } }
5816                 macro_rules! handle_raa { () => {
5817                         if let Some(revoke_and_ack) = raa {
5818                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5819                                         node_id: counterparty_node_id,
5820                                         msg: revoke_and_ack,
5821                                 });
5822                         }
5823                 } }
5824                 match order {
5825                         RAACommitmentOrder::CommitmentFirst => {
5826                                 handle_cs!();
5827                                 handle_raa!();
5828                         },
5829                         RAACommitmentOrder::RevokeAndACKFirst => {
5830                                 handle_raa!();
5831                                 handle_cs!();
5832                         },
5833                 }
5834
5835                 if let Some(tx) = funding_broadcastable {
5836                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5837                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5838                 }
5839
5840                 {
5841                         let mut pending_events = self.pending_events.lock().unwrap();
5842                         emit_channel_pending_event!(pending_events, channel);
5843                         emit_channel_ready_event!(pending_events, channel);
5844                 }
5845
5846                 htlc_forwards
5847         }
5848
5849         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5850                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5851
5852                 let counterparty_node_id = match counterparty_node_id {
5853                         Some(cp_id) => cp_id.clone(),
5854                         None => {
5855                                 // TODO: Once we can rely on the counterparty_node_id from the
5856                                 // monitor event, this and the id_to_peer map should be removed.
5857                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5858                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5859                                         Some(cp_id) => cp_id.clone(),
5860                                         None => return,
5861                                 }
5862                         }
5863                 };
5864                 let per_peer_state = self.per_peer_state.read().unwrap();
5865                 let mut peer_state_lock;
5866                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5867                 if peer_state_mutex_opt.is_none() { return }
5868                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5869                 let peer_state = &mut *peer_state_lock;
5870                 let channel =
5871                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5872                                 chan
5873                         } else {
5874                                 let update_actions = peer_state.monitor_update_blocked_actions
5875                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5876                                 mem::drop(peer_state_lock);
5877                                 mem::drop(per_peer_state);
5878                                 self.handle_monitor_update_completion_actions(update_actions);
5879                                 return;
5880                         };
5881                 let remaining_in_flight =
5882                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5883                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5884                                 pending.len()
5885                         } else { 0 };
5886                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5887                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5888                         remaining_in_flight);
5889                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5890                         return;
5891                 }
5892                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5893         }
5894
5895         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5896         ///
5897         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5898         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5899         /// the channel.
5900         ///
5901         /// The `user_channel_id` parameter will be provided back in
5902         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5903         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5904         ///
5905         /// Note that this method will return an error and reject the channel, if it requires support
5906         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5907         /// used to accept such channels.
5908         ///
5909         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5910         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5911         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5912                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5913         }
5914
5915         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5916         /// it as confirmed immediately.
5917         ///
5918         /// The `user_channel_id` parameter will be provided back in
5919         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5920         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5921         ///
5922         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5923         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5924         ///
5925         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5926         /// transaction and blindly assumes that it will eventually confirm.
5927         ///
5928         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5929         /// does not pay to the correct script the correct amount, *you will lose funds*.
5930         ///
5931         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5932         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5933         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5934                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5935         }
5936
5937         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5938                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5939
5940                 let peers_without_funded_channels =
5941                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5942                 let per_peer_state = self.per_peer_state.read().unwrap();
5943                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5944                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5945                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5946                 let peer_state = &mut *peer_state_lock;
5947                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5948
5949                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5950                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5951                 // that we can delay allocating the SCID until after we're sure that the checks below will
5952                 // succeed.
5953                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5954                         Some(unaccepted_channel) => {
5955                                 let best_block_height = self.best_block.read().unwrap().height();
5956                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5957                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5958                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5959                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5960                         }
5961                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5962                 }?;
5963
5964                 if accept_0conf {
5965                         // This should have been correctly configured by the call to InboundV1Channel::new.
5966                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5967                 } else if channel.context.get_channel_type().requires_zero_conf() {
5968                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5969                                 node_id: channel.context.get_counterparty_node_id(),
5970                                 action: msgs::ErrorAction::SendErrorMessage{
5971                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5972                                 }
5973                         };
5974                         peer_state.pending_msg_events.push(send_msg_err_event);
5975                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5976                 } else {
5977                         // If this peer already has some channels, a new channel won't increase our number of peers
5978                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5979                         // channels per-peer we can accept channels from a peer with existing ones.
5980                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5981                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5982                                         node_id: channel.context.get_counterparty_node_id(),
5983                                         action: msgs::ErrorAction::SendErrorMessage{
5984                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5985                                         }
5986                                 };
5987                                 peer_state.pending_msg_events.push(send_msg_err_event);
5988                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5989                         }
5990                 }
5991
5992                 // Now that we know we have a channel, assign an outbound SCID alias.
5993                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5994                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5995
5996                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5997                         node_id: channel.context.get_counterparty_node_id(),
5998                         msg: channel.accept_inbound_channel(),
5999                 });
6000
6001                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
6002
6003                 Ok(())
6004         }
6005
6006         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
6007         /// or 0-conf channels.
6008         ///
6009         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6010         /// non-0-conf channels we have with the peer.
6011         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6012         where Filter: Fn(&PeerState<SP>) -> bool {
6013                 let mut peers_without_funded_channels = 0;
6014                 let best_block_height = self.best_block.read().unwrap().height();
6015                 {
6016                         let peer_state_lock = self.per_peer_state.read().unwrap();
6017                         for (_, peer_mtx) in peer_state_lock.iter() {
6018                                 let peer = peer_mtx.lock().unwrap();
6019                                 if !maybe_count_peer(&*peer) { continue; }
6020                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6021                                 if num_unfunded_channels == peer.total_channel_count() {
6022                                         peers_without_funded_channels += 1;
6023                                 }
6024                         }
6025                 }
6026                 return peers_without_funded_channels;
6027         }
6028
6029         fn unfunded_channel_count(
6030                 peer: &PeerState<SP>, best_block_height: u32
6031         ) -> usize {
6032                 let mut num_unfunded_channels = 0;
6033                 for (_, phase) in peer.channel_by_id.iter() {
6034                         match phase {
6035                                 ChannelPhase::Funded(chan) => {
6036                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6037                                         // which have not yet had any confirmations on-chain.
6038                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6039                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6040                                         {
6041                                                 num_unfunded_channels += 1;
6042                                         }
6043                                 },
6044                                 ChannelPhase::UnfundedInboundV1(chan) => {
6045                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6046                                                 num_unfunded_channels += 1;
6047                                         }
6048                                 },
6049                                 ChannelPhase::UnfundedOutboundV1(_) => {
6050                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6051                                         continue;
6052                                 }
6053                         }
6054                 }
6055                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6056         }
6057
6058         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6059                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6060                 // likely to be lost on restart!
6061                 if msg.chain_hash != self.chain_hash {
6062                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
6063                 }
6064
6065                 if !self.default_configuration.accept_inbound_channels {
6066                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6067                 }
6068
6069                 // Get the number of peers with channels, but without funded ones. We don't care too much
6070                 // about peers that never open a channel, so we filter by peers that have at least one
6071                 // channel, and then limit the number of those with unfunded channels.
6072                 let channeled_peers_without_funding =
6073                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6074
6075                 let per_peer_state = self.per_peer_state.read().unwrap();
6076                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6077                     .ok_or_else(|| {
6078                                 debug_assert!(false);
6079                                 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())
6080                         })?;
6081                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6082                 let peer_state = &mut *peer_state_lock;
6083
6084                 // If this peer already has some channels, a new channel won't increase our number of peers
6085                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6086                 // channels per-peer we can accept channels from a peer with existing ones.
6087                 if peer_state.total_channel_count() == 0 &&
6088                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6089                         !self.default_configuration.manually_accept_inbound_channels
6090                 {
6091                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6092                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6093                                 msg.temporary_channel_id.clone()));
6094                 }
6095
6096                 let best_block_height = self.best_block.read().unwrap().height();
6097                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6098                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6099                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6100                                 msg.temporary_channel_id.clone()));
6101                 }
6102
6103                 let channel_id = msg.temporary_channel_id;
6104                 let channel_exists = peer_state.has_channel(&channel_id);
6105                 if channel_exists {
6106                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
6107                 }
6108
6109                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6110                 if self.default_configuration.manually_accept_inbound_channels {
6111                         let mut pending_events = self.pending_events.lock().unwrap();
6112                         pending_events.push_back((events::Event::OpenChannelRequest {
6113                                 temporary_channel_id: msg.temporary_channel_id.clone(),
6114                                 counterparty_node_id: counterparty_node_id.clone(),
6115                                 funding_satoshis: msg.funding_satoshis,
6116                                 push_msat: msg.push_msat,
6117                                 channel_type: msg.channel_type.clone().unwrap(),
6118                         }, None));
6119                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6120                                 open_channel_msg: msg.clone(),
6121                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6122                         });
6123                         return Ok(());
6124                 }
6125
6126                 // Otherwise create the channel right now.
6127                 let mut random_bytes = [0u8; 16];
6128                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6129                 let user_channel_id = u128::from_be_bytes(random_bytes);
6130                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6131                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6132                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6133                 {
6134                         Err(e) => {
6135                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
6136                         },
6137                         Ok(res) => res
6138                 };
6139
6140                 let channel_type = channel.context.get_channel_type();
6141                 if channel_type.requires_zero_conf() {
6142                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6143                 }
6144                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6145                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
6146                 }
6147
6148                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6149                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6150
6151                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6152                         node_id: counterparty_node_id.clone(),
6153                         msg: channel.accept_inbound_channel(),
6154                 });
6155                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6156                 Ok(())
6157         }
6158
6159         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6160                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6161                 // likely to be lost on restart!
6162                 let (value, output_script, user_id) = {
6163                         let per_peer_state = self.per_peer_state.read().unwrap();
6164                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6165                                 .ok_or_else(|| {
6166                                         debug_assert!(false);
6167                                         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)
6168                                 })?;
6169                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6170                         let peer_state = &mut *peer_state_lock;
6171                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6172                                 hash_map::Entry::Occupied(mut phase) => {
6173                                         match phase.get_mut() {
6174                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6175                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6176                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6177                                                 },
6178                                                 _ => {
6179                                                         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));
6180                                                 }
6181                                         }
6182                                 },
6183                                 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))
6184                         }
6185                 };
6186                 let mut pending_events = self.pending_events.lock().unwrap();
6187                 pending_events.push_back((events::Event::FundingGenerationReady {
6188                         temporary_channel_id: msg.temporary_channel_id,
6189                         counterparty_node_id: *counterparty_node_id,
6190                         channel_value_satoshis: value,
6191                         output_script,
6192                         user_channel_id: user_id,
6193                 }, None));
6194                 Ok(())
6195         }
6196
6197         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6198                 let best_block = *self.best_block.read().unwrap();
6199
6200                 let per_peer_state = self.per_peer_state.read().unwrap();
6201                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6202                         .ok_or_else(|| {
6203                                 debug_assert!(false);
6204                                 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)
6205                         })?;
6206
6207                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6208                 let peer_state = &mut *peer_state_lock;
6209                 let (chan, funding_msg, monitor) =
6210                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6211                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6212                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
6213                                                 Ok(res) => res,
6214                                                 Err((mut inbound_chan, err)) => {
6215                                                         // We've already removed this inbound channel from the map in `PeerState`
6216                                                         // above so at this point we just need to clean up any lingering entries
6217                                                         // concerning this channel as it is safe to do so.
6218                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
6219                                                         let user_id = inbound_chan.context.get_user_id();
6220                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
6221                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
6222                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
6223                                                 },
6224                                         }
6225                                 },
6226                                 Some(ChannelPhase::Funded(_)) | Some(ChannelPhase::UnfundedOutboundV1(_)) => {
6227                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id));
6228                                 },
6229                                 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))
6230                         };
6231
6232                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
6233                         hash_map::Entry::Occupied(_) => {
6234                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
6235                         },
6236                         hash_map::Entry::Vacant(e) => {
6237                                 let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
6238                                 match id_to_peer_lock.entry(chan.context.channel_id()) {
6239                                         hash_map::Entry::Occupied(_) => {
6240                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
6241                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6242                                                         funding_msg.channel_id))
6243                                         },
6244                                         hash_map::Entry::Vacant(i_e) => {
6245                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6246                                                 if let Ok(persist_state) = monitor_res {
6247                                                         i_e.insert(chan.context.get_counterparty_node_id());
6248                                                         mem::drop(id_to_peer_lock);
6249
6250                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6251                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6252                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6253                                                         // until we have persisted our monitor.
6254                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6255                                                                 node_id: counterparty_node_id.clone(),
6256                                                                 msg: funding_msg,
6257                                                         });
6258
6259                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6260                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6261                                                                         per_peer_state, chan, INITIAL_MONITOR);
6262                                                         } else {
6263                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6264                                                         }
6265                                                         Ok(())
6266                                                 } else {
6267                                                         log_error!(self.logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6268                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6269                                                                 "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6270                                                                 funding_msg.channel_id));
6271                                                 }
6272                                         }
6273                                 }
6274                         }
6275                 }
6276         }
6277
6278         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6279                 let best_block = *self.best_block.read().unwrap();
6280                 let per_peer_state = self.per_peer_state.read().unwrap();
6281                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6282                         .ok_or_else(|| {
6283                                 debug_assert!(false);
6284                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6285                         })?;
6286
6287                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6288                 let peer_state = &mut *peer_state_lock;
6289                 match peer_state.channel_by_id.entry(msg.channel_id) {
6290                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6291                                 match chan_phase_entry.get_mut() {
6292                                         ChannelPhase::Funded(ref mut chan) => {
6293                                                 let monitor = try_chan_phase_entry!(self,
6294                                                         chan.funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan_phase_entry);
6295                                                 if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6296                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6297                                                         Ok(())
6298                                                 } else {
6299                                                         try_chan_phase_entry!(self, Err(ChannelError::Close("Channel funding outpoint was a duplicate".to_owned())), chan_phase_entry)
6300                                                 }
6301                                         },
6302                                         _ => {
6303                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6304                                         },
6305                                 }
6306                         },
6307                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6308                 }
6309         }
6310
6311         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6312                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6313                 // closing a channel), so any changes are likely to be lost on restart!
6314                 let per_peer_state = self.per_peer_state.read().unwrap();
6315                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6316                         .ok_or_else(|| {
6317                                 debug_assert!(false);
6318                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6319                         })?;
6320                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6321                 let peer_state = &mut *peer_state_lock;
6322                 match peer_state.channel_by_id.entry(msg.channel_id) {
6323                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6324                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6325                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6326                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
6327                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6328                                                 log_trace!(self.logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6329                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6330                                                         node_id: counterparty_node_id.clone(),
6331                                                         msg: announcement_sigs,
6332                                                 });
6333                                         } else if chan.context.is_usable() {
6334                                                 // If we're sending an announcement_signatures, we'll send the (public)
6335                                                 // channel_update after sending a channel_announcement when we receive our
6336                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6337                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6338                                                 // announcement_signatures.
6339                                                 log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6340                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6341                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6342                                                                 node_id: counterparty_node_id.clone(),
6343                                                                 msg,
6344                                                         });
6345                                                 }
6346                                         }
6347
6348                                         {
6349                                                 let mut pending_events = self.pending_events.lock().unwrap();
6350                                                 emit_channel_ready_event!(pending_events, chan);
6351                                         }
6352
6353                                         Ok(())
6354                                 } else {
6355                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6356                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6357                                 }
6358                         },
6359                         hash_map::Entry::Vacant(_) => {
6360                                 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))
6361                         }
6362                 }
6363         }
6364
6365         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6366                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6367                 let mut finish_shutdown = None;
6368                 {
6369                         let per_peer_state = self.per_peer_state.read().unwrap();
6370                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6371                                 .ok_or_else(|| {
6372                                         debug_assert!(false);
6373                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6374                                 })?;
6375                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6376                         let peer_state = &mut *peer_state_lock;
6377                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6378                                 let phase = chan_phase_entry.get_mut();
6379                                 match phase {
6380                                         ChannelPhase::Funded(chan) => {
6381                                                 if !chan.received_shutdown() {
6382                                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
6383                                                                 msg.channel_id,
6384                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6385                                                 }
6386
6387                                                 let funding_txo_opt = chan.context.get_funding_txo();
6388                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6389                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6390                                                 dropped_htlcs = htlcs;
6391
6392                                                 if let Some(msg) = shutdown {
6393                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6394                                                         // here as we don't need the monitor update to complete until we send a
6395                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6396                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6397                                                                 node_id: *counterparty_node_id,
6398                                                                 msg,
6399                                                         });
6400                                                 }
6401                                                 // Update the monitor with the shutdown script if necessary.
6402                                                 if let Some(monitor_update) = monitor_update_opt {
6403                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6404                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6405                                                 }
6406                                         },
6407                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6408                                                 let context = phase.context_mut();
6409                                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6410                                                 self.issue_channel_close_events(&context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
6411                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6412                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false));
6413                                         },
6414                                 }
6415                         } else {
6416                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6417                         }
6418                 }
6419                 for htlc_source in dropped_htlcs.drain(..) {
6420                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6421                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6422                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6423                 }
6424                 if let Some(shutdown_res) = finish_shutdown {
6425                         self.finish_close_channel(shutdown_res);
6426                 }
6427
6428                 Ok(())
6429         }
6430
6431         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6432                 let mut shutdown_result = None;
6433                 let unbroadcasted_batch_funding_txid;
6434                 let per_peer_state = self.per_peer_state.read().unwrap();
6435                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6436                         .ok_or_else(|| {
6437                                 debug_assert!(false);
6438                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6439                         })?;
6440                 let (tx, chan_option) = {
6441                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6442                         let peer_state = &mut *peer_state_lock;
6443                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6444                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6445                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6446                                                 unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
6447                                                 let (closing_signed, tx) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6448                                                 if let Some(msg) = closing_signed {
6449                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6450                                                                 node_id: counterparty_node_id.clone(),
6451                                                                 msg,
6452                                                         });
6453                                                 }
6454                                                 if tx.is_some() {
6455                                                         // We're done with this channel, we've got a signed closing transaction and
6456                                                         // will send the closing_signed back to the remote peer upon return. This
6457                                                         // also implies there are no pending HTLCs left on the channel, so we can
6458                                                         // fully delete it from tracking (the channel monitor is still around to
6459                                                         // watch for old state broadcasts)!
6460                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)))
6461                                                 } else { (tx, None) }
6462                                         } else {
6463                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6464                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6465                                         }
6466                                 },
6467                                 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))
6468                         }
6469                 };
6470                 if let Some(broadcast_tx) = tx {
6471                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
6472                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6473                 }
6474                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6475                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6476                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6477                                 let peer_state = &mut *peer_state_lock;
6478                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6479                                         msg: update
6480                                 });
6481                         }
6482                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6483                         shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
6484                 }
6485                 mem::drop(per_peer_state);
6486                 if let Some(shutdown_result) = shutdown_result {
6487                         self.finish_close_channel(shutdown_result);
6488                 }
6489                 Ok(())
6490         }
6491
6492         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6493                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6494                 //determine the state of the payment based on our response/if we forward anything/the time
6495                 //we take to respond. We should take care to avoid allowing such an attack.
6496                 //
6497                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6498                 //us repeatedly garbled in different ways, and compare our error messages, which are
6499                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6500                 //but we should prevent it anyway.
6501
6502                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6503                 // closing a channel), so any changes are likely to be lost on restart!
6504
6505                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
6506                 let per_peer_state = self.per_peer_state.read().unwrap();
6507                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6508                         .ok_or_else(|| {
6509                                 debug_assert!(false);
6510                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6511                         })?;
6512                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6513                 let peer_state = &mut *peer_state_lock;
6514                 match peer_state.channel_by_id.entry(msg.channel_id) {
6515                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6516                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6517                                         let pending_forward_info = match decoded_hop_res {
6518                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6519                                                         self.construct_pending_htlc_status(msg, shared_secret, next_hop,
6520                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt),
6521                                                 Err(e) => PendingHTLCStatus::Fail(e)
6522                                         };
6523                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6524                                                 // If the update_add is completely bogus, the call will Err and we will close,
6525                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6526                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6527                                                 match pending_forward_info {
6528                                                         PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
6529                                                                 let reason = if (error_code & 0x1000) != 0 {
6530                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6531                                                                         HTLCFailReason::reason(real_code, error_data)
6532                                                                 } else {
6533                                                                         HTLCFailReason::from_failure_code(error_code)
6534                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6535                                                                 let msg = msgs::UpdateFailHTLC {
6536                                                                         channel_id: msg.channel_id,
6537                                                                         htlc_id: msg.htlc_id,
6538                                                                         reason
6539                                                                 };
6540                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6541                                                         },
6542                                                         _ => pending_forward_info
6543                                                 }
6544                                         };
6545                                         try_chan_phase_entry!(self, chan.update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &self.logger), chan_phase_entry);
6546                                 } else {
6547                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6548                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6549                                 }
6550                         },
6551                         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))
6552                 }
6553                 Ok(())
6554         }
6555
6556         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6557                 let funding_txo;
6558                 let (htlc_source, forwarded_htlc_value) = {
6559                         let per_peer_state = self.per_peer_state.read().unwrap();
6560                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6561                                 .ok_or_else(|| {
6562                                         debug_assert!(false);
6563                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6564                                 })?;
6565                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6566                         let peer_state = &mut *peer_state_lock;
6567                         match peer_state.channel_by_id.entry(msg.channel_id) {
6568                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6569                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6570                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6571                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6572                                                         log_trace!(self.logger,
6573                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6574                                                                 msg.channel_id);
6575                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6576                                                                 .or_insert_with(Vec::new)
6577                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6578                                                 }
6579                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6580                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6581                                                 // We do this instead in the `claim_funds_internal` by attaching a
6582                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6583                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6584                                                 // process the RAA as messages are processed from single peers serially.
6585                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6586                                                 res
6587                                         } else {
6588                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6589                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6590                                         }
6591                                 },
6592                                 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))
6593                         }
6594                 };
6595                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6596                 Ok(())
6597         }
6598
6599         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6600                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6601                 // closing a channel), so any changes are likely to be lost on restart!
6602                 let per_peer_state = self.per_peer_state.read().unwrap();
6603                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6604                         .ok_or_else(|| {
6605                                 debug_assert!(false);
6606                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6607                         })?;
6608                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6609                 let peer_state = &mut *peer_state_lock;
6610                 match peer_state.channel_by_id.entry(msg.channel_id) {
6611                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6612                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6613                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6614                                 } else {
6615                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6616                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6617                                 }
6618                         },
6619                         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))
6620                 }
6621                 Ok(())
6622         }
6623
6624         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6625                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6626                 // closing a channel), so any changes are likely to be lost on restart!
6627                 let per_peer_state = self.per_peer_state.read().unwrap();
6628                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6629                         .ok_or_else(|| {
6630                                 debug_assert!(false);
6631                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6632                         })?;
6633                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6634                 let peer_state = &mut *peer_state_lock;
6635                 match peer_state.channel_by_id.entry(msg.channel_id) {
6636                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6637                                 if (msg.failure_code & 0x8000) == 0 {
6638                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6639                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6640                                 }
6641                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6642                                         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);
6643                                 } else {
6644                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6645                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6646                                 }
6647                                 Ok(())
6648                         },
6649                         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))
6650                 }
6651         }
6652
6653         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6654                 let per_peer_state = self.per_peer_state.read().unwrap();
6655                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6656                         .ok_or_else(|| {
6657                                 debug_assert!(false);
6658                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6659                         })?;
6660                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6661                 let peer_state = &mut *peer_state_lock;
6662                 match peer_state.channel_by_id.entry(msg.channel_id) {
6663                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6664                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6665                                         let funding_txo = chan.context.get_funding_txo();
6666                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &self.logger), chan_phase_entry);
6667                                         if let Some(monitor_update) = monitor_update_opt {
6668                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6669                                                         peer_state, per_peer_state, chan);
6670                                         }
6671                                         Ok(())
6672                                 } else {
6673                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6674                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6675                                 }
6676                         },
6677                         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))
6678                 }
6679         }
6680
6681         #[inline]
6682         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6683                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6684                         let mut push_forward_event = false;
6685                         let mut new_intercept_events = VecDeque::new();
6686                         let mut failed_intercept_forwards = Vec::new();
6687                         if !pending_forwards.is_empty() {
6688                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6689                                         let scid = match forward_info.routing {
6690                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6691                                                 PendingHTLCRouting::Receive { .. } => 0,
6692                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6693                                         };
6694                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6695                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6696
6697                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6698                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6699                                         match forward_htlcs.entry(scid) {
6700                                                 hash_map::Entry::Occupied(mut entry) => {
6701                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6702                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6703                                                 },
6704                                                 hash_map::Entry::Vacant(entry) => {
6705                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6706                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6707                                                         {
6708                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6709                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6710                                                                 match pending_intercepts.entry(intercept_id) {
6711                                                                         hash_map::Entry::Vacant(entry) => {
6712                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6713                                                                                         requested_next_hop_scid: scid,
6714                                                                                         payment_hash: forward_info.payment_hash,
6715                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6716                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6717                                                                                         intercept_id
6718                                                                                 }, None));
6719                                                                                 entry.insert(PendingAddHTLCInfo {
6720                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6721                                                                         },
6722                                                                         hash_map::Entry::Occupied(_) => {
6723                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6724                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6725                                                                                         short_channel_id: prev_short_channel_id,
6726                                                                                         user_channel_id: Some(prev_user_channel_id),
6727                                                                                         outpoint: prev_funding_outpoint,
6728                                                                                         htlc_id: prev_htlc_id,
6729                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6730                                                                                         phantom_shared_secret: None,
6731                                                                                 });
6732
6733                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6734                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6735                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6736                                                                                 ));
6737                                                                         }
6738                                                                 }
6739                                                         } else {
6740                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6741                                                                 // payments are being processed.
6742                                                                 if forward_htlcs_empty {
6743                                                                         push_forward_event = true;
6744                                                                 }
6745                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6746                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6747                                                         }
6748                                                 }
6749                                         }
6750                                 }
6751                         }
6752
6753                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6754                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6755                         }
6756
6757                         if !new_intercept_events.is_empty() {
6758                                 let mut events = self.pending_events.lock().unwrap();
6759                                 events.append(&mut new_intercept_events);
6760                         }
6761                         if push_forward_event { self.push_pending_forwards_ev() }
6762                 }
6763         }
6764
6765         fn push_pending_forwards_ev(&self) {
6766                 let mut pending_events = self.pending_events.lock().unwrap();
6767                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6768                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6769                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6770                 ).count();
6771                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6772                 // events is done in batches and they are not removed until we're done processing each
6773                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6774                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6775                 // payments will need an additional forwarding event before being claimed to make them look
6776                 // real by taking more time.
6777                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6778                         pending_events.push_back((Event::PendingHTLCsForwardable {
6779                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6780                         }, None));
6781                 }
6782         }
6783
6784         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6785         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6786         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6787         /// the [`ChannelMonitorUpdate`] in question.
6788         fn raa_monitor_updates_held(&self,
6789                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6790                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6791         ) -> bool {
6792                 actions_blocking_raa_monitor_updates
6793                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6794                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6795                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6796                                 channel_funding_outpoint,
6797                                 counterparty_node_id,
6798                         })
6799                 })
6800         }
6801
6802         #[cfg(any(test, feature = "_test_utils"))]
6803         pub(crate) fn test_raa_monitor_updates_held(&self,
6804                 counterparty_node_id: PublicKey, channel_id: ChannelId
6805         ) -> bool {
6806                 let per_peer_state = self.per_peer_state.read().unwrap();
6807                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6808                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6809                         let peer_state = &mut *peer_state_lck;
6810
6811                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6812                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6813                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6814                         }
6815                 }
6816                 false
6817         }
6818
6819         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6820                 let htlcs_to_fail = {
6821                         let per_peer_state = self.per_peer_state.read().unwrap();
6822                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6823                                 .ok_or_else(|| {
6824                                         debug_assert!(false);
6825                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6826                                 }).map(|mtx| mtx.lock().unwrap())?;
6827                         let peer_state = &mut *peer_state_lock;
6828                         match peer_state.channel_by_id.entry(msg.channel_id) {
6829                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6830                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6831                                                 let funding_txo_opt = chan.context.get_funding_txo();
6832                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6833                                                         self.raa_monitor_updates_held(
6834                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6835                                                                 *counterparty_node_id)
6836                                                 } else { false };
6837                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
6838                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &self.logger, mon_update_blocked), chan_phase_entry);
6839                                                 if let Some(monitor_update) = monitor_update_opt {
6840                                                         let funding_txo = funding_txo_opt
6841                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
6842                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
6843                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6844                                                 }
6845                                                 htlcs_to_fail
6846                                         } else {
6847                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6848                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
6849                                         }
6850                                 },
6851                                 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))
6852                         }
6853                 };
6854                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6855                 Ok(())
6856         }
6857
6858         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6859                 let per_peer_state = self.per_peer_state.read().unwrap();
6860                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6861                         .ok_or_else(|| {
6862                                 debug_assert!(false);
6863                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6864                         })?;
6865                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6866                 let peer_state = &mut *peer_state_lock;
6867                 match peer_state.channel_by_id.entry(msg.channel_id) {
6868                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6869                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6870                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &self.logger), chan_phase_entry);
6871                                 } else {
6872                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6873                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
6874                                 }
6875                         },
6876                         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))
6877                 }
6878                 Ok(())
6879         }
6880
6881         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6882                 let per_peer_state = self.per_peer_state.read().unwrap();
6883                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6884                         .ok_or_else(|| {
6885                                 debug_assert!(false);
6886                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6887                         })?;
6888                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6889                 let peer_state = &mut *peer_state_lock;
6890                 match peer_state.channel_by_id.entry(msg.channel_id) {
6891                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6892                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6893                                         if !chan.context.is_usable() {
6894                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6895                                         }
6896
6897                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6898                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6899                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
6900                                                         msg, &self.default_configuration
6901                                                 ), chan_phase_entry),
6902                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6903                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6904                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
6905                                         });
6906                                 } else {
6907                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6908                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
6909                                 }
6910                         },
6911                         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))
6912                 }
6913                 Ok(())
6914         }
6915
6916         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
6917         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6918                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6919                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6920                         None => {
6921                                 // It's not a local channel
6922                                 return Ok(NotifyOption::SkipPersistNoEvents)
6923                         }
6924                 };
6925                 let per_peer_state = self.per_peer_state.read().unwrap();
6926                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6927                 if peer_state_mutex_opt.is_none() {
6928                         return Ok(NotifyOption::SkipPersistNoEvents)
6929                 }
6930                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6931                 let peer_state = &mut *peer_state_lock;
6932                 match peer_state.channel_by_id.entry(chan_id) {
6933                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6934                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6935                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
6936                                                 if chan.context.should_announce() {
6937                                                         // If the announcement is about a channel of ours which is public, some
6938                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
6939                                                         // a scary-looking error message and return Ok instead.
6940                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6941                                                 }
6942                                                 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));
6943                                         }
6944                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
6945                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
6946                                         if were_node_one == msg_from_node_one {
6947                                                 return Ok(NotifyOption::SkipPersistNoEvents);
6948                                         } else {
6949                                                 log_debug!(self.logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
6950                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
6951                                                 // If nothing changed after applying their update, we don't need to bother
6952                                                 // persisting.
6953                                                 if !did_change {
6954                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6955                                                 }
6956                                         }
6957                                 } else {
6958                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6959                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
6960                                 }
6961                         },
6962                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
6963                 }
6964                 Ok(NotifyOption::DoPersist)
6965         }
6966
6967         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
6968                 let htlc_forwards;
6969                 let need_lnd_workaround = {
6970                         let per_peer_state = self.per_peer_state.read().unwrap();
6971
6972                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6973                                 .ok_or_else(|| {
6974                                         debug_assert!(false);
6975                                         MsgHandleErrInternal::send_err_msg_no_close(
6976                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6977                                                 msg.channel_id
6978                                         )
6979                                 })?;
6980                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6981                         let peer_state = &mut *peer_state_lock;
6982                         match peer_state.channel_by_id.entry(msg.channel_id) {
6983                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6984                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6985                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
6986                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
6987                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
6988                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6989                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
6990                                                         msg, &self.logger, &self.node_signer, self.chain_hash,
6991                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
6992                                                 let mut channel_update = None;
6993                                                 if let Some(msg) = responses.shutdown_msg {
6994                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6995                                                                 node_id: counterparty_node_id.clone(),
6996                                                                 msg,
6997                                                         });
6998                                                 } else if chan.context.is_usable() {
6999                                                         // If the channel is in a usable state (ie the channel is not being shut
7000                                                         // down), send a unicast channel_update to our counterparty to make sure
7001                                                         // they have the latest channel parameters.
7002                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
7003                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
7004                                                                         node_id: chan.context.get_counterparty_node_id(),
7005                                                                         msg,
7006                                                                 });
7007                                                         }
7008                                                 }
7009                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7010                                                 htlc_forwards = self.handle_channel_resumption(
7011                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7012                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7013                                                 if let Some(upd) = channel_update {
7014                                                         peer_state.pending_msg_events.push(upd);
7015                                                 }
7016                                                 need_lnd_workaround
7017                                         } else {
7018                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7019                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7020                                         }
7021                                 },
7022                                 hash_map::Entry::Vacant(_) => {
7023                                         log_debug!(self.logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7024                                                 log_bytes!(msg.channel_id.0));
7025                                         // Unfortunately, lnd doesn't force close on errors
7026                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7027                                         // One of the few ways to get an lnd counterparty to force close is by
7028                                         // replicating what they do when restoring static channel backups (SCBs). They
7029                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7030                                         // invalid `your_last_per_commitment_secret`.
7031                                         //
7032                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7033                                         // can assume it's likely the channel closed from our point of view, but it
7034                                         // remains open on the counterparty's side. By sending this bogus
7035                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7036                                         // force close broadcasting their latest state. If the closing transaction from
7037                                         // our point of view remains unconfirmed, it'll enter a race with the
7038                                         // counterparty's to-be-broadcast latest commitment transaction.
7039                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7040                                                 node_id: *counterparty_node_id,
7041                                                 msg: msgs::ChannelReestablish {
7042                                                         channel_id: msg.channel_id,
7043                                                         next_local_commitment_number: 0,
7044                                                         next_remote_commitment_number: 0,
7045                                                         your_last_per_commitment_secret: [1u8; 32],
7046                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7047                                                         next_funding_txid: None,
7048                                                 },
7049                                         });
7050                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7051                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7052                                                         counterparty_node_id), msg.channel_id)
7053                                         )
7054                                 }
7055                         }
7056                 };
7057
7058                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7059                 if let Some(forwards) = htlc_forwards {
7060                         self.forward_htlcs(&mut [forwards][..]);
7061                         persist = NotifyOption::DoPersist;
7062                 }
7063
7064                 if let Some(channel_ready_msg) = need_lnd_workaround {
7065                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7066                 }
7067                 Ok(persist)
7068         }
7069
7070         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7071         fn process_pending_monitor_events(&self) -> bool {
7072                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7073
7074                 let mut failed_channels = Vec::new();
7075                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7076                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7077                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7078                         for monitor_event in monitor_events.drain(..) {
7079                                 match monitor_event {
7080                                         MonitorEvent::HTLCEvent(htlc_update) => {
7081                                                 if let Some(preimage) = htlc_update.payment_preimage {
7082                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7083                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
7084                                                 } else {
7085                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7086                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
7087                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7088                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7089                                                 }
7090                                         },
7091                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
7092                                                 let counterparty_node_id_opt = match counterparty_node_id {
7093                                                         Some(cp_id) => Some(cp_id),
7094                                                         None => {
7095                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7096                                                                 // monitor event, this and the id_to_peer map should be removed.
7097                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
7098                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
7099                                                         }
7100                                                 };
7101                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7102                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7103                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7104                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7105                                                                 let peer_state = &mut *peer_state_lock;
7106                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7107                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
7108                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7109                                                                                 failed_channels.push(chan.context.force_shutdown(false));
7110                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7111                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7112                                                                                                 msg: update
7113                                                                                         });
7114                                                                                 }
7115                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
7116                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7117                                                                                         node_id: chan.context.get_counterparty_node_id(),
7118                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7119                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7120                                                                                         },
7121                                                                                 });
7122                                                                         }
7123                                                                 }
7124                                                         }
7125                                                 }
7126                                         },
7127                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
7128                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
7129                                         },
7130                                 }
7131                         }
7132                 }
7133
7134                 for failure in failed_channels.drain(..) {
7135                         self.finish_close_channel(failure);
7136                 }
7137
7138                 has_pending_monitor_events
7139         }
7140
7141         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7142         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7143         /// update events as a separate process method here.
7144         #[cfg(fuzzing)]
7145         pub fn process_monitor_events(&self) {
7146                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7147                 self.process_pending_monitor_events();
7148         }
7149
7150         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7151         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7152         /// update was applied.
7153         fn check_free_holding_cells(&self) -> bool {
7154                 let mut has_monitor_update = false;
7155                 let mut failed_htlcs = Vec::new();
7156
7157                 // Walk our list of channels and find any that need to update. Note that when we do find an
7158                 // update, if it includes actions that must be taken afterwards, we have to drop the
7159                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7160                 // manage to go through all our peers without finding a single channel to update.
7161                 'peer_loop: loop {
7162                         let per_peer_state = self.per_peer_state.read().unwrap();
7163                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7164                                 'chan_loop: loop {
7165                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7166                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7167                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7168                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7169                                         ) {
7170                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7171                                                 let funding_txo = chan.context.get_funding_txo();
7172                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7173                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
7174                                                 if !holding_cell_failed_htlcs.is_empty() {
7175                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7176                                                 }
7177                                                 if let Some(monitor_update) = monitor_opt {
7178                                                         has_monitor_update = true;
7179
7180                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7181                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7182                                                         continue 'peer_loop;
7183                                                 }
7184                                         }
7185                                         break 'chan_loop;
7186                                 }
7187                         }
7188                         break 'peer_loop;
7189                 }
7190
7191                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7192                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7193                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7194                 }
7195
7196                 has_update
7197         }
7198
7199         /// Check whether any channels have finished removing all pending updates after a shutdown
7200         /// exchange and can now send a closing_signed.
7201         /// Returns whether any closing_signed messages were generated.
7202         fn maybe_generate_initial_closing_signed(&self) -> bool {
7203                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7204                 let mut has_update = false;
7205                 let mut shutdown_results = Vec::new();
7206                 {
7207                         let per_peer_state = self.per_peer_state.read().unwrap();
7208
7209                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7210                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7211                                 let peer_state = &mut *peer_state_lock;
7212                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7213                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7214                                         match phase {
7215                                                 ChannelPhase::Funded(chan) => {
7216                                                         let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
7217                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
7218                                                                 Ok((msg_opt, tx_opt)) => {
7219                                                                         if let Some(msg) = msg_opt {
7220                                                                                 has_update = true;
7221                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7222                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7223                                                                                 });
7224                                                                         }
7225                                                                         if let Some(tx) = tx_opt {
7226                                                                                 // We're done with this channel. We got a closing_signed and sent back
7227                                                                                 // a closing_signed with a closing transaction to broadcast.
7228                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7229                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7230                                                                                                 msg: update
7231                                                                                         });
7232                                                                                 }
7233
7234                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
7235
7236                                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
7237                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7238                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7239                                                                                 shutdown_results.push((None, Vec::new(), unbroadcasted_batch_funding_txid));
7240                                                                                 false
7241                                                                         } else { true }
7242                                                                 },
7243                                                                 Err(e) => {
7244                                                                         has_update = true;
7245                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7246                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7247                                                                         !close_channel
7248                                                                 }
7249                                                         }
7250                                                 },
7251                                                 _ => true, // Retain unfunded channels if present.
7252                                         }
7253                                 });
7254                         }
7255                 }
7256
7257                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7258                         let _ = handle_error!(self, err, counterparty_node_id);
7259                 }
7260
7261                 for shutdown_result in shutdown_results.drain(..) {
7262                         self.finish_close_channel(shutdown_result);
7263                 }
7264
7265                 has_update
7266         }
7267
7268         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7269         /// pushing the channel monitor update (if any) to the background events queue and removing the
7270         /// Channel object.
7271         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7272                 for mut failure in failed_channels.drain(..) {
7273                         // Either a commitment transactions has been confirmed on-chain or
7274                         // Channel::block_disconnected detected that the funding transaction has been
7275                         // reorganized out of the main chain.
7276                         // We cannot broadcast our latest local state via monitor update (as
7277                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7278                         // so we track the update internally and handle it when the user next calls
7279                         // timer_tick_occurred, guaranteeing we're running normally.
7280                         if let Some((counterparty_node_id, funding_txo, update)) = failure.0.take() {
7281                                 assert_eq!(update.updates.len(), 1);
7282                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7283                                         assert!(should_broadcast);
7284                                 } else { unreachable!(); }
7285                                 self.pending_background_events.lock().unwrap().push(
7286                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7287                                                 counterparty_node_id, funding_txo, update
7288                                         });
7289                         }
7290                         self.finish_close_channel(failure);
7291                 }
7292         }
7293
7294         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7295         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7296         /// not have an expiration unless otherwise set on the builder.
7297         ///
7298         /// Uses a one-hop [`BlindedPath`] for the offer with [`ChannelManager::get_our_node_id`] as the
7299         /// introduction node and a derived signing pubkey for recipient privacy. As such, currently,
7300         /// the node must be announced. Otherwise, there is no way to find a path to the introduction
7301         /// node in order to send the [`InvoiceRequest`].
7302         ///
7303         /// [`Offer`]: crate::offers::offer::Offer
7304         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7305         pub fn create_offer_builder(
7306                 &self, description: String
7307         ) -> OfferBuilder<DerivedMetadata, secp256k1::All> {
7308                 let node_id = self.get_our_node_id();
7309                 let expanded_key = &self.inbound_payment_key;
7310                 let entropy = &*self.entropy_source;
7311                 let secp_ctx = &self.secp_ctx;
7312                 let path = self.create_one_hop_blinded_path();
7313
7314                 OfferBuilder::deriving_signing_pubkey(description, node_id, expanded_key, entropy, secp_ctx)
7315                         .chain_hash(self.chain_hash)
7316                         .path(path)
7317         }
7318
7319         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7320         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7321         ///
7322         /// The builder will have the provided expiration set. Any changes to the expiration on the
7323         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7324         /// block time minus two hours is used for the current time when determining if the refund has
7325         /// expired.
7326         ///
7327         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund. To
7328         /// revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the invoice.
7329         ///
7330         /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
7331         /// the introduction node and a derived payer id for sender privacy. As such, currently, the
7332         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7333         /// in order to send the [`Bolt12Invoice`].
7334         ///
7335         /// [`Refund`]: crate::offers::refund::Refund
7336         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7337         pub fn create_refund_builder(
7338                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7339                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7340         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7341                 let node_id = self.get_our_node_id();
7342                 let expanded_key = &self.inbound_payment_key;
7343                 let entropy = &*self.entropy_source;
7344                 let secp_ctx = &self.secp_ctx;
7345                 let path = self.create_one_hop_blinded_path();
7346
7347                 let builder = RefundBuilder::deriving_payer_id(
7348                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7349                 )?
7350                         .chain_hash(self.chain_hash)
7351                         .absolute_expiry(absolute_expiry)
7352                         .path(path);
7353
7354                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7355                 self.pending_outbound_payments
7356                         .add_new_awaiting_invoice(
7357                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7358                         )
7359                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7360
7361                 Ok(builder)
7362         }
7363
7364         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7365         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7366         /// [`Bolt12Invoice`] once it is received.
7367         ///
7368         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7369         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7370         /// The optional parameters are used in the builder, if `Some`:
7371         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7372         ///   [`Offer::expects_quantity`] is `true`.
7373         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7374         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7375         ///
7376         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7377         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7378         /// been sent. To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving
7379         /// the invoice.
7380         ///
7381         /// Errors if a duplicate `payment_id` is provided given the caveats in the aforementioned link.
7382         ///
7383         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7384         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7385         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7386         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7387         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7388         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7389         pub fn pay_for_offer(
7390                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7391                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7392                 max_total_routing_fee_msat: Option<u64>
7393         ) -> Result<(), Bolt12SemanticError> {
7394                 let expanded_key = &self.inbound_payment_key;
7395                 let entropy = &*self.entropy_source;
7396                 let secp_ctx = &self.secp_ctx;
7397
7398                 let builder = offer
7399                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7400                         .chain_hash(self.chain_hash)?;
7401                 let builder = match quantity {
7402                         None => builder,
7403                         Some(quantity) => builder.quantity(quantity)?,
7404                 };
7405                 let builder = match amount_msats {
7406                         None => builder,
7407                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7408                 };
7409                 let builder = match payer_note {
7410                         None => builder,
7411                         Some(payer_note) => builder.payer_note(payer_note),
7412                 };
7413
7414                 let invoice_request = builder.build_and_sign()?;
7415                 let reply_path = self.create_one_hop_blinded_path();
7416
7417                 let expiration = StaleExpiration::TimerTicks(1);
7418                 self.pending_outbound_payments
7419                         .add_new_awaiting_invoice(
7420                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7421                         )
7422                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7423
7424                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7425                 if offer.paths().is_empty() {
7426                         let message = PendingOnionMessage {
7427                                 contents: OffersMessage::InvoiceRequest(invoice_request),
7428                                 destination: Destination::Node(offer.signing_pubkey()),
7429                                 reply_path: Some(reply_path),
7430                         };
7431                         pending_offers_messages.push(message);
7432                 } else {
7433                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7434                         // Using only one path could result in a failure if the path no longer exists. But only
7435                         // one invoice for a given payment id will be paid, even if more than one is received.
7436                         const REQUEST_LIMIT: usize = 10;
7437                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7438                                 let message = PendingOnionMessage {
7439                                         contents: OffersMessage::InvoiceRequest(invoice_request.clone()),
7440                                         destination: Destination::BlindedPath(path.clone()),
7441                                         reply_path: Some(reply_path.clone()),
7442                                 };
7443                                 pending_offers_messages.push(message);
7444                         }
7445                 }
7446
7447                 Ok(())
7448         }
7449
7450         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7451         /// message.
7452         ///
7453         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7454         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7455         /// [`PaymentPreimage`].
7456         ///
7457         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7458         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7459                 let expanded_key = &self.inbound_payment_key;
7460                 let entropy = &*self.entropy_source;
7461                 let secp_ctx = &self.secp_ctx;
7462
7463                 let amount_msats = refund.amount_msats();
7464                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7465
7466                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7467                         Ok((payment_hash, payment_secret)) => {
7468                                 let payment_paths = vec![
7469                                         self.create_one_hop_blinded_payment_path(payment_secret),
7470                                 ];
7471                                 #[cfg(not(feature = "no-std"))]
7472                                 let builder = refund.respond_using_derived_keys(
7473                                         payment_paths, payment_hash, expanded_key, entropy
7474                                 )?;
7475                                 #[cfg(feature = "no-std")]
7476                                 let created_at = Duration::from_secs(
7477                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7478                                 );
7479                                 #[cfg(feature = "no-std")]
7480                                 let builder = refund.respond_using_derived_keys_no_std(
7481                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7482                                 )?;
7483                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7484                                 let reply_path = self.create_one_hop_blinded_path();
7485
7486                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7487                                 if refund.paths().is_empty() {
7488                                         let message = PendingOnionMessage {
7489                                                 contents: OffersMessage::Invoice(invoice),
7490                                                 destination: Destination::Node(refund.payer_id()),
7491                                                 reply_path: Some(reply_path),
7492                                         };
7493                                         pending_offers_messages.push(message);
7494                                 } else {
7495                                         for path in refund.paths() {
7496                                                 let message = PendingOnionMessage {
7497                                                         contents: OffersMessage::Invoice(invoice.clone()),
7498                                                         destination: Destination::BlindedPath(path.clone()),
7499                                                         reply_path: Some(reply_path.clone()),
7500                                                 };
7501                                                 pending_offers_messages.push(message);
7502                                         }
7503                                 }
7504
7505                                 Ok(())
7506                         },
7507                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7508                 }
7509         }
7510
7511         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7512         /// to pay us.
7513         ///
7514         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7515         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7516         ///
7517         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7518         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7519         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7520         /// passed directly to [`claim_funds`].
7521         ///
7522         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7523         ///
7524         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7525         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7526         ///
7527         /// # Note
7528         ///
7529         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7530         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7531         ///
7532         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7533         ///
7534         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7535         /// on versions of LDK prior to 0.0.114.
7536         ///
7537         /// [`claim_funds`]: Self::claim_funds
7538         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7539         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7540         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7541         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7542         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7543         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7544                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7545                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7546                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7547                         min_final_cltv_expiry_delta)
7548         }
7549
7550         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7551         /// stored external to LDK.
7552         ///
7553         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7554         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7555         /// the `min_value_msat` provided here, if one is provided.
7556         ///
7557         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7558         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7559         /// payments.
7560         ///
7561         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7562         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7563         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7564         /// sender "proof-of-payment" unless they have paid the required amount.
7565         ///
7566         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7567         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7568         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7569         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7570         /// invoices when no timeout is set.
7571         ///
7572         /// Note that we use block header time to time-out pending inbound payments (with some margin
7573         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7574         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7575         /// If you need exact expiry semantics, you should enforce them upon receipt of
7576         /// [`PaymentClaimable`].
7577         ///
7578         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7579         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7580         ///
7581         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7582         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7583         ///
7584         /// # Note
7585         ///
7586         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7587         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7588         ///
7589         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7590         ///
7591         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7592         /// on versions of LDK prior to 0.0.114.
7593         ///
7594         /// [`create_inbound_payment`]: Self::create_inbound_payment
7595         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7596         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7597                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7598                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7599                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7600                         min_final_cltv_expiry)
7601         }
7602
7603         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7604         /// previously returned from [`create_inbound_payment`].
7605         ///
7606         /// [`create_inbound_payment`]: Self::create_inbound_payment
7607         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7608                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7609         }
7610
7611         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7612         /// node.
7613         fn create_one_hop_blinded_path(&self) -> BlindedPath {
7614                 let entropy_source = self.entropy_source.deref();
7615                 let secp_ctx = &self.secp_ctx;
7616                 BlindedPath::one_hop_for_message(self.get_our_node_id(), entropy_source, secp_ctx).unwrap()
7617         }
7618
7619         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7620         /// node.
7621         fn create_one_hop_blinded_payment_path(
7622                 &self, payment_secret: PaymentSecret
7623         ) -> (BlindedPayInfo, BlindedPath) {
7624                 let entropy_source = self.entropy_source.deref();
7625                 let secp_ctx = &self.secp_ctx;
7626
7627                 let payee_node_id = self.get_our_node_id();
7628                 let max_cltv_expiry = self.best_block.read().unwrap().height() + LATENCY_GRACE_PERIOD_BLOCKS;
7629                 let payee_tlvs = ReceiveTlvs {
7630                         payment_secret,
7631                         payment_constraints: PaymentConstraints {
7632                                 max_cltv_expiry,
7633                                 htlc_minimum_msat: 1,
7634                         },
7635                 };
7636                 // TODO: Err for overflow?
7637                 BlindedPath::one_hop_for_payment(
7638                         payee_node_id, payee_tlvs, entropy_source, secp_ctx
7639                 ).unwrap()
7640         }
7641
7642         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
7643         /// are used when constructing the phantom invoice's route hints.
7644         ///
7645         /// [phantom node payments]: crate::sign::PhantomKeysManager
7646         pub fn get_phantom_scid(&self) -> u64 {
7647                 let best_block_height = self.best_block.read().unwrap().height();
7648                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7649                 loop {
7650                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7651                         // Ensure the generated scid doesn't conflict with a real channel.
7652                         match short_to_chan_info.get(&scid_candidate) {
7653                                 Some(_) => continue,
7654                                 None => return scid_candidate
7655                         }
7656                 }
7657         }
7658
7659         /// Gets route hints for use in receiving [phantom node payments].
7660         ///
7661         /// [phantom node payments]: crate::sign::PhantomKeysManager
7662         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
7663                 PhantomRouteHints {
7664                         channels: self.list_usable_channels(),
7665                         phantom_scid: self.get_phantom_scid(),
7666                         real_node_pubkey: self.get_our_node_id(),
7667                 }
7668         }
7669
7670         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
7671         /// used when constructing the route hints for HTLCs intended to be intercepted. See
7672         /// [`ChannelManager::forward_intercepted_htlc`].
7673         ///
7674         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
7675         /// times to get a unique scid.
7676         pub fn get_intercept_scid(&self) -> u64 {
7677                 let best_block_height = self.best_block.read().unwrap().height();
7678                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7679                 loop {
7680                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7681                         // Ensure the generated scid doesn't conflict with a real channel.
7682                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
7683                         return scid_candidate
7684                 }
7685         }
7686
7687         /// Gets inflight HTLC information by processing pending outbound payments that are in
7688         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
7689         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
7690                 let mut inflight_htlcs = InFlightHtlcs::new();
7691
7692                 let per_peer_state = self.per_peer_state.read().unwrap();
7693                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7694                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7695                         let peer_state = &mut *peer_state_lock;
7696                         for chan in peer_state.channel_by_id.values().filter_map(
7697                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7698                         ) {
7699                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
7700                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
7701                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
7702                                         }
7703                                 }
7704                         }
7705                 }
7706
7707                 inflight_htlcs
7708         }
7709
7710         #[cfg(any(test, feature = "_test_utils"))]
7711         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
7712                 let events = core::cell::RefCell::new(Vec::new());
7713                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
7714                 self.process_pending_events(&event_handler);
7715                 events.into_inner()
7716         }
7717
7718         #[cfg(feature = "_test_utils")]
7719         pub fn push_pending_event(&self, event: events::Event) {
7720                 let mut events = self.pending_events.lock().unwrap();
7721                 events.push_back((event, None));
7722         }
7723
7724         #[cfg(test)]
7725         pub fn pop_pending_event(&self) -> Option<events::Event> {
7726                 let mut events = self.pending_events.lock().unwrap();
7727                 events.pop_front().map(|(e, _)| e)
7728         }
7729
7730         #[cfg(test)]
7731         pub fn has_pending_payments(&self) -> bool {
7732                 self.pending_outbound_payments.has_pending_payments()
7733         }
7734
7735         #[cfg(test)]
7736         pub fn clear_pending_payments(&self) {
7737                 self.pending_outbound_payments.clear_pending_payments()
7738         }
7739
7740         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
7741         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
7742         /// operation. It will double-check that nothing *else* is also blocking the same channel from
7743         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
7744         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
7745                 loop {
7746                         let per_peer_state = self.per_peer_state.read().unwrap();
7747                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7748                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7749                                 let peer_state = &mut *peer_state_lck;
7750
7751                                 if let Some(blocker) = completed_blocker.take() {
7752                                         // Only do this on the first iteration of the loop.
7753                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
7754                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
7755                                         {
7756                                                 blockers.retain(|iter| iter != &blocker);
7757                                         }
7758                                 }
7759
7760                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7761                                         channel_funding_outpoint, counterparty_node_id) {
7762                                         // Check that, while holding the peer lock, we don't have anything else
7763                                         // blocking monitor updates for this channel. If we do, release the monitor
7764                                         // update(s) when those blockers complete.
7765                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
7766                                                 &channel_funding_outpoint.to_channel_id());
7767                                         break;
7768                                 }
7769
7770                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
7771                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7772                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
7773                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
7774                                                         log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
7775                                                                 channel_funding_outpoint.to_channel_id());
7776                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
7777                                                                 peer_state_lck, peer_state, per_peer_state, chan);
7778                                                         if further_update_exists {
7779                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
7780                                                                 // top of the loop.
7781                                                                 continue;
7782                                                         }
7783                                                 } else {
7784                                                         log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
7785                                                                 channel_funding_outpoint.to_channel_id());
7786                                                 }
7787                                         }
7788                                 }
7789                         } else {
7790                                 log_debug!(self.logger,
7791                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
7792                                         log_pubkey!(counterparty_node_id));
7793                         }
7794                         break;
7795                 }
7796         }
7797
7798         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
7799                 for action in actions {
7800                         match action {
7801                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7802                                         channel_funding_outpoint, counterparty_node_id
7803                                 } => {
7804                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
7805                                 }
7806                         }
7807                 }
7808         }
7809
7810         /// Processes any events asynchronously in the order they were generated since the last call
7811         /// using the given event handler.
7812         ///
7813         /// See the trait-level documentation of [`EventsProvider`] for requirements.
7814         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
7815                 &self, handler: H
7816         ) {
7817                 let mut ev;
7818                 process_events_body!(self, ev, { handler(ev).await });
7819         }
7820 }
7821
7822 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>
7823 where
7824         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7825         T::Target: BroadcasterInterface,
7826         ES::Target: EntropySource,
7827         NS::Target: NodeSigner,
7828         SP::Target: SignerProvider,
7829         F::Target: FeeEstimator,
7830         R::Target: Router,
7831         L::Target: Logger,
7832 {
7833         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
7834         /// The returned array will contain `MessageSendEvent`s for different peers if
7835         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
7836         /// is always placed next to each other.
7837         ///
7838         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
7839         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
7840         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
7841         /// will randomly be placed first or last in the returned array.
7842         ///
7843         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
7844         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
7845         /// the `MessageSendEvent`s to the specific peer they were generated under.
7846         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
7847                 let events = RefCell::new(Vec::new());
7848                 PersistenceNotifierGuard::optionally_notify(self, || {
7849                         let mut result = NotifyOption::SkipPersistNoEvents;
7850
7851                         // TODO: This behavior should be documented. It's unintuitive that we query
7852                         // ChannelMonitors when clearing other events.
7853                         if self.process_pending_monitor_events() {
7854                                 result = NotifyOption::DoPersist;
7855                         }
7856
7857                         if self.check_free_holding_cells() {
7858                                 result = NotifyOption::DoPersist;
7859                         }
7860                         if self.maybe_generate_initial_closing_signed() {
7861                                 result = NotifyOption::DoPersist;
7862                         }
7863
7864                         let mut pending_events = Vec::new();
7865                         let per_peer_state = self.per_peer_state.read().unwrap();
7866                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7867                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7868                                 let peer_state = &mut *peer_state_lock;
7869                                 if peer_state.pending_msg_events.len() > 0 {
7870                                         pending_events.append(&mut peer_state.pending_msg_events);
7871                                 }
7872                         }
7873
7874                         if !pending_events.is_empty() {
7875                                 events.replace(pending_events);
7876                         }
7877
7878                         result
7879                 });
7880                 events.into_inner()
7881         }
7882 }
7883
7884 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>
7885 where
7886         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7887         T::Target: BroadcasterInterface,
7888         ES::Target: EntropySource,
7889         NS::Target: NodeSigner,
7890         SP::Target: SignerProvider,
7891         F::Target: FeeEstimator,
7892         R::Target: Router,
7893         L::Target: Logger,
7894 {
7895         /// Processes events that must be periodically handled.
7896         ///
7897         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
7898         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
7899         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
7900                 let mut ev;
7901                 process_events_body!(self, ev, handler.handle_event(ev));
7902         }
7903 }
7904
7905 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>
7906 where
7907         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7908         T::Target: BroadcasterInterface,
7909         ES::Target: EntropySource,
7910         NS::Target: NodeSigner,
7911         SP::Target: SignerProvider,
7912         F::Target: FeeEstimator,
7913         R::Target: Router,
7914         L::Target: Logger,
7915 {
7916         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7917                 {
7918                         let best_block = self.best_block.read().unwrap();
7919                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
7920                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
7921                         assert_eq!(best_block.height(), height - 1,
7922                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
7923                 }
7924
7925                 self.transactions_confirmed(header, txdata, height);
7926                 self.best_block_updated(header, height);
7927         }
7928
7929         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
7930                 let _persistence_guard =
7931                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7932                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7933                 let new_height = height - 1;
7934                 {
7935                         let mut best_block = self.best_block.write().unwrap();
7936                         assert_eq!(best_block.block_hash(), header.block_hash(),
7937                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
7938                         assert_eq!(best_block.height(), height,
7939                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
7940                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
7941                 }
7942
7943                 self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger));
7944         }
7945 }
7946
7947 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>
7948 where
7949         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7950         T::Target: BroadcasterInterface,
7951         ES::Target: EntropySource,
7952         NS::Target: NodeSigner,
7953         SP::Target: SignerProvider,
7954         F::Target: FeeEstimator,
7955         R::Target: Router,
7956         L::Target: Logger,
7957 {
7958         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7959                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7960                 // during initialization prior to the chain_monitor being fully configured in some cases.
7961                 // See the docs for `ChannelManagerReadArgs` for more.
7962
7963                 let block_hash = header.block_hash();
7964                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
7965
7966                 let _persistence_guard =
7967                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7968                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7969                 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger)
7970                         .map(|(a, b)| (a, Vec::new(), b)));
7971
7972                 let last_best_block_height = self.best_block.read().unwrap().height();
7973                 if height < last_best_block_height {
7974                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
7975                         self.do_chain_event(Some(last_best_block_height), |channel| channel.best_block_updated(last_best_block_height, timestamp as u32, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger));
7976                 }
7977         }
7978
7979         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
7980                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7981                 // during initialization prior to the chain_monitor being fully configured in some cases.
7982                 // See the docs for `ChannelManagerReadArgs` for more.
7983
7984                 let block_hash = header.block_hash();
7985                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
7986
7987                 let _persistence_guard =
7988                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7989                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7990                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
7991
7992                 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger));
7993
7994                 macro_rules! max_time {
7995                         ($timestamp: expr) => {
7996                                 loop {
7997                                         // Update $timestamp to be the max of its current value and the block
7998                                         // timestamp. This should keep us close to the current time without relying on
7999                                         // having an explicit local time source.
8000                                         // Just in case we end up in a race, we loop until we either successfully
8001                                         // update $timestamp or decide we don't need to.
8002                                         let old_serial = $timestamp.load(Ordering::Acquire);
8003                                         if old_serial >= header.time as usize { break; }
8004                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8005                                                 break;
8006                                         }
8007                                 }
8008                         }
8009                 }
8010                 max_time!(self.highest_seen_timestamp);
8011                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8012                 payment_secrets.retain(|_, inbound_payment| {
8013                         inbound_payment.expiry_time > header.time as u64
8014                 });
8015         }
8016
8017         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
8018                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8019                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8020                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8021                         let peer_state = &mut *peer_state_lock;
8022                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8023                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
8024                                         res.push((funding_txo.txid, Some(block_hash)));
8025                                 }
8026                         }
8027                 }
8028                 res
8029         }
8030
8031         fn transaction_unconfirmed(&self, txid: &Txid) {
8032                 let _persistence_guard =
8033                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8034                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8035                 self.do_chain_event(None, |channel| {
8036                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8037                                 if funding_txo.txid == *txid {
8038                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
8039                                 } else { Ok((None, Vec::new(), None)) }
8040                         } else { Ok((None, Vec::new(), None)) }
8041                 });
8042         }
8043 }
8044
8045 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>
8046 where
8047         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8048         T::Target: BroadcasterInterface,
8049         ES::Target: EntropySource,
8050         NS::Target: NodeSigner,
8051         SP::Target: SignerProvider,
8052         F::Target: FeeEstimator,
8053         R::Target: Router,
8054         L::Target: Logger,
8055 {
8056         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8057         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8058         /// the function.
8059         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8060                         (&self, height_opt: Option<u32>, f: FN) {
8061                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8062                 // during initialization prior to the chain_monitor being fully configured in some cases.
8063                 // See the docs for `ChannelManagerReadArgs` for more.
8064
8065                 let mut failed_channels = Vec::new();
8066                 let mut timed_out_htlcs = Vec::new();
8067                 {
8068                         let per_peer_state = self.per_peer_state.read().unwrap();
8069                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8070                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8071                                 let peer_state = &mut *peer_state_lock;
8072                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8073                                 peer_state.channel_by_id.retain(|_, phase| {
8074                                         match phase {
8075                                                 // Retain unfunded channels.
8076                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8077                                                 ChannelPhase::Funded(channel) => {
8078                                                         let res = f(channel);
8079                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8080                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8081                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8082                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8083                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8084                                                                 }
8085                                                                 if let Some(channel_ready) = channel_ready_opt {
8086                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8087                                                                         if channel.context.is_usable() {
8088                                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8089                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8090                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8091                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8092                                                                                                 msg,
8093                                                                                         });
8094                                                                                 }
8095                                                                         } else {
8096                                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8097                                                                         }
8098                                                                 }
8099
8100                                                                 {
8101                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8102                                                                         emit_channel_ready_event!(pending_events, channel);
8103                                                                 }
8104
8105                                                                 if let Some(announcement_sigs) = announcement_sigs {
8106                                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8107                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8108                                                                                 node_id: channel.context.get_counterparty_node_id(),
8109                                                                                 msg: announcement_sigs,
8110                                                                         });
8111                                                                         if let Some(height) = height_opt {
8112                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8113                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8114                                                                                                 msg: announcement,
8115                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8116                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8117                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8118                                                                                         });
8119                                                                                 }
8120                                                                         }
8121                                                                 }
8122                                                                 if channel.is_our_channel_ready() {
8123                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8124                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8125                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8126                                                                                 // can relay using the real SCID at relay-time (i.e.
8127                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8128                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8129                                                                                 // is always consistent.
8130                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8131                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8132                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8133                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8134                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8135                                                                         }
8136                                                                 }
8137                                                         } else if let Err(reason) = res {
8138                                                                 update_maps_on_chan_removal!(self, &channel.context);
8139                                                                 // It looks like our counterparty went on-chain or funding transaction was
8140                                                                 // reorged out of the main chain. Close the channel.
8141                                                                 failed_channels.push(channel.context.force_shutdown(true));
8142                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8143                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
8144                                                                                 msg: update
8145                                                                         });
8146                                                                 }
8147                                                                 let reason_message = format!("{}", reason);
8148                                                                 self.issue_channel_close_events(&channel.context, reason);
8149                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8150                                                                         node_id: channel.context.get_counterparty_node_id(),
8151                                                                         action: msgs::ErrorAction::DisconnectPeer {
8152                                                                                 msg: Some(msgs::ErrorMessage {
8153                                                                                         channel_id: channel.context.channel_id(),
8154                                                                                         data: reason_message,
8155                                                                                 })
8156                                                                         },
8157                                                                 });
8158                                                                 return false;
8159                                                         }
8160                                                         true
8161                                                 }
8162                                         }
8163                                 });
8164                         }
8165                 }
8166
8167                 if let Some(height) = height_opt {
8168                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8169                                 payment.htlcs.retain(|htlc| {
8170                                         // If height is approaching the number of blocks we think it takes us to get
8171                                         // our commitment transaction confirmed before the HTLC expires, plus the
8172                                         // number of blocks we generally consider it to take to do a commitment update,
8173                                         // just give up on it and fail the HTLC.
8174                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8175                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8176                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8177
8178                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8179                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8180                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8181                                                 false
8182                                         } else { true }
8183                                 });
8184                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8185                         });
8186
8187                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8188                         intercepted_htlcs.retain(|_, htlc| {
8189                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8190                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8191                                                 short_channel_id: htlc.prev_short_channel_id,
8192                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8193                                                 htlc_id: htlc.prev_htlc_id,
8194                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8195                                                 phantom_shared_secret: None,
8196                                                 outpoint: htlc.prev_funding_outpoint,
8197                                         });
8198
8199                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8200                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8201                                                 _ => unreachable!(),
8202                                         };
8203                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8204                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8205                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8206                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8207                                         false
8208                                 } else { true }
8209                         });
8210                 }
8211
8212                 self.handle_init_event_channel_failures(failed_channels);
8213
8214                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8215                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8216                 }
8217         }
8218
8219         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8220         /// may have events that need processing.
8221         ///
8222         /// In order to check if this [`ChannelManager`] needs persisting, call
8223         /// [`Self::get_and_clear_needs_persistence`].
8224         ///
8225         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8226         /// [`ChannelManager`] and should instead register actions to be taken later.
8227         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8228                 self.event_persist_notifier.get_future()
8229         }
8230
8231         /// Returns true if this [`ChannelManager`] needs to be persisted.
8232         pub fn get_and_clear_needs_persistence(&self) -> bool {
8233                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8234         }
8235
8236         #[cfg(any(test, feature = "_test_utils"))]
8237         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8238                 self.event_persist_notifier.notify_pending()
8239         }
8240
8241         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8242         /// [`chain::Confirm`] interfaces.
8243         pub fn current_best_block(&self) -> BestBlock {
8244                 self.best_block.read().unwrap().clone()
8245         }
8246
8247         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
8248         /// [`ChannelManager`].
8249         pub fn node_features(&self) -> NodeFeatures {
8250                 provided_node_features(&self.default_configuration)
8251         }
8252
8253         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
8254         /// [`ChannelManager`].
8255         ///
8256         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8257         /// or not. Thus, this method is not public.
8258         #[cfg(any(feature = "_test_utils", test))]
8259         pub fn invoice_features(&self) -> Bolt11InvoiceFeatures {
8260                 provided_invoice_features(&self.default_configuration)
8261         }
8262
8263         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
8264         /// [`ChannelManager`].
8265         pub fn channel_features(&self) -> ChannelFeatures {
8266                 provided_channel_features(&self.default_configuration)
8267         }
8268
8269         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
8270         /// [`ChannelManager`].
8271         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8272                 provided_channel_type_features(&self.default_configuration)
8273         }
8274
8275         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
8276         /// [`ChannelManager`].
8277         pub fn init_features(&self) -> InitFeatures {
8278                 provided_init_features(&self.default_configuration)
8279         }
8280 }
8281
8282 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8283         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8284 where
8285         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8286         T::Target: BroadcasterInterface,
8287         ES::Target: EntropySource,
8288         NS::Target: NodeSigner,
8289         SP::Target: SignerProvider,
8290         F::Target: FeeEstimator,
8291         R::Target: Router,
8292         L::Target: Logger,
8293 {
8294         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8295                 // Note that we never need to persist the updated ChannelManager for an inbound
8296                 // open_channel message - pre-funded channels are never written so there should be no
8297                 // change to the contents.
8298                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8299                         let res = self.internal_open_channel(counterparty_node_id, msg);
8300                         let persist = match &res {
8301                                 Err(e) if e.closes_channel() => {
8302                                         debug_assert!(false, "We shouldn't close a new channel");
8303                                         NotifyOption::DoPersist
8304                                 },
8305                                 _ => NotifyOption::SkipPersistHandleEvents,
8306                         };
8307                         let _ = handle_error!(self, res, *counterparty_node_id);
8308                         persist
8309                 });
8310         }
8311
8312         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8313                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8314                         "Dual-funded channels not supported".to_owned(),
8315                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8316         }
8317
8318         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8319                 // Note that we never need to persist the updated ChannelManager for an inbound
8320                 // accept_channel message - pre-funded channels are never written so there should be no
8321                 // change to the contents.
8322                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8323                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8324                         NotifyOption::SkipPersistHandleEvents
8325                 });
8326         }
8327
8328         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8329                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8330                         "Dual-funded channels not supported".to_owned(),
8331                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8332         }
8333
8334         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8335                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8336                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8337         }
8338
8339         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8340                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8341                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8342         }
8343
8344         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8345                 // Note that we never need to persist the updated ChannelManager for an inbound
8346                 // channel_ready message - while the channel's state will change, any channel_ready message
8347                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8348                 // will not force-close the channel on startup.
8349                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8350                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8351                         let persist = match &res {
8352                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8353                                 _ => NotifyOption::SkipPersistHandleEvents,
8354                         };
8355                         let _ = handle_error!(self, res, *counterparty_node_id);
8356                         persist
8357                 });
8358         }
8359
8360         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8361                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8362                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8363         }
8364
8365         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8366                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8367                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8368         }
8369
8370         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8371                 // Note that we never need to persist the updated ChannelManager for an inbound
8372                 // update_add_htlc message - the message itself doesn't change our channel state only the
8373                 // `commitment_signed` message afterwards will.
8374                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8375                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8376                         let persist = match &res {
8377                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8378                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8379                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8380                         };
8381                         let _ = handle_error!(self, res, *counterparty_node_id);
8382                         persist
8383                 });
8384         }
8385
8386         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8387                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8388                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8389         }
8390
8391         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8392                 // Note that we never need to persist the updated ChannelManager for an inbound
8393                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8394                 // `commitment_signed` message afterwards will.
8395                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8396                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8397                         let persist = match &res {
8398                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8399                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8400                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8401                         };
8402                         let _ = handle_error!(self, res, *counterparty_node_id);
8403                         persist
8404                 });
8405         }
8406
8407         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8408                 // Note that we never need to persist the updated ChannelManager for an inbound
8409                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8410                 // only the `commitment_signed` message afterwards will.
8411                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8412                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8413                         let persist = match &res {
8414                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8415                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8416                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8417                         };
8418                         let _ = handle_error!(self, res, *counterparty_node_id);
8419                         persist
8420                 });
8421         }
8422
8423         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8424                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8425                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8426         }
8427
8428         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8429                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8430                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8431         }
8432
8433         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8434                 // Note that we never need to persist the updated ChannelManager for an inbound
8435                 // update_fee message - the message itself doesn't change our channel state only the
8436                 // `commitment_signed` message afterwards will.
8437                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8438                         let res = self.internal_update_fee(counterparty_node_id, msg);
8439                         let persist = match &res {
8440                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8441                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8442                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8443                         };
8444                         let _ = handle_error!(self, res, *counterparty_node_id);
8445                         persist
8446                 });
8447         }
8448
8449         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8450                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8451                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8452         }
8453
8454         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8455                 PersistenceNotifierGuard::optionally_notify(self, || {
8456                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8457                                 persist
8458                         } else {
8459                                 NotifyOption::DoPersist
8460                         }
8461                 });
8462         }
8463
8464         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8465                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8466                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8467                         let persist = match &res {
8468                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8469                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8470                                 Ok(persist) => *persist,
8471                         };
8472                         let _ = handle_error!(self, res, *counterparty_node_id);
8473                         persist
8474                 });
8475         }
8476
8477         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8478                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8479                         self, || NotifyOption::SkipPersistHandleEvents);
8480                 let mut failed_channels = Vec::new();
8481                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8482                 let remove_peer = {
8483                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
8484                                 log_pubkey!(counterparty_node_id));
8485                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8486                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8487                                 let peer_state = &mut *peer_state_lock;
8488                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8489                                 peer_state.channel_by_id.retain(|_, phase| {
8490                                         let context = match phase {
8491                                                 ChannelPhase::Funded(chan) => {
8492                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger).is_ok() {
8493                                                                 // We only retain funded channels that are not shutdown.
8494                                                                 return true;
8495                                                         }
8496                                                         &mut chan.context
8497                                                 },
8498                                                 // Unfunded channels will always be removed.
8499                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8500                                                         &mut chan.context
8501                                                 },
8502                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8503                                                         &mut chan.context
8504                                                 },
8505                                         };
8506                                         // Clean up for removal.
8507                                         update_maps_on_chan_removal!(self, &context);
8508                                         self.issue_channel_close_events(&context, ClosureReason::DisconnectedPeer);
8509                                         failed_channels.push(context.force_shutdown(false));
8510                                         false
8511                                 });
8512                                 // Note that we don't bother generating any events for pre-accept channels -
8513                                 // they're not considered "channels" yet from the PoV of our events interface.
8514                                 peer_state.inbound_channel_request_by_id.clear();
8515                                 pending_msg_events.retain(|msg| {
8516                                         match msg {
8517                                                 // V1 Channel Establishment
8518                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8519                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8520                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8521                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8522                                                 // V2 Channel Establishment
8523                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8524                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8525                                                 // Common Channel Establishment
8526                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8527                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8528                                                 // Interactive Transaction Construction
8529                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8530                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8531                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8532                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8533                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8534                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8535                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8536                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8537                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8538                                                 // Channel Operations
8539                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8540                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8541                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8542                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8543                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8544                                                 &events::MessageSendEvent::HandleError { .. } => false,
8545                                                 // Gossip
8546                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8547                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8548                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8549                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8550                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8551                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8552                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8553                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8554                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8555                                         }
8556                                 });
8557                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8558                                 peer_state.is_connected = false;
8559                                 peer_state.ok_to_remove(true)
8560                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8561                 };
8562                 if remove_peer {
8563                         per_peer_state.remove(counterparty_node_id);
8564                 }
8565                 mem::drop(per_peer_state);
8566
8567                 for failure in failed_channels.drain(..) {
8568                         self.finish_close_channel(failure);
8569                 }
8570         }
8571
8572         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8573                 if !init_msg.features.supports_static_remote_key() {
8574                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8575                         return Err(());
8576                 }
8577
8578                 let mut res = Ok(());
8579
8580                 PersistenceNotifierGuard::optionally_notify(self, || {
8581                         // If we have too many peers connected which don't have funded channels, disconnect the
8582                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8583                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8584                         // peers connect, but we'll reject new channels from them.
8585                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8586                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8587
8588                         {
8589                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8590                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8591                                         hash_map::Entry::Vacant(e) => {
8592                                                 if inbound_peer_limited {
8593                                                         res = Err(());
8594                                                         return NotifyOption::SkipPersistNoEvents;
8595                                                 }
8596                                                 e.insert(Mutex::new(PeerState {
8597                                                         channel_by_id: HashMap::new(),
8598                                                         inbound_channel_request_by_id: HashMap::new(),
8599                                                         latest_features: init_msg.features.clone(),
8600                                                         pending_msg_events: Vec::new(),
8601                                                         in_flight_monitor_updates: BTreeMap::new(),
8602                                                         monitor_update_blocked_actions: BTreeMap::new(),
8603                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
8604                                                         is_connected: true,
8605                                                 }));
8606                                         },
8607                                         hash_map::Entry::Occupied(e) => {
8608                                                 let mut peer_state = e.get().lock().unwrap();
8609                                                 peer_state.latest_features = init_msg.features.clone();
8610
8611                                                 let best_block_height = self.best_block.read().unwrap().height();
8612                                                 if inbound_peer_limited &&
8613                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
8614                                                         peer_state.channel_by_id.len()
8615                                                 {
8616                                                         res = Err(());
8617                                                         return NotifyOption::SkipPersistNoEvents;
8618                                                 }
8619
8620                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
8621                                                 peer_state.is_connected = true;
8622                                         },
8623                                 }
8624                         }
8625
8626                         log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
8627
8628                         let per_peer_state = self.per_peer_state.read().unwrap();
8629                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8630                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8631                                 let peer_state = &mut *peer_state_lock;
8632                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8633
8634                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
8635                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else {
8636                                                 // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
8637                                                 // (so won't be recovered after a crash), they shouldn't exist here and we would never need to
8638                                                 // worry about closing and removing them.
8639                                                 debug_assert!(false);
8640                                                 None
8641                                         }
8642                                 ).for_each(|chan| {
8643                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
8644                                                 node_id: chan.context.get_counterparty_node_id(),
8645                                                 msg: chan.get_channel_reestablish(&self.logger),
8646                                         });
8647                                 });
8648                         }
8649
8650                         return NotifyOption::SkipPersistHandleEvents;
8651                         //TODO: Also re-broadcast announcement_signatures
8652                 });
8653                 res
8654         }
8655
8656         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
8657                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8658
8659                 match &msg.data as &str {
8660                         "cannot co-op close channel w/ active htlcs"|
8661                         "link failed to shutdown" =>
8662                         {
8663                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
8664                                 // send one while HTLCs are still present. The issue is tracked at
8665                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
8666                                 // to fix it but none so far have managed to land upstream. The issue appears to be
8667                                 // very low priority for the LND team despite being marked "P1".
8668                                 // We're not going to bother handling this in a sensible way, instead simply
8669                                 // repeating the Shutdown message on repeat until morale improves.
8670                                 if !msg.channel_id.is_zero() {
8671                                         let per_peer_state = self.per_peer_state.read().unwrap();
8672                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8673                                         if peer_state_mutex_opt.is_none() { return; }
8674                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
8675                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
8676                                                 if let Some(msg) = chan.get_outbound_shutdown() {
8677                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
8678                                                                 node_id: *counterparty_node_id,
8679                                                                 msg,
8680                                                         });
8681                                                 }
8682                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
8683                                                         node_id: *counterparty_node_id,
8684                                                         action: msgs::ErrorAction::SendWarningMessage {
8685                                                                 msg: msgs::WarningMessage {
8686                                                                         channel_id: msg.channel_id,
8687                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
8688                                                                 },
8689                                                                 log_level: Level::Trace,
8690                                                         }
8691                                                 });
8692                                         }
8693                                 }
8694                                 return;
8695                         }
8696                         _ => {}
8697                 }
8698
8699                 if msg.channel_id.is_zero() {
8700                         let channel_ids: Vec<ChannelId> = {
8701                                 let per_peer_state = self.per_peer_state.read().unwrap();
8702                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8703                                 if peer_state_mutex_opt.is_none() { return; }
8704                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8705                                 let peer_state = &mut *peer_state_lock;
8706                                 // Note that we don't bother generating any events for pre-accept channels -
8707                                 // they're not considered "channels" yet from the PoV of our events interface.
8708                                 peer_state.inbound_channel_request_by_id.clear();
8709                                 peer_state.channel_by_id.keys().cloned().collect()
8710                         };
8711                         for channel_id in channel_ids {
8712                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8713                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
8714                         }
8715                 } else {
8716                         {
8717                                 // First check if we can advance the channel type and try again.
8718                                 let per_peer_state = self.per_peer_state.read().unwrap();
8719                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8720                                 if peer_state_mutex_opt.is_none() { return; }
8721                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8722                                 let peer_state = &mut *peer_state_lock;
8723                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8724                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
8725                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
8726                                                         node_id: *counterparty_node_id,
8727                                                         msg,
8728                                                 });
8729                                                 return;
8730                                         }
8731                                 }
8732                         }
8733
8734                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8735                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
8736                 }
8737         }
8738
8739         fn provided_node_features(&self) -> NodeFeatures {
8740                 provided_node_features(&self.default_configuration)
8741         }
8742
8743         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
8744                 provided_init_features(&self.default_configuration)
8745         }
8746
8747         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8748                 Some(vec![self.chain_hash])
8749         }
8750
8751         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
8752                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8753                         "Dual-funded channels not supported".to_owned(),
8754                          msg.channel_id.clone())), *counterparty_node_id);
8755         }
8756
8757         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
8758                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8759                         "Dual-funded channels not supported".to_owned(),
8760                          msg.channel_id.clone())), *counterparty_node_id);
8761         }
8762
8763         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
8764                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8765                         "Dual-funded channels not supported".to_owned(),
8766                          msg.channel_id.clone())), *counterparty_node_id);
8767         }
8768
8769         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
8770                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8771                         "Dual-funded channels not supported".to_owned(),
8772                          msg.channel_id.clone())), *counterparty_node_id);
8773         }
8774
8775         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
8776                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8777                         "Dual-funded channels not supported".to_owned(),
8778                          msg.channel_id.clone())), *counterparty_node_id);
8779         }
8780
8781         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
8782                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8783                         "Dual-funded channels not supported".to_owned(),
8784                          msg.channel_id.clone())), *counterparty_node_id);
8785         }
8786
8787         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
8788                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8789                         "Dual-funded channels not supported".to_owned(),
8790                          msg.channel_id.clone())), *counterparty_node_id);
8791         }
8792
8793         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
8794                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8795                         "Dual-funded channels not supported".to_owned(),
8796                          msg.channel_id.clone())), *counterparty_node_id);
8797         }
8798
8799         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
8800                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8801                         "Dual-funded channels not supported".to_owned(),
8802                          msg.channel_id.clone())), *counterparty_node_id);
8803         }
8804 }
8805
8806 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
8807 /// [`ChannelManager`].
8808 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
8809         let mut node_features = provided_init_features(config).to_context();
8810         node_features.set_keysend_optional();
8811         node_features
8812 }
8813
8814 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
8815 /// [`ChannelManager`].
8816 ///
8817 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8818 /// or not. Thus, this method is not public.
8819 #[cfg(any(feature = "_test_utils", test))]
8820 pub(crate) fn provided_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
8821         provided_init_features(config).to_context()
8822 }
8823
8824 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
8825 /// [`ChannelManager`].
8826 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
8827         provided_init_features(config).to_context()
8828 }
8829
8830 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
8831 /// [`ChannelManager`].
8832 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
8833         ChannelTypeFeatures::from_init(&provided_init_features(config))
8834 }
8835
8836 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
8837 /// [`ChannelManager`].
8838 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
8839         // Note that if new features are added here which other peers may (eventually) require, we
8840         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
8841         // [`ErroringMessageHandler`].
8842         let mut features = InitFeatures::empty();
8843         features.set_data_loss_protect_required();
8844         features.set_upfront_shutdown_script_optional();
8845         features.set_variable_length_onion_required();
8846         features.set_static_remote_key_required();
8847         features.set_payment_secret_required();
8848         features.set_basic_mpp_optional();
8849         features.set_wumbo_optional();
8850         features.set_shutdown_any_segwit_optional();
8851         features.set_channel_type_optional();
8852         features.set_scid_privacy_optional();
8853         features.set_zero_conf_optional();
8854         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
8855                 features.set_anchors_zero_fee_htlc_tx_optional();
8856         }
8857         features
8858 }
8859
8860 const SERIALIZATION_VERSION: u8 = 1;
8861 const MIN_SERIALIZATION_VERSION: u8 = 1;
8862
8863 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
8864         (2, fee_base_msat, required),
8865         (4, fee_proportional_millionths, required),
8866         (6, cltv_expiry_delta, required),
8867 });
8868
8869 impl_writeable_tlv_based!(ChannelCounterparty, {
8870         (2, node_id, required),
8871         (4, features, required),
8872         (6, unspendable_punishment_reserve, required),
8873         (8, forwarding_info, option),
8874         (9, outbound_htlc_minimum_msat, option),
8875         (11, outbound_htlc_maximum_msat, option),
8876 });
8877
8878 impl Writeable for ChannelDetails {
8879         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8880                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8881                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8882                 let user_channel_id_low = self.user_channel_id as u64;
8883                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
8884                 write_tlv_fields!(writer, {
8885                         (1, self.inbound_scid_alias, option),
8886                         (2, self.channel_id, required),
8887                         (3, self.channel_type, option),
8888                         (4, self.counterparty, required),
8889                         (5, self.outbound_scid_alias, option),
8890                         (6, self.funding_txo, option),
8891                         (7, self.config, option),
8892                         (8, self.short_channel_id, option),
8893                         (9, self.confirmations, option),
8894                         (10, self.channel_value_satoshis, required),
8895                         (12, self.unspendable_punishment_reserve, option),
8896                         (14, user_channel_id_low, required),
8897                         (16, self.balance_msat, required),
8898                         (18, self.outbound_capacity_msat, required),
8899                         (19, self.next_outbound_htlc_limit_msat, required),
8900                         (20, self.inbound_capacity_msat, required),
8901                         (21, self.next_outbound_htlc_minimum_msat, required),
8902                         (22, self.confirmations_required, option),
8903                         (24, self.force_close_spend_delay, option),
8904                         (26, self.is_outbound, required),
8905                         (28, self.is_channel_ready, required),
8906                         (30, self.is_usable, required),
8907                         (32, self.is_public, required),
8908                         (33, self.inbound_htlc_minimum_msat, option),
8909                         (35, self.inbound_htlc_maximum_msat, option),
8910                         (37, user_channel_id_high_opt, option),
8911                         (39, self.feerate_sat_per_1000_weight, option),
8912                         (41, self.channel_shutdown_state, option),
8913                 });
8914                 Ok(())
8915         }
8916 }
8917
8918 impl Readable for ChannelDetails {
8919         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8920                 _init_and_read_len_prefixed_tlv_fields!(reader, {
8921                         (1, inbound_scid_alias, option),
8922                         (2, channel_id, required),
8923                         (3, channel_type, option),
8924                         (4, counterparty, required),
8925                         (5, outbound_scid_alias, option),
8926                         (6, funding_txo, option),
8927                         (7, config, option),
8928                         (8, short_channel_id, option),
8929                         (9, confirmations, option),
8930                         (10, channel_value_satoshis, required),
8931                         (12, unspendable_punishment_reserve, option),
8932                         (14, user_channel_id_low, required),
8933                         (16, balance_msat, required),
8934                         (18, outbound_capacity_msat, required),
8935                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
8936                         // filled in, so we can safely unwrap it here.
8937                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
8938                         (20, inbound_capacity_msat, required),
8939                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
8940                         (22, confirmations_required, option),
8941                         (24, force_close_spend_delay, option),
8942                         (26, is_outbound, required),
8943                         (28, is_channel_ready, required),
8944                         (30, is_usable, required),
8945                         (32, is_public, required),
8946                         (33, inbound_htlc_minimum_msat, option),
8947                         (35, inbound_htlc_maximum_msat, option),
8948                         (37, user_channel_id_high_opt, option),
8949                         (39, feerate_sat_per_1000_weight, option),
8950                         (41, channel_shutdown_state, option),
8951                 });
8952
8953                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8954                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8955                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
8956                 let user_channel_id = user_channel_id_low as u128 +
8957                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
8958
8959                 Ok(Self {
8960                         inbound_scid_alias,
8961                         channel_id: channel_id.0.unwrap(),
8962                         channel_type,
8963                         counterparty: counterparty.0.unwrap(),
8964                         outbound_scid_alias,
8965                         funding_txo,
8966                         config,
8967                         short_channel_id,
8968                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
8969                         unspendable_punishment_reserve,
8970                         user_channel_id,
8971                         balance_msat: balance_msat.0.unwrap(),
8972                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
8973                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
8974                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
8975                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
8976                         confirmations_required,
8977                         confirmations,
8978                         force_close_spend_delay,
8979                         is_outbound: is_outbound.0.unwrap(),
8980                         is_channel_ready: is_channel_ready.0.unwrap(),
8981                         is_usable: is_usable.0.unwrap(),
8982                         is_public: is_public.0.unwrap(),
8983                         inbound_htlc_minimum_msat,
8984                         inbound_htlc_maximum_msat,
8985                         feerate_sat_per_1000_weight,
8986                         channel_shutdown_state,
8987                 })
8988         }
8989 }
8990
8991 impl_writeable_tlv_based!(PhantomRouteHints, {
8992         (2, channels, required_vec),
8993         (4, phantom_scid, required),
8994         (6, real_node_pubkey, required),
8995 });
8996
8997 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
8998         (0, Forward) => {
8999                 (0, onion_packet, required),
9000                 (2, short_channel_id, required),
9001         },
9002         (1, Receive) => {
9003                 (0, payment_data, required),
9004                 (1, phantom_shared_secret, option),
9005                 (2, incoming_cltv_expiry, required),
9006                 (3, payment_metadata, option),
9007                 (5, custom_tlvs, optional_vec),
9008         },
9009         (2, ReceiveKeysend) => {
9010                 (0, payment_preimage, required),
9011                 (2, incoming_cltv_expiry, required),
9012                 (3, payment_metadata, option),
9013                 (4, payment_data, option), // Added in 0.0.116
9014                 (5, custom_tlvs, optional_vec),
9015         },
9016 ;);
9017
9018 impl_writeable_tlv_based!(PendingHTLCInfo, {
9019         (0, routing, required),
9020         (2, incoming_shared_secret, required),
9021         (4, payment_hash, required),
9022         (6, outgoing_amt_msat, required),
9023         (8, outgoing_cltv_value, required),
9024         (9, incoming_amt_msat, option),
9025         (10, skimmed_fee_msat, option),
9026 });
9027
9028
9029 impl Writeable for HTLCFailureMsg {
9030         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9031                 match self {
9032                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9033                                 0u8.write(writer)?;
9034                                 channel_id.write(writer)?;
9035                                 htlc_id.write(writer)?;
9036                                 reason.write(writer)?;
9037                         },
9038                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9039                                 channel_id, htlc_id, sha256_of_onion, failure_code
9040                         }) => {
9041                                 1u8.write(writer)?;
9042                                 channel_id.write(writer)?;
9043                                 htlc_id.write(writer)?;
9044                                 sha256_of_onion.write(writer)?;
9045                                 failure_code.write(writer)?;
9046                         },
9047                 }
9048                 Ok(())
9049         }
9050 }
9051
9052 impl Readable for HTLCFailureMsg {
9053         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9054                 let id: u8 = Readable::read(reader)?;
9055                 match id {
9056                         0 => {
9057                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9058                                         channel_id: Readable::read(reader)?,
9059                                         htlc_id: Readable::read(reader)?,
9060                                         reason: Readable::read(reader)?,
9061                                 }))
9062                         },
9063                         1 => {
9064                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9065                                         channel_id: Readable::read(reader)?,
9066                                         htlc_id: Readable::read(reader)?,
9067                                         sha256_of_onion: Readable::read(reader)?,
9068                                         failure_code: Readable::read(reader)?,
9069                                 }))
9070                         },
9071                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9072                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9073                         // messages contained in the variants.
9074                         // In version 0.0.101, support for reading the variants with these types was added, and
9075                         // we should migrate to writing these variants when UpdateFailHTLC or
9076                         // UpdateFailMalformedHTLC get TLV fields.
9077                         2 => {
9078                                 let length: BigSize = Readable::read(reader)?;
9079                                 let mut s = FixedLengthReader::new(reader, length.0);
9080                                 let res = Readable::read(&mut s)?;
9081                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9082                                 Ok(HTLCFailureMsg::Relay(res))
9083                         },
9084                         3 => {
9085                                 let length: BigSize = Readable::read(reader)?;
9086                                 let mut s = FixedLengthReader::new(reader, length.0);
9087                                 let res = Readable::read(&mut s)?;
9088                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9089                                 Ok(HTLCFailureMsg::Malformed(res))
9090                         },
9091                         _ => Err(DecodeError::UnknownRequiredFeature),
9092                 }
9093         }
9094 }
9095
9096 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9097         (0, Forward),
9098         (1, Fail),
9099 );
9100
9101 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9102         (0, short_channel_id, required),
9103         (1, phantom_shared_secret, option),
9104         (2, outpoint, required),
9105         (4, htlc_id, required),
9106         (6, incoming_packet_shared_secret, required),
9107         (7, user_channel_id, option),
9108 });
9109
9110 impl Writeable for ClaimableHTLC {
9111         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9112                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9113                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9114                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9115                 };
9116                 write_tlv_fields!(writer, {
9117                         (0, self.prev_hop, required),
9118                         (1, self.total_msat, required),
9119                         (2, self.value, required),
9120                         (3, self.sender_intended_value, required),
9121                         (4, payment_data, option),
9122                         (5, self.total_value_received, option),
9123                         (6, self.cltv_expiry, required),
9124                         (8, keysend_preimage, option),
9125                         (10, self.counterparty_skimmed_fee_msat, option),
9126                 });
9127                 Ok(())
9128         }
9129 }
9130
9131 impl Readable for ClaimableHTLC {
9132         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9133                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9134                         (0, prev_hop, required),
9135                         (1, total_msat, option),
9136                         (2, value_ser, required),
9137                         (3, sender_intended_value, option),
9138                         (4, payment_data_opt, option),
9139                         (5, total_value_received, option),
9140                         (6, cltv_expiry, required),
9141                         (8, keysend_preimage, option),
9142                         (10, counterparty_skimmed_fee_msat, option),
9143                 });
9144                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9145                 let value = value_ser.0.unwrap();
9146                 let onion_payload = match keysend_preimage {
9147                         Some(p) => {
9148                                 if payment_data.is_some() {
9149                                         return Err(DecodeError::InvalidValue)
9150                                 }
9151                                 if total_msat.is_none() {
9152                                         total_msat = Some(value);
9153                                 }
9154                                 OnionPayload::Spontaneous(p)
9155                         },
9156                         None => {
9157                                 if total_msat.is_none() {
9158                                         if payment_data.is_none() {
9159                                                 return Err(DecodeError::InvalidValue)
9160                                         }
9161                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9162                                 }
9163                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9164                         },
9165                 };
9166                 Ok(Self {
9167                         prev_hop: prev_hop.0.unwrap(),
9168                         timer_ticks: 0,
9169                         value,
9170                         sender_intended_value: sender_intended_value.unwrap_or(value),
9171                         total_value_received,
9172                         total_msat: total_msat.unwrap(),
9173                         onion_payload,
9174                         cltv_expiry: cltv_expiry.0.unwrap(),
9175                         counterparty_skimmed_fee_msat,
9176                 })
9177         }
9178 }
9179
9180 impl Readable for HTLCSource {
9181         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9182                 let id: u8 = Readable::read(reader)?;
9183                 match id {
9184                         0 => {
9185                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9186                                 let mut first_hop_htlc_msat: u64 = 0;
9187                                 let mut path_hops = Vec::new();
9188                                 let mut payment_id = None;
9189                                 let mut payment_params: Option<PaymentParameters> = None;
9190                                 let mut blinded_tail: Option<BlindedTail> = None;
9191                                 read_tlv_fields!(reader, {
9192                                         (0, session_priv, required),
9193                                         (1, payment_id, option),
9194                                         (2, first_hop_htlc_msat, required),
9195                                         (4, path_hops, required_vec),
9196                                         (5, payment_params, (option: ReadableArgs, 0)),
9197                                         (6, blinded_tail, option),
9198                                 });
9199                                 if payment_id.is_none() {
9200                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9201                                         // instead.
9202                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9203                                 }
9204                                 let path = Path { hops: path_hops, blinded_tail };
9205                                 if path.hops.len() == 0 {
9206                                         return Err(DecodeError::InvalidValue);
9207                                 }
9208                                 if let Some(params) = payment_params.as_mut() {
9209                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9210                                                 if final_cltv_expiry_delta == &0 {
9211                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9212                                                 }
9213                                         }
9214                                 }
9215                                 Ok(HTLCSource::OutboundRoute {
9216                                         session_priv: session_priv.0.unwrap(),
9217                                         first_hop_htlc_msat,
9218                                         path,
9219                                         payment_id: payment_id.unwrap(),
9220                                 })
9221                         }
9222                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9223                         _ => Err(DecodeError::UnknownRequiredFeature),
9224                 }
9225         }
9226 }
9227
9228 impl Writeable for HTLCSource {
9229         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9230                 match self {
9231                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9232                                 0u8.write(writer)?;
9233                                 let payment_id_opt = Some(payment_id);
9234                                 write_tlv_fields!(writer, {
9235                                         (0, session_priv, required),
9236                                         (1, payment_id_opt, option),
9237                                         (2, first_hop_htlc_msat, required),
9238                                         // 3 was previously used to write a PaymentSecret for the payment.
9239                                         (4, path.hops, required_vec),
9240                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9241                                         (6, path.blinded_tail, option),
9242                                  });
9243                         }
9244                         HTLCSource::PreviousHopData(ref field) => {
9245                                 1u8.write(writer)?;
9246                                 field.write(writer)?;
9247                         }
9248                 }
9249                 Ok(())
9250         }
9251 }
9252
9253 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9254         (0, forward_info, required),
9255         (1, prev_user_channel_id, (default_value, 0)),
9256         (2, prev_short_channel_id, required),
9257         (4, prev_htlc_id, required),
9258         (6, prev_funding_outpoint, required),
9259 });
9260
9261 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
9262         (1, FailHTLC) => {
9263                 (0, htlc_id, required),
9264                 (2, err_packet, required),
9265         };
9266         (0, AddHTLC)
9267 );
9268
9269 impl_writeable_tlv_based!(PendingInboundPayment, {
9270         (0, payment_secret, required),
9271         (2, expiry_time, required),
9272         (4, user_payment_id, required),
9273         (6, payment_preimage, required),
9274         (8, min_value_msat, required),
9275 });
9276
9277 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>
9278 where
9279         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9280         T::Target: BroadcasterInterface,
9281         ES::Target: EntropySource,
9282         NS::Target: NodeSigner,
9283         SP::Target: SignerProvider,
9284         F::Target: FeeEstimator,
9285         R::Target: Router,
9286         L::Target: Logger,
9287 {
9288         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9289                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9290
9291                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9292
9293                 self.chain_hash.write(writer)?;
9294                 {
9295                         let best_block = self.best_block.read().unwrap();
9296                         best_block.height().write(writer)?;
9297                         best_block.block_hash().write(writer)?;
9298                 }
9299
9300                 let mut serializable_peer_count: u64 = 0;
9301                 {
9302                         let per_peer_state = self.per_peer_state.read().unwrap();
9303                         let mut number_of_funded_channels = 0;
9304                         for (_, peer_state_mutex) in per_peer_state.iter() {
9305                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9306                                 let peer_state = &mut *peer_state_lock;
9307                                 if !peer_state.ok_to_remove(false) {
9308                                         serializable_peer_count += 1;
9309                                 }
9310
9311                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9312                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9313                                 ).count();
9314                         }
9315
9316                         (number_of_funded_channels as u64).write(writer)?;
9317
9318                         for (_, peer_state_mutex) in per_peer_state.iter() {
9319                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9320                                 let peer_state = &mut *peer_state_lock;
9321                                 for channel in peer_state.channel_by_id.iter().filter_map(
9322                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9323                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9324                                         } else { None }
9325                                 ) {
9326                                         channel.write(writer)?;
9327                                 }
9328                         }
9329                 }
9330
9331                 {
9332                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9333                         (forward_htlcs.len() as u64).write(writer)?;
9334                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9335                                 short_channel_id.write(writer)?;
9336                                 (pending_forwards.len() as u64).write(writer)?;
9337                                 for forward in pending_forwards {
9338                                         forward.write(writer)?;
9339                                 }
9340                         }
9341                 }
9342
9343                 let per_peer_state = self.per_peer_state.write().unwrap();
9344
9345                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9346                 let claimable_payments = self.claimable_payments.lock().unwrap();
9347                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9348
9349                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9350                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9351                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9352                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9353                         payment_hash.write(writer)?;
9354                         (payment.htlcs.len() as u64).write(writer)?;
9355                         for htlc in payment.htlcs.iter() {
9356                                 htlc.write(writer)?;
9357                         }
9358                         htlc_purposes.push(&payment.purpose);
9359                         htlc_onion_fields.push(&payment.onion_fields);
9360                 }
9361
9362                 let mut monitor_update_blocked_actions_per_peer = None;
9363                 let mut peer_states = Vec::new();
9364                 for (_, peer_state_mutex) in per_peer_state.iter() {
9365                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9366                         // of a lockorder violation deadlock - no other thread can be holding any
9367                         // per_peer_state lock at all.
9368                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9369                 }
9370
9371                 (serializable_peer_count).write(writer)?;
9372                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9373                         // Peers which we have no channels to should be dropped once disconnected. As we
9374                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9375                         // consider all peers as disconnected here. There's therefore no need write peers with
9376                         // no channels.
9377                         if !peer_state.ok_to_remove(false) {
9378                                 peer_pubkey.write(writer)?;
9379                                 peer_state.latest_features.write(writer)?;
9380                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9381                                         monitor_update_blocked_actions_per_peer
9382                                                 .get_or_insert_with(Vec::new)
9383                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9384                                 }
9385                         }
9386                 }
9387
9388                 let events = self.pending_events.lock().unwrap();
9389                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9390                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9391                 // refuse to read the new ChannelManager.
9392                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9393                 if events_not_backwards_compatible {
9394                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9395                         // well save the space and not write any events here.
9396                         0u64.write(writer)?;
9397                 } else {
9398                         (events.len() as u64).write(writer)?;
9399                         for (event, _) in events.iter() {
9400                                 event.write(writer)?;
9401                         }
9402                 }
9403
9404                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
9405                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
9406                 // the closing monitor updates were always effectively replayed on startup (either directly
9407                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
9408                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
9409                 0u64.write(writer)?;
9410
9411                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
9412                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
9413                 // likely to be identical.
9414                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9415                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9416
9417                 (pending_inbound_payments.len() as u64).write(writer)?;
9418                 for (hash, pending_payment) in pending_inbound_payments.iter() {
9419                         hash.write(writer)?;
9420                         pending_payment.write(writer)?;
9421                 }
9422
9423                 // For backwards compat, write the session privs and their total length.
9424                 let mut num_pending_outbounds_compat: u64 = 0;
9425                 for (_, outbound) in pending_outbound_payments.iter() {
9426                         if !outbound.is_fulfilled() && !outbound.abandoned() {
9427                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
9428                         }
9429                 }
9430                 num_pending_outbounds_compat.write(writer)?;
9431                 for (_, outbound) in pending_outbound_payments.iter() {
9432                         match outbound {
9433                                 PendingOutboundPayment::Legacy { session_privs } |
9434                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9435                                         for session_priv in session_privs.iter() {
9436                                                 session_priv.write(writer)?;
9437                                         }
9438                                 }
9439                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
9440                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
9441                                 PendingOutboundPayment::Fulfilled { .. } => {},
9442                                 PendingOutboundPayment::Abandoned { .. } => {},
9443                         }
9444                 }
9445
9446                 // Encode without retry info for 0.0.101 compatibility.
9447                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
9448                 for (id, outbound) in pending_outbound_payments.iter() {
9449                         match outbound {
9450                                 PendingOutboundPayment::Legacy { session_privs } |
9451                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9452                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
9453                                 },
9454                                 _ => {},
9455                         }
9456                 }
9457
9458                 let mut pending_intercepted_htlcs = None;
9459                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
9460                 if our_pending_intercepts.len() != 0 {
9461                         pending_intercepted_htlcs = Some(our_pending_intercepts);
9462                 }
9463
9464                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
9465                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
9466                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
9467                         // map. Thus, if there are no entries we skip writing a TLV for it.
9468                         pending_claiming_payments = None;
9469                 }
9470
9471                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
9472                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9473                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
9474                                 if !updates.is_empty() {
9475                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
9476                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
9477                                 }
9478                         }
9479                 }
9480
9481                 write_tlv_fields!(writer, {
9482                         (1, pending_outbound_payments_no_retry, required),
9483                         (2, pending_intercepted_htlcs, option),
9484                         (3, pending_outbound_payments, required),
9485                         (4, pending_claiming_payments, option),
9486                         (5, self.our_network_pubkey, required),
9487                         (6, monitor_update_blocked_actions_per_peer, option),
9488                         (7, self.fake_scid_rand_bytes, required),
9489                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
9490                         (9, htlc_purposes, required_vec),
9491                         (10, in_flight_monitor_updates, option),
9492                         (11, self.probing_cookie_secret, required),
9493                         (13, htlc_onion_fields, optional_vec),
9494                 });
9495
9496                 Ok(())
9497         }
9498 }
9499
9500 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
9501         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9502                 (self.len() as u64).write(w)?;
9503                 for (event, action) in self.iter() {
9504                         event.write(w)?;
9505                         action.write(w)?;
9506                         #[cfg(debug_assertions)] {
9507                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
9508                                 // be persisted and are regenerated on restart. However, if such an event has a
9509                                 // post-event-handling action we'll write nothing for the event and would have to
9510                                 // either forget the action or fail on deserialization (which we do below). Thus,
9511                                 // check that the event is sane here.
9512                                 let event_encoded = event.encode();
9513                                 let event_read: Option<Event> =
9514                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
9515                                 if action.is_some() { assert!(event_read.is_some()); }
9516                         }
9517                 }
9518                 Ok(())
9519         }
9520 }
9521 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
9522         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9523                 let len: u64 = Readable::read(reader)?;
9524                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
9525                 let mut events: Self = VecDeque::with_capacity(cmp::min(
9526                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
9527                         len) as usize);
9528                 for _ in 0..len {
9529                         let ev_opt = MaybeReadable::read(reader)?;
9530                         let action = Readable::read(reader)?;
9531                         if let Some(ev) = ev_opt {
9532                                 events.push_back((ev, action));
9533                         } else if action.is_some() {
9534                                 return Err(DecodeError::InvalidValue);
9535                         }
9536                 }
9537                 Ok(events)
9538         }
9539 }
9540
9541 impl_writeable_tlv_based_enum!(ChannelShutdownState,
9542         (0, NotShuttingDown) => {},
9543         (2, ShutdownInitiated) => {},
9544         (4, ResolvingHTLCs) => {},
9545         (6, NegotiatingClosingFee) => {},
9546         (8, ShutdownComplete) => {}, ;
9547 );
9548
9549 /// Arguments for the creation of a ChannelManager that are not deserialized.
9550 ///
9551 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
9552 /// is:
9553 /// 1) Deserialize all stored [`ChannelMonitor`]s.
9554 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
9555 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
9556 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
9557 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
9558 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
9559 ///    same way you would handle a [`chain::Filter`] call using
9560 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
9561 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
9562 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
9563 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
9564 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
9565 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
9566 ///    the next step.
9567 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
9568 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
9569 ///
9570 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
9571 /// call any other methods on the newly-deserialized [`ChannelManager`].
9572 ///
9573 /// Note that because some channels may be closed during deserialization, it is critical that you
9574 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
9575 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
9576 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
9577 /// not force-close the same channels but consider them live), you may end up revoking a state for
9578 /// which you've already broadcasted the transaction.
9579 ///
9580 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
9581 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9582 where
9583         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9584         T::Target: BroadcasterInterface,
9585         ES::Target: EntropySource,
9586         NS::Target: NodeSigner,
9587         SP::Target: SignerProvider,
9588         F::Target: FeeEstimator,
9589         R::Target: Router,
9590         L::Target: Logger,
9591 {
9592         /// A cryptographically secure source of entropy.
9593         pub entropy_source: ES,
9594
9595         /// A signer that is able to perform node-scoped cryptographic operations.
9596         pub node_signer: NS,
9597
9598         /// The keys provider which will give us relevant keys. Some keys will be loaded during
9599         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
9600         /// signing data.
9601         pub signer_provider: SP,
9602
9603         /// The fee_estimator for use in the ChannelManager in the future.
9604         ///
9605         /// No calls to the FeeEstimator will be made during deserialization.
9606         pub fee_estimator: F,
9607         /// The chain::Watch for use in the ChannelManager in the future.
9608         ///
9609         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
9610         /// you have deserialized ChannelMonitors separately and will add them to your
9611         /// chain::Watch after deserializing this ChannelManager.
9612         pub chain_monitor: M,
9613
9614         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
9615         /// used to broadcast the latest local commitment transactions of channels which must be
9616         /// force-closed during deserialization.
9617         pub tx_broadcaster: T,
9618         /// The router which will be used in the ChannelManager in the future for finding routes
9619         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
9620         ///
9621         /// No calls to the router will be made during deserialization.
9622         pub router: R,
9623         /// The Logger for use in the ChannelManager and which may be used to log information during
9624         /// deserialization.
9625         pub logger: L,
9626         /// Default settings used for new channels. Any existing channels will continue to use the
9627         /// runtime settings which were stored when the ChannelManager was serialized.
9628         pub default_config: UserConfig,
9629
9630         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
9631         /// value.context.get_funding_txo() should be the key).
9632         ///
9633         /// If a monitor is inconsistent with the channel state during deserialization the channel will
9634         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
9635         /// is true for missing channels as well. If there is a monitor missing for which we find
9636         /// channel data Err(DecodeError::InvalidValue) will be returned.
9637         ///
9638         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
9639         /// this struct.
9640         ///
9641         /// This is not exported to bindings users because we have no HashMap bindings
9642         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
9643 }
9644
9645 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9646                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
9647 where
9648         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9649         T::Target: BroadcasterInterface,
9650         ES::Target: EntropySource,
9651         NS::Target: NodeSigner,
9652         SP::Target: SignerProvider,
9653         F::Target: FeeEstimator,
9654         R::Target: Router,
9655         L::Target: Logger,
9656 {
9657         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
9658         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
9659         /// populate a HashMap directly from C.
9660         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,
9661                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
9662                 Self {
9663                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
9664                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
9665                 }
9666         }
9667 }
9668
9669 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
9670 // SipmleArcChannelManager type:
9671 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9672         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
9673 where
9674         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9675         T::Target: BroadcasterInterface,
9676         ES::Target: EntropySource,
9677         NS::Target: NodeSigner,
9678         SP::Target: SignerProvider,
9679         F::Target: FeeEstimator,
9680         R::Target: Router,
9681         L::Target: Logger,
9682 {
9683         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9684                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
9685                 Ok((blockhash, Arc::new(chan_manager)))
9686         }
9687 }
9688
9689 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9690         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
9691 where
9692         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9693         T::Target: BroadcasterInterface,
9694         ES::Target: EntropySource,
9695         NS::Target: NodeSigner,
9696         SP::Target: SignerProvider,
9697         F::Target: FeeEstimator,
9698         R::Target: Router,
9699         L::Target: Logger,
9700 {
9701         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9702                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
9703
9704                 let chain_hash: ChainHash = Readable::read(reader)?;
9705                 let best_block_height: u32 = Readable::read(reader)?;
9706                 let best_block_hash: BlockHash = Readable::read(reader)?;
9707
9708                 let mut failed_htlcs = Vec::new();
9709
9710                 let channel_count: u64 = Readable::read(reader)?;
9711                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
9712                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9713                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9714                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9715                 let mut channel_closures = VecDeque::new();
9716                 let mut close_background_events = Vec::new();
9717                 for _ in 0..channel_count {
9718                         let mut channel: Channel<SP> = Channel::read(reader, (
9719                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
9720                         ))?;
9721                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
9722                         funding_txo_set.insert(funding_txo.clone());
9723                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
9724                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
9725                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
9726                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
9727                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9728                                         // But if the channel is behind of the monitor, close the channel:
9729                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
9730                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
9731                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9732                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
9733                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
9734                                         }
9735                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
9736                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
9737                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
9738                                         }
9739                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
9740                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
9741                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
9742                                         }
9743                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
9744                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
9745                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
9746                                         }
9747                                         let (monitor_update, mut new_failed_htlcs, batch_funding_txid) = channel.context.force_shutdown(true);
9748                                         if batch_funding_txid.is_some() {
9749                                                 return Err(DecodeError::InvalidValue);
9750                                         }
9751                                         if let Some((counterparty_node_id, funding_txo, update)) = monitor_update {
9752                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
9753                                                         counterparty_node_id, funding_txo, update
9754                                                 });
9755                                         }
9756                                         failed_htlcs.append(&mut new_failed_htlcs);
9757                                         channel_closures.push_back((events::Event::ChannelClosed {
9758                                                 channel_id: channel.context.channel_id(),
9759                                                 user_channel_id: channel.context.get_user_id(),
9760                                                 reason: ClosureReason::OutdatedChannelManager,
9761                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9762                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9763                                         }, None));
9764                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
9765                                                 let mut found_htlc = false;
9766                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
9767                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
9768                                                 }
9769                                                 if !found_htlc {
9770                                                         // If we have some HTLCs in the channel which are not present in the newer
9771                                                         // ChannelMonitor, they have been removed and should be failed back to
9772                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
9773                                                         // were actually claimed we'd have generated and ensured the previous-hop
9774                                                         // claim update ChannelMonitor updates were persisted prior to persising
9775                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
9776                                                         // backwards leg of the HTLC will simply be rejected.
9777                                                         log_info!(args.logger,
9778                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
9779                                                                 &channel.context.channel_id(), &payment_hash);
9780                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9781                                                 }
9782                                         }
9783                                 } else {
9784                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
9785                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
9786                                                 monitor.get_latest_update_id());
9787                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
9788                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9789                                         }
9790                                         if channel.context.is_funding_broadcast() {
9791                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
9792                                         }
9793                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
9794                                                 hash_map::Entry::Occupied(mut entry) => {
9795                                                         let by_id_map = entry.get_mut();
9796                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9797                                                 },
9798                                                 hash_map::Entry::Vacant(entry) => {
9799                                                         let mut by_id_map = HashMap::new();
9800                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9801                                                         entry.insert(by_id_map);
9802                                                 }
9803                                         }
9804                                 }
9805                         } else if channel.is_awaiting_initial_mon_persist() {
9806                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
9807                                 // was in-progress, we never broadcasted the funding transaction and can still
9808                                 // safely discard the channel.
9809                                 let _ = channel.context.force_shutdown(false);
9810                                 channel_closures.push_back((events::Event::ChannelClosed {
9811                                         channel_id: channel.context.channel_id(),
9812                                         user_channel_id: channel.context.get_user_id(),
9813                                         reason: ClosureReason::DisconnectedPeer,
9814                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9815                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9816                                 }, None));
9817                         } else {
9818                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
9819                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9820                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9821                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
9822                                 log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
9823                                 return Err(DecodeError::InvalidValue);
9824                         }
9825                 }
9826
9827                 for (funding_txo, _) in args.channel_monitors.iter() {
9828                         if !funding_txo_set.contains(funding_txo) {
9829                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
9830                                         &funding_txo.to_channel_id());
9831                                 let monitor_update = ChannelMonitorUpdate {
9832                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
9833                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
9834                                 };
9835                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
9836                         }
9837                 }
9838
9839                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
9840                 let forward_htlcs_count: u64 = Readable::read(reader)?;
9841                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
9842                 for _ in 0..forward_htlcs_count {
9843                         let short_channel_id = Readable::read(reader)?;
9844                         let pending_forwards_count: u64 = Readable::read(reader)?;
9845                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
9846                         for _ in 0..pending_forwards_count {
9847                                 pending_forwards.push(Readable::read(reader)?);
9848                         }
9849                         forward_htlcs.insert(short_channel_id, pending_forwards);
9850                 }
9851
9852                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
9853                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
9854                 for _ in 0..claimable_htlcs_count {
9855                         let payment_hash = Readable::read(reader)?;
9856                         let previous_hops_len: u64 = Readable::read(reader)?;
9857                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
9858                         for _ in 0..previous_hops_len {
9859                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
9860                         }
9861                         claimable_htlcs_list.push((payment_hash, previous_hops));
9862                 }
9863
9864                 let peer_state_from_chans = |channel_by_id| {
9865                         PeerState {
9866                                 channel_by_id,
9867                                 inbound_channel_request_by_id: HashMap::new(),
9868                                 latest_features: InitFeatures::empty(),
9869                                 pending_msg_events: Vec::new(),
9870                                 in_flight_monitor_updates: BTreeMap::new(),
9871                                 monitor_update_blocked_actions: BTreeMap::new(),
9872                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
9873                                 is_connected: false,
9874                         }
9875                 };
9876
9877                 let peer_count: u64 = Readable::read(reader)?;
9878                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
9879                 for _ in 0..peer_count {
9880                         let peer_pubkey = Readable::read(reader)?;
9881                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
9882                         let mut peer_state = peer_state_from_chans(peer_chans);
9883                         peer_state.latest_features = Readable::read(reader)?;
9884                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
9885                 }
9886
9887                 let event_count: u64 = Readable::read(reader)?;
9888                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
9889                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
9890                 for _ in 0..event_count {
9891                         match MaybeReadable::read(reader)? {
9892                                 Some(event) => pending_events_read.push_back((event, None)),
9893                                 None => continue,
9894                         }
9895                 }
9896
9897                 let background_event_count: u64 = Readable::read(reader)?;
9898                 for _ in 0..background_event_count {
9899                         match <u8 as Readable>::read(reader)? {
9900                                 0 => {
9901                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
9902                                         // however we really don't (and never did) need them - we regenerate all
9903                                         // on-startup monitor updates.
9904                                         let _: OutPoint = Readable::read(reader)?;
9905                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
9906                                 }
9907                                 _ => return Err(DecodeError::InvalidValue),
9908                         }
9909                 }
9910
9911                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
9912                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
9913
9914                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
9915                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
9916                 for _ in 0..pending_inbound_payment_count {
9917                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
9918                                 return Err(DecodeError::InvalidValue);
9919                         }
9920                 }
9921
9922                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
9923                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
9924                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
9925                 for _ in 0..pending_outbound_payments_count_compat {
9926                         let session_priv = Readable::read(reader)?;
9927                         let payment = PendingOutboundPayment::Legacy {
9928                                 session_privs: [session_priv].iter().cloned().collect()
9929                         };
9930                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
9931                                 return Err(DecodeError::InvalidValue)
9932                         };
9933                 }
9934
9935                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
9936                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
9937                 let mut pending_outbound_payments = None;
9938                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
9939                 let mut received_network_pubkey: Option<PublicKey> = None;
9940                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
9941                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
9942                 let mut claimable_htlc_purposes = None;
9943                 let mut claimable_htlc_onion_fields = None;
9944                 let mut pending_claiming_payments = Some(HashMap::new());
9945                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
9946                 let mut events_override = None;
9947                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
9948                 read_tlv_fields!(reader, {
9949                         (1, pending_outbound_payments_no_retry, option),
9950                         (2, pending_intercepted_htlcs, option),
9951                         (3, pending_outbound_payments, option),
9952                         (4, pending_claiming_payments, option),
9953                         (5, received_network_pubkey, option),
9954                         (6, monitor_update_blocked_actions_per_peer, option),
9955                         (7, fake_scid_rand_bytes, option),
9956                         (8, events_override, option),
9957                         (9, claimable_htlc_purposes, optional_vec),
9958                         (10, in_flight_monitor_updates, option),
9959                         (11, probing_cookie_secret, option),
9960                         (13, claimable_htlc_onion_fields, optional_vec),
9961                 });
9962                 if fake_scid_rand_bytes.is_none() {
9963                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
9964                 }
9965
9966                 if probing_cookie_secret.is_none() {
9967                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
9968                 }
9969
9970                 if let Some(events) = events_override {
9971                         pending_events_read = events;
9972                 }
9973
9974                 if !channel_closures.is_empty() {
9975                         pending_events_read.append(&mut channel_closures);
9976                 }
9977
9978                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
9979                         pending_outbound_payments = Some(pending_outbound_payments_compat);
9980                 } else if pending_outbound_payments.is_none() {
9981                         let mut outbounds = HashMap::new();
9982                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
9983                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
9984                         }
9985                         pending_outbound_payments = Some(outbounds);
9986                 }
9987                 let pending_outbounds = OutboundPayments {
9988                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
9989                         retry_lock: Mutex::new(())
9990                 };
9991
9992                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
9993                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
9994                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
9995                 // replayed, and for each monitor update we have to replay we have to ensure there's a
9996                 // `ChannelMonitor` for it.
9997                 //
9998                 // In order to do so we first walk all of our live channels (so that we can check their
9999                 // state immediately after doing the update replays, when we have the `update_id`s
10000                 // available) and then walk any remaining in-flight updates.
10001                 //
10002                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10003                 let mut pending_background_events = Vec::new();
10004                 macro_rules! handle_in_flight_updates {
10005                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10006                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
10007                         ) => { {
10008                                 let mut max_in_flight_update_id = 0;
10009                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10010                                 for update in $chan_in_flight_upds.iter() {
10011                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10012                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
10013                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10014                                         pending_background_events.push(
10015                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10016                                                         counterparty_node_id: $counterparty_node_id,
10017                                                         funding_txo: $funding_txo,
10018                                                         update: update.clone(),
10019                                                 });
10020                                 }
10021                                 if $chan_in_flight_upds.is_empty() {
10022                                         // We had some updates to apply, but it turns out they had completed before we
10023                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10024                                         // the completion actions for any monitor updates, but otherwise are done.
10025                                         pending_background_events.push(
10026                                                 BackgroundEvent::MonitorUpdatesComplete {
10027                                                         counterparty_node_id: $counterparty_node_id,
10028                                                         channel_id: $funding_txo.to_channel_id(),
10029                                                 });
10030                                 }
10031                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10032                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
10033                                         return Err(DecodeError::InvalidValue);
10034                                 }
10035                                 max_in_flight_update_id
10036                         } }
10037                 }
10038
10039                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10040                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10041                         let peer_state = &mut *peer_state_lock;
10042                         for phase in peer_state.channel_by_id.values() {
10043                                 if let ChannelPhase::Funded(chan) = phase {
10044                                         // Channels that were persisted have to be funded, otherwise they should have been
10045                                         // discarded.
10046                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10047                                         let monitor = args.channel_monitors.get(&funding_txo)
10048                                                 .expect("We already checked for monitor presence when loading channels");
10049                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10050                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10051                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10052                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10053                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10054                                                                         funding_txo, monitor, peer_state, ""));
10055                                                 }
10056                                         }
10057                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10058                                                 // If the channel is ahead of the monitor, return InvalidValue:
10059                                                 log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10060                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10061                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10062                                                 log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10063                                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10064                                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10065                                                 log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10066                                                 log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10067                                                 return Err(DecodeError::InvalidValue);
10068                                         }
10069                                 } else {
10070                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10071                                         // created in this `channel_by_id` map.
10072                                         debug_assert!(false);
10073                                         return Err(DecodeError::InvalidValue);
10074                                 }
10075                         }
10076                 }
10077
10078                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10079                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10080                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10081                                         // Now that we've removed all the in-flight monitor updates for channels that are
10082                                         // still open, we need to replay any monitor updates that are for closed channels,
10083                                         // creating the neccessary peer_state entries as we go.
10084                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10085                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
10086                                         });
10087                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10088                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10089                                                 funding_txo, monitor, peer_state, "closed ");
10090                                 } else {
10091                                         log_error!(args.logger, "A ChannelMonitor is missing even though we have in-flight updates for it! This indicates a potentially-critical violation of the chain::Watch API!");
10092                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
10093                                                 &funding_txo.to_channel_id());
10094                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10095                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10096                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10097                                         log_error!(args.logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10098                                         return Err(DecodeError::InvalidValue);
10099                                 }
10100                         }
10101                 }
10102
10103                 // Note that we have to do the above replays before we push new monitor updates.
10104                 pending_background_events.append(&mut close_background_events);
10105
10106                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10107                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10108                 // have a fully-constructed `ChannelManager` at the end.
10109                 let mut pending_claims_to_replay = Vec::new();
10110
10111                 {
10112                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10113                         // ChannelMonitor data for any channels for which we do not have authorative state
10114                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10115                         // corresponding `Channel` at all).
10116                         // This avoids several edge-cases where we would otherwise "forget" about pending
10117                         // payments which are still in-flight via their on-chain state.
10118                         // We only rebuild the pending payments map if we were most recently serialized by
10119                         // 0.0.102+
10120                         for (_, monitor) in args.channel_monitors.iter() {
10121                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
10122                                 if counterparty_opt.is_none() {
10123                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10124                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10125                                                         if path.hops.is_empty() {
10126                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
10127                                                                 return Err(DecodeError::InvalidValue);
10128                                                         }
10129
10130                                                         let path_amt = path.final_value_msat();
10131                                                         let mut session_priv_bytes = [0; 32];
10132                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10133                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10134                                                                 hash_map::Entry::Occupied(mut entry) => {
10135                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10136                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10137                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), &htlc.payment_hash);
10138                                                                 },
10139                                                                 hash_map::Entry::Vacant(entry) => {
10140                                                                         let path_fee = path.fee_msat();
10141                                                                         entry.insert(PendingOutboundPayment::Retryable {
10142                                                                                 retry_strategy: None,
10143                                                                                 attempts: PaymentAttempts::new(),
10144                                                                                 payment_params: None,
10145                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
10146                                                                                 payment_hash: htlc.payment_hash,
10147                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10148                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10149                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10150                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10151                                                                                 pending_amt_msat: path_amt,
10152                                                                                 pending_fee_msat: Some(path_fee),
10153                                                                                 total_msat: path_amt,
10154                                                                                 starting_block_height: best_block_height,
10155                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10156                                                                         });
10157                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10158                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10159                                                                 }
10160                                                         }
10161                                                 }
10162                                         }
10163                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10164                                                 match htlc_source {
10165                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10166                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10167                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10168                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10169                                                                 };
10170                                                                 // The ChannelMonitor is now responsible for this HTLC's
10171                                                                 // failure/success and will let us know what its outcome is. If we
10172                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10173                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10174                                                                 // the monitor was when forwarding the payment.
10175                                                                 forward_htlcs.retain(|_, forwards| {
10176                                                                         forwards.retain(|forward| {
10177                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10178                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10179                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10180                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10181                                                                                                 false
10182                                                                                         } else { true }
10183                                                                                 } else { true }
10184                                                                         });
10185                                                                         !forwards.is_empty()
10186                                                                 });
10187                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10188                                                                         if pending_forward_matches_htlc(&htlc_info) {
10189                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10190                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10191                                                                                 pending_events_read.retain(|(event, _)| {
10192                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10193                                                                                                 intercepted_id != ev_id
10194                                                                                         } else { true }
10195                                                                                 });
10196                                                                                 false
10197                                                                         } else { true }
10198                                                                 });
10199                                                         },
10200                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10201                                                                 if let Some(preimage) = preimage_opt {
10202                                                                         let pending_events = Mutex::new(pending_events_read);
10203                                                                         // Note that we set `from_onchain` to "false" here,
10204                                                                         // deliberately keeping the pending payment around forever.
10205                                                                         // Given it should only occur when we have a channel we're
10206                                                                         // force-closing for being stale that's okay.
10207                                                                         // The alternative would be to wipe the state when claiming,
10208                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10209                                                                         // it and the `PaymentSent` on every restart until the
10210                                                                         // `ChannelMonitor` is removed.
10211                                                                         let compl_action =
10212                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10213                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10214                                                                                         counterparty_node_id: path.hops[0].pubkey,
10215                                                                                 };
10216                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10217                                                                                 path, false, compl_action, &pending_events, &args.logger);
10218                                                                         pending_events_read = pending_events.into_inner().unwrap();
10219                                                                 }
10220                                                         },
10221                                                 }
10222                                         }
10223                                 }
10224
10225                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10226                                 // preimages from it which may be needed in upstream channels for forwarded
10227                                 // payments.
10228                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10229                                         .into_iter()
10230                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10231                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10232                                                         if let Some(payment_preimage) = preimage_opt {
10233                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10234                                                                         // Check if `counterparty_opt.is_none()` to see if the
10235                                                                         // downstream chan is closed (because we don't have a
10236                                                                         // channel_id -> peer map entry).
10237                                                                         counterparty_opt.is_none(),
10238                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10239                                                                         monitor.get_funding_txo().0))
10240                                                         } else { None }
10241                                                 } else {
10242                                                         // If it was an outbound payment, we've handled it above - if a preimage
10243                                                         // came in and we persisted the `ChannelManager` we either handled it and
10244                                                         // are good to go or the channel force-closed - we don't have to handle the
10245                                                         // channel still live case here.
10246                                                         None
10247                                                 }
10248                                         });
10249                                 for tuple in outbound_claimed_htlcs_iter {
10250                                         pending_claims_to_replay.push(tuple);
10251                                 }
10252                         }
10253                 }
10254
10255                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10256                         // If we have pending HTLCs to forward, assume we either dropped a
10257                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10258                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10259                         // constant as enough time has likely passed that we should simply handle the forwards
10260                         // now, or at least after the user gets a chance to reconnect to our peers.
10261                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10262                                 time_forwardable: Duration::from_secs(2),
10263                         }, None));
10264                 }
10265
10266                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10267                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10268
10269                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10270                 if let Some(purposes) = claimable_htlc_purposes {
10271                         if purposes.len() != claimable_htlcs_list.len() {
10272                                 return Err(DecodeError::InvalidValue);
10273                         }
10274                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10275                                 if onion_fields.len() != claimable_htlcs_list.len() {
10276                                         return Err(DecodeError::InvalidValue);
10277                                 }
10278                                 for (purpose, (onion, (payment_hash, htlcs))) in
10279                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10280                                 {
10281                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10282                                                 purpose, htlcs, onion_fields: onion,
10283                                         });
10284                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10285                                 }
10286                         } else {
10287                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10288                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10289                                                 purpose, htlcs, onion_fields: None,
10290                                         });
10291                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10292                                 }
10293                         }
10294                 } else {
10295                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10296                         // include a `_legacy_hop_data` in the `OnionPayload`.
10297                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10298                                 if htlcs.is_empty() {
10299                                         return Err(DecodeError::InvalidValue);
10300                                 }
10301                                 let purpose = match &htlcs[0].onion_payload {
10302                                         OnionPayload::Invoice { _legacy_hop_data } => {
10303                                                 if let Some(hop_data) = _legacy_hop_data {
10304                                                         events::PaymentPurpose::InvoicePayment {
10305                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10306                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10307                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10308                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10309                                                                                 Err(()) => {
10310                                                                                         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);
10311                                                                                         return Err(DecodeError::InvalidValue);
10312                                                                                 }
10313                                                                         }
10314                                                                 },
10315                                                                 payment_secret: hop_data.payment_secret,
10316                                                         }
10317                                                 } else { return Err(DecodeError::InvalidValue); }
10318                                         },
10319                                         OnionPayload::Spontaneous(payment_preimage) =>
10320                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10321                                 };
10322                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10323                                         purpose, htlcs, onion_fields: None,
10324                                 });
10325                         }
10326                 }
10327
10328                 let mut secp_ctx = Secp256k1::new();
10329                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10330
10331                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10332                         Ok(key) => key,
10333                         Err(()) => return Err(DecodeError::InvalidValue)
10334                 };
10335                 if let Some(network_pubkey) = received_network_pubkey {
10336                         if network_pubkey != our_network_pubkey {
10337                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10338                                 return Err(DecodeError::InvalidValue);
10339                         }
10340                 }
10341
10342                 let mut outbound_scid_aliases = HashSet::new();
10343                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10344                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10345                         let peer_state = &mut *peer_state_lock;
10346                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10347                                 if let ChannelPhase::Funded(chan) = phase {
10348                                         if chan.context.outbound_scid_alias() == 0 {
10349                                                 let mut outbound_scid_alias;
10350                                                 loop {
10351                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10352                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10353                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10354                                                 }
10355                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10356                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10357                                                 // Note that in rare cases its possible to hit this while reading an older
10358                                                 // channel if we just happened to pick a colliding outbound alias above.
10359                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10360                                                 return Err(DecodeError::InvalidValue);
10361                                         }
10362                                         if chan.context.is_usable() {
10363                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10364                                                         // Note that in rare cases its possible to hit this while reading an older
10365                                                         // channel if we just happened to pick a colliding outbound alias above.
10366                                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10367                                                         return Err(DecodeError::InvalidValue);
10368                                                 }
10369                                         }
10370                                 } else {
10371                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10372                                         // created in this `channel_by_id` map.
10373                                         debug_assert!(false);
10374                                         return Err(DecodeError::InvalidValue);
10375                                 }
10376                         }
10377                 }
10378
10379                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10380
10381                 for (_, monitor) in args.channel_monitors.iter() {
10382                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10383                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10384                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10385                                         let mut claimable_amt_msat = 0;
10386                                         let mut receiver_node_id = Some(our_network_pubkey);
10387                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
10388                                         if phantom_shared_secret.is_some() {
10389                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
10390                                                         .expect("Failed to get node_id for phantom node recipient");
10391                                                 receiver_node_id = Some(phantom_pubkey)
10392                                         }
10393                                         for claimable_htlc in &payment.htlcs {
10394                                                 claimable_amt_msat += claimable_htlc.value;
10395
10396                                                 // Add a holding-cell claim of the payment to the Channel, which should be
10397                                                 // applied ~immediately on peer reconnection. Because it won't generate a
10398                                                 // new commitment transaction we can just provide the payment preimage to
10399                                                 // the corresponding ChannelMonitor and nothing else.
10400                                                 //
10401                                                 // We do so directly instead of via the normal ChannelMonitor update
10402                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
10403                                                 // we're not allowed to call it directly yet. Further, we do the update
10404                                                 // without incrementing the ChannelMonitor update ID as there isn't any
10405                                                 // reason to.
10406                                                 // If we were to generate a new ChannelMonitor update ID here and then
10407                                                 // crash before the user finishes block connect we'd end up force-closing
10408                                                 // this channel as well. On the flip side, there's no harm in restarting
10409                                                 // without the new monitor persisted - we'll end up right back here on
10410                                                 // restart.
10411                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
10412                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
10413                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
10414                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10415                                                         let peer_state = &mut *peer_state_lock;
10416                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
10417                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
10418                                                         }
10419                                                 }
10420                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
10421                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
10422                                                 }
10423                                         }
10424                                         pending_events_read.push_back((events::Event::PaymentClaimed {
10425                                                 receiver_node_id,
10426                                                 payment_hash,
10427                                                 purpose: payment.purpose,
10428                                                 amount_msat: claimable_amt_msat,
10429                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
10430                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
10431                                         }, None));
10432                                 }
10433                         }
10434                 }
10435
10436                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
10437                         if let Some(peer_state) = per_peer_state.get(&node_id) {
10438                                 for (_, actions) in monitor_update_blocked_actions.iter() {
10439                                         for action in actions.iter() {
10440                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
10441                                                         downstream_counterparty_and_funding_outpoint:
10442                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
10443                                                 } = action {
10444                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
10445                                                                 log_trace!(args.logger,
10446                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
10447                                                                         blocked_channel_outpoint.to_channel_id());
10448                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
10449                                                                         .entry(blocked_channel_outpoint.to_channel_id())
10450                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
10451                                                         } else {
10452                                                                 // If the channel we were blocking has closed, we don't need to
10453                                                                 // worry about it - the blocked monitor update should never have
10454                                                                 // been released from the `Channel` object so it can't have
10455                                                                 // completed, and if the channel closed there's no reason to bother
10456                                                                 // anymore.
10457                                                         }
10458                                                 }
10459                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
10460                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
10461                                                 }
10462                                         }
10463                                 }
10464                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
10465                         } else {
10466                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
10467                                 return Err(DecodeError::InvalidValue);
10468                         }
10469                 }
10470
10471                 let channel_manager = ChannelManager {
10472                         chain_hash,
10473                         fee_estimator: bounded_fee_estimator,
10474                         chain_monitor: args.chain_monitor,
10475                         tx_broadcaster: args.tx_broadcaster,
10476                         router: args.router,
10477
10478                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
10479
10480                         inbound_payment_key: expanded_inbound_key,
10481                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
10482                         pending_outbound_payments: pending_outbounds,
10483                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
10484
10485                         forward_htlcs: Mutex::new(forward_htlcs),
10486                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
10487                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
10488                         id_to_peer: Mutex::new(id_to_peer),
10489                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
10490                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
10491
10492                         probing_cookie_secret: probing_cookie_secret.unwrap(),
10493
10494                         our_network_pubkey,
10495                         secp_ctx,
10496
10497                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
10498
10499                         per_peer_state: FairRwLock::new(per_peer_state),
10500
10501                         pending_events: Mutex::new(pending_events_read),
10502                         pending_events_processor: AtomicBool::new(false),
10503                         pending_background_events: Mutex::new(pending_background_events),
10504                         total_consistency_lock: RwLock::new(()),
10505                         background_events_processed_since_startup: AtomicBool::new(false),
10506
10507                         event_persist_notifier: Notifier::new(),
10508                         needs_persist_flag: AtomicBool::new(false),
10509
10510                         funding_batch_states: Mutex::new(BTreeMap::new()),
10511
10512                         pending_offers_messages: Mutex::new(Vec::new()),
10513
10514                         entropy_source: args.entropy_source,
10515                         node_signer: args.node_signer,
10516                         signer_provider: args.signer_provider,
10517
10518                         logger: args.logger,
10519                         default_configuration: args.default_config,
10520                 };
10521
10522                 for htlc_source in failed_htlcs.drain(..) {
10523                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
10524                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
10525                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
10526                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
10527                 }
10528
10529                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
10530                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
10531                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
10532                         // channel is closed we just assume that it probably came from an on-chain claim.
10533                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
10534                                 downstream_closed, true, downstream_node_id, downstream_funding);
10535                 }
10536
10537                 //TODO: Broadcast channel update for closed channels, but only after we've made a
10538                 //connection or two.
10539
10540                 Ok((best_block_hash.clone(), channel_manager))
10541         }
10542 }
10543
10544 #[cfg(test)]
10545 mod tests {
10546         use bitcoin::hashes::Hash;
10547         use bitcoin::hashes::sha256::Hash as Sha256;
10548         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10549         use core::sync::atomic::Ordering;
10550         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
10551         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
10552         use crate::ln::ChannelId;
10553         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
10554         use crate::ln::functional_test_utils::*;
10555         use crate::ln::msgs::{self, ErrorAction};
10556         use crate::ln::msgs::ChannelMessageHandler;
10557         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
10558         use crate::util::errors::APIError;
10559         use crate::util::test_utils;
10560         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
10561         use crate::sign::EntropySource;
10562
10563         #[test]
10564         fn test_notify_limits() {
10565                 // Check that a few cases which don't require the persistence of a new ChannelManager,
10566                 // indeed, do not cause the persistence of a new ChannelManager.
10567                 let chanmon_cfgs = create_chanmon_cfgs(3);
10568                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10569                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10570                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10571
10572                 // All nodes start with a persistable update pending as `create_network` connects each node
10573                 // with all other nodes to make most tests simpler.
10574                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10575                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10576                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10577
10578                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10579
10580                 // We check that the channel info nodes have doesn't change too early, even though we try
10581                 // to connect messages with new values
10582                 chan.0.contents.fee_base_msat *= 2;
10583                 chan.1.contents.fee_base_msat *= 2;
10584                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
10585                         &nodes[1].node.get_our_node_id()).pop().unwrap();
10586                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
10587                         &nodes[0].node.get_our_node_id()).pop().unwrap();
10588
10589                 // The first two nodes (which opened a channel) should now require fresh persistence
10590                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10591                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10592                 // ... but the last node should not.
10593                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10594                 // After persisting the first two nodes they should no longer need fresh persistence.
10595                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10596                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10597
10598                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
10599                 // about the channel.
10600                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
10601                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
10602                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10603
10604                 // The nodes which are a party to the channel should also ignore messages from unrelated
10605                 // parties.
10606                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10607                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10608                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10609                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10610                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10611                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10612
10613                 // At this point the channel info given by peers should still be the same.
10614                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10615                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10616
10617                 // An earlier version of handle_channel_update didn't check the directionality of the
10618                 // update message and would always update the local fee info, even if our peer was
10619                 // (spuriously) forwarding us our own channel_update.
10620                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
10621                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
10622                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
10623
10624                 // First deliver each peers' own message, checking that the node doesn't need to be
10625                 // persisted and that its channel info remains the same.
10626                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
10627                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
10628                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10629                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10630                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10631                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10632
10633                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
10634                 // the channel info has updated.
10635                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
10636                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
10637                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10638                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10639                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
10640                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
10641         }
10642
10643         #[test]
10644         fn test_keysend_dup_hash_partial_mpp() {
10645                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
10646                 // expected.
10647                 let chanmon_cfgs = create_chanmon_cfgs(2);
10648                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10649                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10650                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10651                 create_announced_chan_between_nodes(&nodes, 0, 1);
10652
10653                 // First, send a partial MPP payment.
10654                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
10655                 let mut mpp_route = route.clone();
10656                 mpp_route.paths.push(mpp_route.paths[0].clone());
10657
10658                 let payment_id = PaymentId([42; 32]);
10659                 // Use the utility function send_payment_along_path to send the payment with MPP data which
10660                 // indicates there are more HTLCs coming.
10661                 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.
10662                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
10663                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
10664                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
10665                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
10666                 check_added_monitors!(nodes[0], 1);
10667                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10668                 assert_eq!(events.len(), 1);
10669                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10670
10671                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
10672                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10673                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10674                 check_added_monitors!(nodes[0], 1);
10675                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10676                 assert_eq!(events.len(), 1);
10677                 let ev = events.drain(..).next().unwrap();
10678                 let payment_event = SendEvent::from_event(ev);
10679                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10680                 check_added_monitors!(nodes[1], 0);
10681                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10682                 expect_pending_htlcs_forwardable!(nodes[1]);
10683                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
10684                 check_added_monitors!(nodes[1], 1);
10685                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10686                 assert!(updates.update_add_htlcs.is_empty());
10687                 assert!(updates.update_fulfill_htlcs.is_empty());
10688                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10689                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10690                 assert!(updates.update_fee.is_none());
10691                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10692                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10693                 expect_payment_failed!(nodes[0], our_payment_hash, true);
10694
10695                 // Send the second half of the original MPP payment.
10696                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
10697                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
10698                 check_added_monitors!(nodes[0], 1);
10699                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10700                 assert_eq!(events.len(), 1);
10701                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
10702
10703                 // Claim the full MPP payment. Note that we can't use a test utility like
10704                 // claim_funds_along_route because the ordering of the messages causes the second half of the
10705                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
10706                 // lightning messages manually.
10707                 nodes[1].node.claim_funds(payment_preimage);
10708                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
10709                 check_added_monitors!(nodes[1], 2);
10710
10711                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10712                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
10713                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
10714                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
10715                 check_added_monitors!(nodes[0], 1);
10716                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10717                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
10718                 check_added_monitors!(nodes[1], 1);
10719                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10720                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
10721                 check_added_monitors!(nodes[1], 1);
10722                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10723                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
10724                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
10725                 check_added_monitors!(nodes[0], 1);
10726                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10727                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
10728                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10729                 check_added_monitors!(nodes[0], 1);
10730                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
10731                 check_added_monitors!(nodes[1], 1);
10732                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
10733                 check_added_monitors!(nodes[1], 1);
10734                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10735                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
10736                 check_added_monitors!(nodes[0], 1);
10737
10738                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
10739                 // path's success and a PaymentPathSuccessful event for each path's success.
10740                 let events = nodes[0].node.get_and_clear_pending_events();
10741                 assert_eq!(events.len(), 2);
10742                 match events[0] {
10743                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10744                                 assert_eq!(payment_id, *actual_payment_id);
10745                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10746                                 assert_eq!(route.paths[0], *path);
10747                         },
10748                         _ => panic!("Unexpected event"),
10749                 }
10750                 match events[1] {
10751                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10752                                 assert_eq!(payment_id, *actual_payment_id);
10753                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10754                                 assert_eq!(route.paths[0], *path);
10755                         },
10756                         _ => panic!("Unexpected event"),
10757                 }
10758         }
10759
10760         #[test]
10761         fn test_keysend_dup_payment_hash() {
10762                 do_test_keysend_dup_payment_hash(false);
10763                 do_test_keysend_dup_payment_hash(true);
10764         }
10765
10766         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
10767                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
10768                 //      outbound regular payment fails as expected.
10769                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
10770                 //      fails as expected.
10771                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
10772                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
10773                 //      reject MPP keysend payments, since in this case where the payment has no payment
10774                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
10775                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
10776                 //      payment secrets and reject otherwise.
10777                 let chanmon_cfgs = create_chanmon_cfgs(2);
10778                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10779                 let mut mpp_keysend_cfg = test_default_channel_config();
10780                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
10781                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
10782                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10783                 create_announced_chan_between_nodes(&nodes, 0, 1);
10784                 let scorer = test_utils::TestScorer::new();
10785                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10786
10787                 // To start (1), send a regular payment but don't claim it.
10788                 let expected_route = [&nodes[1]];
10789                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
10790
10791                 // Next, attempt a keysend payment and make sure it fails.
10792                 let route_params = RouteParameters::from_payment_params_and_value(
10793                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
10794                         TEST_FINAL_CLTV, false), 100_000);
10795                 let route = find_route(
10796                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10797                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10798                 ).unwrap();
10799                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10800                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10801                 check_added_monitors!(nodes[0], 1);
10802                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10803                 assert_eq!(events.len(), 1);
10804                 let ev = events.drain(..).next().unwrap();
10805                 let payment_event = SendEvent::from_event(ev);
10806                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10807                 check_added_monitors!(nodes[1], 0);
10808                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10809                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
10810                 // fails), the second will process the resulting failure and fail the HTLC backward
10811                 expect_pending_htlcs_forwardable!(nodes[1]);
10812                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10813                 check_added_monitors!(nodes[1], 1);
10814                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10815                 assert!(updates.update_add_htlcs.is_empty());
10816                 assert!(updates.update_fulfill_htlcs.is_empty());
10817                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10818                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10819                 assert!(updates.update_fee.is_none());
10820                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10821                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10822                 expect_payment_failed!(nodes[0], payment_hash, true);
10823
10824                 // Finally, claim the original payment.
10825                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10826
10827                 // To start (2), send a keysend payment but don't claim it.
10828                 let payment_preimage = PaymentPreimage([42; 32]);
10829                 let route = find_route(
10830                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10831                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10832                 ).unwrap();
10833                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10834                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10835                 check_added_monitors!(nodes[0], 1);
10836                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10837                 assert_eq!(events.len(), 1);
10838                 let event = events.pop().unwrap();
10839                 let path = vec![&nodes[1]];
10840                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10841
10842                 // Next, attempt a regular payment and make sure it fails.
10843                 let payment_secret = PaymentSecret([43; 32]);
10844                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10845                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10846                 check_added_monitors!(nodes[0], 1);
10847                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10848                 assert_eq!(events.len(), 1);
10849                 let ev = events.drain(..).next().unwrap();
10850                 let payment_event = SendEvent::from_event(ev);
10851                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10852                 check_added_monitors!(nodes[1], 0);
10853                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10854                 expect_pending_htlcs_forwardable!(nodes[1]);
10855                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10856                 check_added_monitors!(nodes[1], 1);
10857                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10858                 assert!(updates.update_add_htlcs.is_empty());
10859                 assert!(updates.update_fulfill_htlcs.is_empty());
10860                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10861                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10862                 assert!(updates.update_fee.is_none());
10863                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10864                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10865                 expect_payment_failed!(nodes[0], payment_hash, true);
10866
10867                 // Finally, succeed the keysend payment.
10868                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10869
10870                 // To start (3), send a keysend payment but don't claim it.
10871                 let payment_id_1 = PaymentId([44; 32]);
10872                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10873                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
10874                 check_added_monitors!(nodes[0], 1);
10875                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10876                 assert_eq!(events.len(), 1);
10877                 let event = events.pop().unwrap();
10878                 let path = vec![&nodes[1]];
10879                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10880
10881                 // Next, attempt a keysend payment and make sure it fails.
10882                 let route_params = RouteParameters::from_payment_params_and_value(
10883                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
10884                         100_000
10885                 );
10886                 let route = find_route(
10887                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10888                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10889                 ).unwrap();
10890                 let payment_id_2 = PaymentId([45; 32]);
10891                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10892                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
10893                 check_added_monitors!(nodes[0], 1);
10894                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10895                 assert_eq!(events.len(), 1);
10896                 let ev = events.drain(..).next().unwrap();
10897                 let payment_event = SendEvent::from_event(ev);
10898                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10899                 check_added_monitors!(nodes[1], 0);
10900                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10901                 expect_pending_htlcs_forwardable!(nodes[1]);
10902                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10903                 check_added_monitors!(nodes[1], 1);
10904                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10905                 assert!(updates.update_add_htlcs.is_empty());
10906                 assert!(updates.update_fulfill_htlcs.is_empty());
10907                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10908                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10909                 assert!(updates.update_fee.is_none());
10910                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10911                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10912                 expect_payment_failed!(nodes[0], payment_hash, true);
10913
10914                 // Finally, claim the original payment.
10915                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10916         }
10917
10918         #[test]
10919         fn test_keysend_hash_mismatch() {
10920                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
10921                 // preimage doesn't match the msg's payment hash.
10922                 let chanmon_cfgs = create_chanmon_cfgs(2);
10923                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10924                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10925                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10926
10927                 let payer_pubkey = nodes[0].node.get_our_node_id();
10928                 let payee_pubkey = nodes[1].node.get_our_node_id();
10929
10930                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10931                 let route_params = RouteParameters::from_payment_params_and_value(
10932                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10933                 let network_graph = nodes[0].network_graph.clone();
10934                 let first_hops = nodes[0].node.list_usable_channels();
10935                 let scorer = test_utils::TestScorer::new();
10936                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10937                 let route = find_route(
10938                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10939                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10940                 ).unwrap();
10941
10942                 let test_preimage = PaymentPreimage([42; 32]);
10943                 let mismatch_payment_hash = PaymentHash([43; 32]);
10944                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
10945                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
10946                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
10947                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
10948                 check_added_monitors!(nodes[0], 1);
10949
10950                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10951                 assert_eq!(updates.update_add_htlcs.len(), 1);
10952                 assert!(updates.update_fulfill_htlcs.is_empty());
10953                 assert!(updates.update_fail_htlcs.is_empty());
10954                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10955                 assert!(updates.update_fee.is_none());
10956                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
10957
10958                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
10959         }
10960
10961         #[test]
10962         fn test_keysend_msg_with_secret_err() {
10963                 // Test that we error as expected if we receive a keysend payment that includes a payment
10964                 // secret when we don't support MPP keysend.
10965                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
10966                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
10967                 let chanmon_cfgs = create_chanmon_cfgs(2);
10968                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10969                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
10970                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10971
10972                 let payer_pubkey = nodes[0].node.get_our_node_id();
10973                 let payee_pubkey = nodes[1].node.get_our_node_id();
10974
10975                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10976                 let route_params = RouteParameters::from_payment_params_and_value(
10977                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10978                 let network_graph = nodes[0].network_graph.clone();
10979                 let first_hops = nodes[0].node.list_usable_channels();
10980                 let scorer = test_utils::TestScorer::new();
10981                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10982                 let route = find_route(
10983                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10984                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10985                 ).unwrap();
10986
10987                 let test_preimage = PaymentPreimage([42; 32]);
10988                 let test_secret = PaymentSecret([43; 32]);
10989                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
10990                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
10991                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
10992                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
10993                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
10994                         PaymentId(payment_hash.0), None, session_privs).unwrap();
10995                 check_added_monitors!(nodes[0], 1);
10996
10997                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10998                 assert_eq!(updates.update_add_htlcs.len(), 1);
10999                 assert!(updates.update_fulfill_htlcs.is_empty());
11000                 assert!(updates.update_fail_htlcs.is_empty());
11001                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11002                 assert!(updates.update_fee.is_none());
11003                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11004
11005                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11006         }
11007
11008         #[test]
11009         fn test_multi_hop_missing_secret() {
11010                 let chanmon_cfgs = create_chanmon_cfgs(4);
11011                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11012                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11013                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11014
11015                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11016                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11017                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11018                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11019
11020                 // Marshall an MPP route.
11021                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11022                 let path = route.paths[0].clone();
11023                 route.paths.push(path);
11024                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11025                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11026                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11027                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11028                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11029                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11030
11031                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11032                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11033                 .unwrap_err() {
11034                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11035                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11036                         },
11037                         _ => panic!("unexpected error")
11038                 }
11039         }
11040
11041         #[test]
11042         fn test_drop_disconnected_peers_when_removing_channels() {
11043                 let chanmon_cfgs = create_chanmon_cfgs(2);
11044                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11045                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11046                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11047
11048                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11049
11050                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11051                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11052
11053                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11054                 check_closed_broadcast!(nodes[0], true);
11055                 check_added_monitors!(nodes[0], 1);
11056                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11057
11058                 {
11059                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11060                         // disconnected and the channel between has been force closed.
11061                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11062                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11063                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11064                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11065                 }
11066
11067                 nodes[0].node.timer_tick_occurred();
11068
11069                 {
11070                         // Assert that nodes[1] has now been removed.
11071                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11072                 }
11073         }
11074
11075         #[test]
11076         fn bad_inbound_payment_hash() {
11077                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11078                 let chanmon_cfgs = create_chanmon_cfgs(2);
11079                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11080                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11081                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11082
11083                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11084                 let payment_data = msgs::FinalOnionHopData {
11085                         payment_secret,
11086                         total_msat: 100_000,
11087                 };
11088
11089                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11090                 // payment verification fails as expected.
11091                 let mut bad_payment_hash = payment_hash.clone();
11092                 bad_payment_hash.0[0] += 1;
11093                 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) {
11094                         Ok(_) => panic!("Unexpected ok"),
11095                         Err(()) => {
11096                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11097                         }
11098                 }
11099
11100                 // Check that using the original payment hash succeeds.
11101                 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());
11102         }
11103
11104         #[test]
11105         fn test_id_to_peer_coverage() {
11106                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
11107                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11108                 // the channel is successfully closed.
11109                 let chanmon_cfgs = create_chanmon_cfgs(2);
11110                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11111                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11112                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11113
11114                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
11115                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11116                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11117                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11118                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11119
11120                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11121                 let channel_id = ChannelId::from_bytes(tx.txid().into_inner());
11122                 {
11123                         // Ensure that the `id_to_peer` map is empty until either party has received the
11124                         // funding transaction, and have the real `channel_id`.
11125                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11126                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11127                 }
11128
11129                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11130                 {
11131                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
11132                         // as it has the funding transaction.
11133                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11134                         assert_eq!(nodes_0_lock.len(), 1);
11135                         assert!(nodes_0_lock.contains_key(&channel_id));
11136                 }
11137
11138                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11139
11140                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11141
11142                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11143                 {
11144                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11145                         assert_eq!(nodes_0_lock.len(), 1);
11146                         assert!(nodes_0_lock.contains_key(&channel_id));
11147                 }
11148                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11149
11150                 {
11151                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
11152                         // as it has the funding transaction.
11153                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11154                         assert_eq!(nodes_1_lock.len(), 1);
11155                         assert!(nodes_1_lock.contains_key(&channel_id));
11156                 }
11157                 check_added_monitors!(nodes[1], 1);
11158                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11159                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11160                 check_added_monitors!(nodes[0], 1);
11161                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11162                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11163                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11164                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11165
11166                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11167                 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()));
11168                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11169                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11170
11171                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11172                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11173                 {
11174                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
11175                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11176                         // fee for the closing transaction has been negotiated and the parties has the other
11177                         // party's signature for the fee negotiated closing transaction.)
11178                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11179                         assert_eq!(nodes_0_lock.len(), 1);
11180                         assert!(nodes_0_lock.contains_key(&channel_id));
11181                 }
11182
11183                 {
11184                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11185                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11186                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11187                         // kept in the `nodes[1]`'s `id_to_peer` map.
11188                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11189                         assert_eq!(nodes_1_lock.len(), 1);
11190                         assert!(nodes_1_lock.contains_key(&channel_id));
11191                 }
11192
11193                 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()));
11194                 {
11195                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11196                         // therefore has all it needs to fully close the channel (both signatures for the
11197                         // closing transaction).
11198                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
11199                         // fully closed by `nodes[0]`.
11200                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11201
11202                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
11203                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11204                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11205                         assert_eq!(nodes_1_lock.len(), 1);
11206                         assert!(nodes_1_lock.contains_key(&channel_id));
11207                 }
11208
11209                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11210
11211                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11212                 {
11213                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
11214                         // they both have everything required to fully close the channel.
11215                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11216                 }
11217                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11218
11219                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11220                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11221         }
11222
11223         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11224                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11225                 check_api_error_message(expected_message, res_err)
11226         }
11227
11228         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11229                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11230                 check_api_error_message(expected_message, res_err)
11231         }
11232
11233         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11234                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11235                 check_api_error_message(expected_message, res_err)
11236         }
11237
11238         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11239                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11240                 check_api_error_message(expected_message, res_err)
11241         }
11242
11243         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11244                 match res_err {
11245                         Err(APIError::APIMisuseError { err }) => {
11246                                 assert_eq!(err, expected_err_message);
11247                         },
11248                         Err(APIError::ChannelUnavailable { err }) => {
11249                                 assert_eq!(err, expected_err_message);
11250                         },
11251                         Ok(_) => panic!("Unexpected Ok"),
11252                         Err(_) => panic!("Unexpected Error"),
11253                 }
11254         }
11255
11256         #[test]
11257         fn test_api_calls_with_unkown_counterparty_node() {
11258                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11259                 // expected if the `counterparty_node_id` is an unkown peer in the
11260                 // `ChannelManager::per_peer_state` map.
11261                 let chanmon_cfg = create_chanmon_cfgs(2);
11262                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11263                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11264                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11265
11266                 // Dummy values
11267                 let channel_id = ChannelId::from_bytes([4; 32]);
11268                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11269                 let intercept_id = InterceptId([0; 32]);
11270
11271                 // Test the API functions.
11272                 check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None), unkown_public_key);
11273
11274                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11275
11276                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11277
11278                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11279
11280                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11281
11282                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11283
11284                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11285         }
11286
11287         #[test]
11288         fn test_api_calls_with_unavailable_channel() {
11289                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11290                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11291                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11292                 // the given `channel_id`.
11293                 let chanmon_cfg = create_chanmon_cfgs(2);
11294                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11295                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11296                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11297
11298                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11299
11300                 // Dummy values
11301                 let channel_id = ChannelId::from_bytes([4; 32]);
11302
11303                 // Test the API functions.
11304                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11305
11306                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11307
11308                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11309
11310                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11311
11312                 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);
11313
11314                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11315         }
11316
11317         #[test]
11318         fn test_connection_limiting() {
11319                 // Test that we limit un-channel'd peers and un-funded channels properly.
11320                 let chanmon_cfgs = create_chanmon_cfgs(2);
11321                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11322                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11323                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11324
11325                 // Note that create_network connects the nodes together for us
11326
11327                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11328                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11329
11330                 let mut funding_tx = None;
11331                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11332                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11333                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11334
11335                         if idx == 0 {
11336                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11337                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11338                                 funding_tx = Some(tx.clone());
11339                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11340                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11341
11342                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11343                                 check_added_monitors!(nodes[1], 1);
11344                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11345
11346                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11347
11348                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11349                                 check_added_monitors!(nodes[0], 1);
11350                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11351                         }
11352                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11353                 }
11354
11355                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11356                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11357                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11358                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11359                         open_channel_msg.temporary_channel_id);
11360
11361                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11362                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11363                 // limit.
11364                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11365                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11366                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11367                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11368                         peer_pks.push(random_pk);
11369                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11370                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11371                         }, true).unwrap();
11372                 }
11373                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11374                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11375                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11376                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11377                 }, true).unwrap_err();
11378
11379                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11380                 // them if we have too many un-channel'd peers.
11381                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11382                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11383                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
11384                 for ev in chan_closed_events {
11385                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
11386                 }
11387                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11388                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11389                 }, true).unwrap();
11390                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11391                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11392                 }, true).unwrap_err();
11393
11394                 // but of course if the connection is outbound its allowed...
11395                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11396                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11397                 }, false).unwrap();
11398                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11399
11400                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
11401                 // Even though we accept one more connection from new peers, we won't actually let them
11402                 // open channels.
11403                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
11404                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11405                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
11406                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
11407                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11408                 }
11409                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11410                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11411                         open_channel_msg.temporary_channel_id);
11412
11413                 // Of course, however, outbound channels are always allowed
11414                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
11415                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
11416
11417                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
11418                 // "protected" and can connect again.
11419                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
11420                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11421                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11422                 }, true).unwrap();
11423                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
11424
11425                 // Further, because the first channel was funded, we can open another channel with
11426                 // last_random_pk.
11427                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11428                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11429         }
11430
11431         #[test]
11432         fn test_outbound_chans_unlimited() {
11433                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
11434                 let chanmon_cfgs = create_chanmon_cfgs(2);
11435                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11436                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11437                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11438
11439                 // Note that create_network connects the nodes together for us
11440
11441                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11442                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11443
11444                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11445                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11446                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11447                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11448                 }
11449
11450                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
11451                 // rejected.
11452                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11453                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11454                         open_channel_msg.temporary_channel_id);
11455
11456                 // but we can still open an outbound channel.
11457                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11458                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
11459
11460                 // but even with such an outbound channel, additional inbound channels will still fail.
11461                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11462                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11463                         open_channel_msg.temporary_channel_id);
11464         }
11465
11466         #[test]
11467         fn test_0conf_limiting() {
11468                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11469                 // flag set and (sometimes) accept channels as 0conf.
11470                 let chanmon_cfgs = create_chanmon_cfgs(2);
11471                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11472                 let mut settings = test_default_channel_config();
11473                 settings.manually_accept_inbound_channels = true;
11474                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
11475                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11476
11477                 // Note that create_network connects the nodes together for us
11478
11479                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11480                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11481
11482                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
11483                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11484                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11485                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11486                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11487                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11488                         }, true).unwrap();
11489
11490                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
11491                         let events = nodes[1].node.get_and_clear_pending_events();
11492                         match events[0] {
11493                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11494                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
11495                                 }
11496                                 _ => panic!("Unexpected event"),
11497                         }
11498                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
11499                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11500                 }
11501
11502                 // If we try to accept a channel from another peer non-0conf it will fail.
11503                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11504                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11505                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11506                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11507                 }, true).unwrap();
11508                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11509                 let events = nodes[1].node.get_and_clear_pending_events();
11510                 match events[0] {
11511                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11512                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
11513                                         Err(APIError::APIMisuseError { err }) =>
11514                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
11515                                         _ => panic!(),
11516                                 }
11517                         }
11518                         _ => panic!("Unexpected event"),
11519                 }
11520                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11521                         open_channel_msg.temporary_channel_id);
11522
11523                 // ...however if we accept the same channel 0conf it should work just fine.
11524                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11525                 let events = nodes[1].node.get_and_clear_pending_events();
11526                 match events[0] {
11527                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11528                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
11529                         }
11530                         _ => panic!("Unexpected event"),
11531                 }
11532                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11533         }
11534
11535         #[test]
11536         fn reject_excessively_underpaying_htlcs() {
11537                 let chanmon_cfg = create_chanmon_cfgs(1);
11538                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11539                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11540                 let node = create_network(1, &node_cfg, &node_chanmgr);
11541                 let sender_intended_amt_msat = 100;
11542                 let extra_fee_msat = 10;
11543                 let hop_data = msgs::InboundOnionPayload::Receive {
11544                         amt_msat: 100,
11545                         outgoing_cltv_value: 42,
11546                         payment_metadata: None,
11547                         keysend_preimage: None,
11548                         payment_data: Some(msgs::FinalOnionHopData {
11549                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11550                         }),
11551                         custom_tlvs: Vec::new(),
11552                 };
11553                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
11554                 // intended amount, we fail the payment.
11555                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
11556                         node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11557                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat))
11558                 {
11559                         assert_eq!(err_code, 19);
11560                 } else { panic!(); }
11561
11562                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
11563                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
11564                         amt_msat: 100,
11565                         outgoing_cltv_value: 42,
11566                         payment_metadata: None,
11567                         keysend_preimage: None,
11568                         payment_data: Some(msgs::FinalOnionHopData {
11569                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11570                         }),
11571                         custom_tlvs: Vec::new(),
11572                 };
11573                 assert!(node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11574                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat)).is_ok());
11575         }
11576
11577         #[test]
11578         fn test_final_incorrect_cltv(){
11579                 let chanmon_cfg = create_chanmon_cfgs(1);
11580                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11581                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11582                 let node = create_network(1, &node_cfg, &node_chanmgr);
11583
11584                 let result = node[0].node.construct_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
11585                         amt_msat: 100,
11586                         outgoing_cltv_value: 22,
11587                         payment_metadata: None,
11588                         keysend_preimage: None,
11589                         payment_data: Some(msgs::FinalOnionHopData {
11590                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
11591                         }),
11592                         custom_tlvs: Vec::new(),
11593                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None);
11594
11595                 // Should not return an error as this condition:
11596                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
11597                 // is not satisfied.
11598                 assert!(result.is_ok());
11599         }
11600
11601         #[test]
11602         fn test_inbound_anchors_manual_acceptance() {
11603                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11604                 // flag set and (sometimes) accept channels as 0conf.
11605                 let mut anchors_cfg = test_default_channel_config();
11606                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11607
11608                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
11609                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
11610
11611                 let chanmon_cfgs = create_chanmon_cfgs(3);
11612                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11613                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
11614                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
11615                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11616
11617                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11618                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11619
11620                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11621                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11622                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
11623                 match &msg_events[0] {
11624                         MessageSendEvent::HandleError { node_id, action } => {
11625                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
11626                                 match action {
11627                                         ErrorAction::SendErrorMessage { msg } =>
11628                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
11629                                         _ => panic!("Unexpected error action"),
11630                                 }
11631                         }
11632                         _ => panic!("Unexpected event"),
11633                 }
11634
11635                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11636                 let events = nodes[2].node.get_and_clear_pending_events();
11637                 match events[0] {
11638                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
11639                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
11640                         _ => panic!("Unexpected event"),
11641                 }
11642                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11643         }
11644
11645         #[test]
11646         fn test_anchors_zero_fee_htlc_tx_fallback() {
11647                 // Tests that if both nodes support anchors, but the remote node does not want to accept
11648                 // anchor channels at the moment, an error it sent to the local node such that it can retry
11649                 // the channel without the anchors feature.
11650                 let chanmon_cfgs = create_chanmon_cfgs(2);
11651                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11652                 let mut anchors_config = test_default_channel_config();
11653                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11654                 anchors_config.manually_accept_inbound_channels = true;
11655                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
11656                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11657
11658                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
11659                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11660                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
11661
11662                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11663                 let events = nodes[1].node.get_and_clear_pending_events();
11664                 match events[0] {
11665                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11666                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
11667                         }
11668                         _ => panic!("Unexpected event"),
11669                 }
11670
11671                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
11672                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
11673
11674                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11675                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
11676
11677                 // Since nodes[1] should not have accepted the channel, it should
11678                 // not have generated any events.
11679                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11680         }
11681
11682         #[test]
11683         fn test_update_channel_config() {
11684                 let chanmon_cfg = create_chanmon_cfgs(2);
11685                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11686                 let mut user_config = test_default_channel_config();
11687                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11688                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11689                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
11690                 let channel = &nodes[0].node.list_channels()[0];
11691
11692                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11693                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11694                 assert_eq!(events.len(), 0);
11695
11696                 user_config.channel_config.forwarding_fee_base_msat += 10;
11697                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11698                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
11699                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11700                 assert_eq!(events.len(), 1);
11701                 match &events[0] {
11702                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11703                         _ => panic!("expected BroadcastChannelUpdate event"),
11704                 }
11705
11706                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
11707                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11708                 assert_eq!(events.len(), 0);
11709
11710                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
11711                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11712                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
11713                         ..Default::default()
11714                 }).unwrap();
11715                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11716                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11717                 assert_eq!(events.len(), 1);
11718                 match &events[0] {
11719                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11720                         _ => panic!("expected BroadcastChannelUpdate event"),
11721                 }
11722
11723                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
11724                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11725                         forwarding_fee_proportional_millionths: Some(new_fee),
11726                         ..Default::default()
11727                 }).unwrap();
11728                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11729                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
11730                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11731                 assert_eq!(events.len(), 1);
11732                 match &events[0] {
11733                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11734                         _ => panic!("expected BroadcastChannelUpdate event"),
11735                 }
11736
11737                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
11738                 // should be applied to ensure update atomicity as specified in the API docs.
11739                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
11740                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
11741                 let new_fee = current_fee + 100;
11742                 assert!(
11743                         matches!(
11744                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
11745                                         forwarding_fee_proportional_millionths: Some(new_fee),
11746                                         ..Default::default()
11747                                 }),
11748                                 Err(APIError::ChannelUnavailable { err: _ }),
11749                         )
11750                 );
11751                 // Check that the fee hasn't changed for the channel that exists.
11752                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
11753                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11754                 assert_eq!(events.len(), 0);
11755         }
11756
11757         #[test]
11758         fn test_payment_display() {
11759                 let payment_id = PaymentId([42; 32]);
11760                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11761                 let payment_hash = PaymentHash([42; 32]);
11762                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11763                 let payment_preimage = PaymentPreimage([42; 32]);
11764                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11765         }
11766
11767         #[test]
11768         fn test_trigger_lnd_force_close() {
11769                 let chanmon_cfg = create_chanmon_cfgs(2);
11770                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11771                 let user_config = test_default_channel_config();
11772                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11773                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11774
11775                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
11776                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
11777                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11778                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11779                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
11780                 check_closed_broadcast(&nodes[0], 1, true);
11781                 check_added_monitors(&nodes[0], 1);
11782                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11783                 {
11784                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
11785                         assert_eq!(txn.len(), 1);
11786                         check_spends!(txn[0], funding_tx);
11787                 }
11788
11789                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
11790                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
11791                 // their side.
11792                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
11793                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
11794                 }, true).unwrap();
11795                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11796                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11797                 }, false).unwrap();
11798                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
11799                 let channel_reestablish = get_event_msg!(
11800                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
11801                 );
11802                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
11803
11804                 // Alice should respond with an error since the channel isn't known, but a bogus
11805                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
11806                 // close even if it was an lnd node.
11807                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
11808                 assert_eq!(msg_events.len(), 2);
11809                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
11810                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
11811                         assert_eq!(msg.next_local_commitment_number, 0);
11812                         assert_eq!(msg.next_remote_commitment_number, 0);
11813                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
11814                 } else { panic!() };
11815                 check_closed_broadcast(&nodes[1], 1, true);
11816                 check_added_monitors(&nodes[1], 1);
11817                 let expected_close_reason = ClosureReason::ProcessingError {
11818                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
11819                 };
11820                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
11821                 {
11822                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
11823                         assert_eq!(txn.len(), 1);
11824                         check_spends!(txn[0], funding_tx);
11825                 }
11826         }
11827 }
11828
11829 #[cfg(ldk_bench)]
11830 pub mod bench {
11831         use crate::chain::Listen;
11832         use crate::chain::chainmonitor::{ChainMonitor, Persist};
11833         use crate::sign::{KeysManager, InMemorySigner};
11834         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
11835         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
11836         use crate::ln::functional_test_utils::*;
11837         use crate::ln::msgs::{ChannelMessageHandler, Init};
11838         use crate::routing::gossip::NetworkGraph;
11839         use crate::routing::router::{PaymentParameters, RouteParameters};
11840         use crate::util::test_utils;
11841         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
11842
11843         use bitcoin::hashes::Hash;
11844         use bitcoin::hashes::sha256::Hash as Sha256;
11845         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
11846
11847         use crate::sync::{Arc, Mutex, RwLock};
11848
11849         use criterion::Criterion;
11850
11851         type Manager<'a, P> = ChannelManager<
11852                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
11853                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
11854                         &'a test_utils::TestLogger, &'a P>,
11855                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
11856                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
11857                 &'a test_utils::TestLogger>;
11858
11859         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
11860                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
11861         }
11862         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
11863                 type CM = Manager<'chan_mon_cfg, P>;
11864                 #[inline]
11865                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
11866                 #[inline]
11867                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
11868         }
11869
11870         pub fn bench_sends(bench: &mut Criterion) {
11871                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
11872         }
11873
11874         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
11875                 // Do a simple benchmark of sending a payment back and forth between two nodes.
11876                 // Note that this is unrealistic as each payment send will require at least two fsync
11877                 // calls per node.
11878                 let network = bitcoin::Network::Testnet;
11879                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
11880
11881                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
11882                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
11883                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
11884                 let scorer = RwLock::new(test_utils::TestScorer::new());
11885                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
11886
11887                 let mut config: UserConfig = Default::default();
11888                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
11889                 config.channel_handshake_config.minimum_depth = 1;
11890
11891                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
11892                 let seed_a = [1u8; 32];
11893                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
11894                 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 {
11895                         network,
11896                         best_block: BestBlock::from_network(network),
11897                 }, genesis_block.header.time);
11898                 let node_a_holder = ANodeHolder { node: &node_a };
11899
11900                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
11901                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
11902                 let seed_b = [2u8; 32];
11903                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
11904                 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 {
11905                         network,
11906                         best_block: BestBlock::from_network(network),
11907                 }, genesis_block.header.time);
11908                 let node_b_holder = ANodeHolder { node: &node_b };
11909
11910                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
11911                         features: node_b.init_features(), networks: None, remote_network_address: None
11912                 }, true).unwrap();
11913                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
11914                         features: node_a.init_features(), networks: None, remote_network_address: None
11915                 }, false).unwrap();
11916                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
11917                 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()));
11918                 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()));
11919
11920                 let tx;
11921                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
11922                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
11923                                 value: 8_000_000, script_pubkey: output_script,
11924                         }]};
11925                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
11926                 } else { panic!(); }
11927
11928                 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()));
11929                 let events_b = node_b.get_and_clear_pending_events();
11930                 assert_eq!(events_b.len(), 1);
11931                 match events_b[0] {
11932                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11933                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11934                         },
11935                         _ => panic!("Unexpected event"),
11936                 }
11937
11938                 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()));
11939                 let events_a = node_a.get_and_clear_pending_events();
11940                 assert_eq!(events_a.len(), 1);
11941                 match events_a[0] {
11942                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11943                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11944                         },
11945                         _ => panic!("Unexpected event"),
11946                 }
11947
11948                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
11949
11950                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
11951                 Listen::block_connected(&node_a, &block, 1);
11952                 Listen::block_connected(&node_b, &block, 1);
11953
11954                 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()));
11955                 let msg_events = node_a.get_and_clear_pending_msg_events();
11956                 assert_eq!(msg_events.len(), 2);
11957                 match msg_events[0] {
11958                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
11959                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
11960                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
11961                         },
11962                         _ => panic!(),
11963                 }
11964                 match msg_events[1] {
11965                         MessageSendEvent::SendChannelUpdate { .. } => {},
11966                         _ => panic!(),
11967                 }
11968
11969                 let events_a = node_a.get_and_clear_pending_events();
11970                 assert_eq!(events_a.len(), 1);
11971                 match events_a[0] {
11972                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11973                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11974                         },
11975                         _ => panic!("Unexpected event"),
11976                 }
11977
11978                 let events_b = node_b.get_and_clear_pending_events();
11979                 assert_eq!(events_b.len(), 1);
11980                 match events_b[0] {
11981                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11982                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11983                         },
11984                         _ => panic!("Unexpected event"),
11985                 }
11986
11987                 let mut payment_count: u64 = 0;
11988                 macro_rules! send_payment {
11989                         ($node_a: expr, $node_b: expr) => {
11990                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
11991                                         .with_bolt11_features($node_b.invoice_features()).unwrap();
11992                                 let mut payment_preimage = PaymentPreimage([0; 32]);
11993                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
11994                                 payment_count += 1;
11995                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
11996                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
11997
11998                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
11999                                         PaymentId(payment_hash.0),
12000                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12001                                         Retry::Attempts(0)).unwrap();
12002                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12003                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12004                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12005                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12006                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12007                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12008                                 $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()));
12009
12010                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12011                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12012                                 $node_b.claim_funds(payment_preimage);
12013                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12014
12015                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12016                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12017                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12018                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12019                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12020                                         },
12021                                         _ => panic!("Failed to generate claim event"),
12022                                 }
12023
12024                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12025                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12026                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12027                                 $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()));
12028
12029                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12030                         }
12031                 }
12032
12033                 bench.bench_function(bench_name, |b| b.iter(|| {
12034                         send_payment!(node_a, node_b);
12035                         send_payment!(node_b, node_a);
12036                 }));
12037         }
12038 }