74fef11e9132c65e05818d07874baa33952d7f53
[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::chain;
35 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
36 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
37 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};
38 use crate::chain::transaction::{OutPoint, TransactionData};
39 use crate::events;
40 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
41 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
42 // construct one themselves.
43 use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
44 use crate::ln::channel::{Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel};
45 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
46 #[cfg(any(feature = "_test_utils", test))]
47 use crate::ln::features::Bolt11InvoiceFeatures;
48 use crate::routing::gossip::NetworkGraph;
49 use crate::routing::router::{BlindedTail, DefaultRouter, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
50 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
51 use crate::ln::msgs;
52 use crate::ln::onion_utils;
53 use crate::ln::onion_utils::HTLCFailReason;
54 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
55 #[cfg(test)]
56 use crate::ln::outbound_payment;
57 use crate::ln::outbound_payment::{OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs, StaleExpiration};
58 use crate::ln::wire::Encode;
59 use crate::offers::offer::{DerivedMetadata, OfferBuilder};
60 use crate::offers::parse::Bolt12SemanticError;
61 use crate::offers::refund::RefundBuilder;
62 use crate::onion_message::{OffersMessage, PendingOnionMessage};
63 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, WriteableEcdsaChannelSigner};
64 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
65 use crate::util::wakers::{Future, Notifier};
66 use crate::util::scid_utils::fake_scid;
67 use crate::util::string::UntrustedString;
68 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
69 use crate::util::logger::{Level, Logger};
70 use crate::util::errors::APIError;
71
72 use alloc::collections::{btree_map, BTreeMap};
73
74 use crate::io;
75 use crate::prelude::*;
76 use core::{cmp, mem};
77 use core::cell::RefCell;
78 use crate::io::Read;
79 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
80 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
81 use core::time::Duration;
82 use core::ops::Deref;
83
84 // Re-export this for use in the public API.
85 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
86 use crate::ln::script::ShutdownScript;
87
88 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
89 //
90 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
91 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
92 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
93 //
94 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
95 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
96 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
97 // before we forward it.
98 //
99 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
100 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
101 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
102 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
103 // our payment, which we can use to decode errors or inform the user that the payment was sent.
104
105 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
106 pub(super) enum PendingHTLCRouting {
107         Forward {
108                 onion_packet: msgs::OnionPacket,
109                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
110                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
111                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
112         },
113         Receive {
114                 payment_data: msgs::FinalOnionHopData,
115                 payment_metadata: Option<Vec<u8>>,
116                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
117                 phantom_shared_secret: Option<[u8; 32]>,
118                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
119                 custom_tlvs: Vec<(u64, Vec<u8>)>,
120         },
121         ReceiveKeysend {
122                 /// This was added in 0.0.116 and will break deserialization on downgrades.
123                 payment_data: Option<msgs::FinalOnionHopData>,
124                 payment_preimage: PaymentPreimage,
125                 payment_metadata: Option<Vec<u8>>,
126                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
127                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
128                 custom_tlvs: Vec<(u64, Vec<u8>)>,
129         },
130 }
131
132 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
133 pub(super) struct PendingHTLCInfo {
134         pub(super) routing: PendingHTLCRouting,
135         pub(super) incoming_shared_secret: [u8; 32],
136         payment_hash: PaymentHash,
137         /// Amount received
138         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
139         /// Sender intended amount to forward or receive (actual amount received
140         /// may overshoot this in either case)
141         pub(super) outgoing_amt_msat: u64,
142         pub(super) outgoing_cltv_value: u32,
143         /// The fee being skimmed off the top of this HTLC. If this is a forward, it'll be the fee we are
144         /// skimming. If we're receiving this HTLC, it's the fee that our counterparty skimmed.
145         pub(super) skimmed_fee_msat: Option<u64>,
146 }
147
148 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
149 pub(super) enum HTLCFailureMsg {
150         Relay(msgs::UpdateFailHTLC),
151         Malformed(msgs::UpdateFailMalformedHTLC),
152 }
153
154 /// Stores whether we can't forward an HTLC or relevant forwarding info
155 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
156 pub(super) enum PendingHTLCStatus {
157         Forward(PendingHTLCInfo),
158         Fail(HTLCFailureMsg),
159 }
160
161 pub(super) struct PendingAddHTLCInfo {
162         pub(super) forward_info: PendingHTLCInfo,
163
164         // These fields are produced in `forward_htlcs()` and consumed in
165         // `process_pending_htlc_forwards()` for constructing the
166         // `HTLCSource::PreviousHopData` for failed and forwarded
167         // HTLCs.
168         //
169         // Note that this may be an outbound SCID alias for the associated channel.
170         prev_short_channel_id: u64,
171         prev_htlc_id: u64,
172         prev_funding_outpoint: OutPoint,
173         prev_user_channel_id: u128,
174 }
175
176 pub(super) enum HTLCForwardInfo {
177         AddHTLC(PendingAddHTLCInfo),
178         FailHTLC {
179                 htlc_id: u64,
180                 err_packet: msgs::OnionErrorPacket,
181         },
182 }
183
184 /// Tracks the inbound corresponding to an outbound HTLC
185 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
186 pub(crate) struct HTLCPreviousHopData {
187         // Note that this may be an outbound SCID alias for the associated channel.
188         short_channel_id: u64,
189         user_channel_id: Option<u128>,
190         htlc_id: u64,
191         incoming_packet_shared_secret: [u8; 32],
192         phantom_shared_secret: Option<[u8; 32]>,
193
194         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
195         // channel with a preimage provided by the forward channel.
196         outpoint: OutPoint,
197 }
198
199 enum OnionPayload {
200         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
201         Invoice {
202                 /// This is only here for backwards-compatibility in serialization, in the future it can be
203                 /// removed, breaking clients running 0.0.106 and earlier.
204                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
205         },
206         /// Contains the payer-provided preimage.
207         Spontaneous(PaymentPreimage),
208 }
209
210 /// HTLCs that are to us and can be failed/claimed by the user
211 struct ClaimableHTLC {
212         prev_hop: HTLCPreviousHopData,
213         cltv_expiry: u32,
214         /// The amount (in msats) of this MPP part
215         value: u64,
216         /// The amount (in msats) that the sender intended to be sent in this MPP
217         /// part (used for validating total MPP amount)
218         sender_intended_value: u64,
219         onion_payload: OnionPayload,
220         timer_ticks: u8,
221         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
222         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
223         total_value_received: Option<u64>,
224         /// The sender intended sum total of all MPP parts specified in the onion
225         total_msat: u64,
226         /// The extra fee our counterparty skimmed off the top of this HTLC.
227         counterparty_skimmed_fee_msat: Option<u64>,
228 }
229
230 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
231         fn from(val: &ClaimableHTLC) -> Self {
232                 events::ClaimedHTLC {
233                         channel_id: val.prev_hop.outpoint.to_channel_id(),
234                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
235                         cltv_expiry: val.cltv_expiry,
236                         value_msat: val.value,
237                 }
238         }
239 }
240
241 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
242 /// a payment and ensure idempotency in LDK.
243 ///
244 /// This is not exported to bindings users as we just use [u8; 32] directly
245 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
246 pub struct PaymentId(pub [u8; Self::LENGTH]);
247
248 impl PaymentId {
249         /// Number of bytes in the id.
250         pub const LENGTH: usize = 32;
251 }
252
253 impl Writeable for PaymentId {
254         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
255                 self.0.write(w)
256         }
257 }
258
259 impl Readable for PaymentId {
260         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
261                 let buf: [u8; 32] = Readable::read(r)?;
262                 Ok(PaymentId(buf))
263         }
264 }
265
266 impl core::fmt::Display for PaymentId {
267         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
268                 crate::util::logger::DebugBytes(&self.0).fmt(f)
269         }
270 }
271
272 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
273 ///
274 /// This is not exported to bindings users as we just use [u8; 32] directly
275 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
276 pub struct InterceptId(pub [u8; 32]);
277
278 impl Writeable for InterceptId {
279         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
280                 self.0.write(w)
281         }
282 }
283
284 impl Readable for InterceptId {
285         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
286                 let buf: [u8; 32] = Readable::read(r)?;
287                 Ok(InterceptId(buf))
288         }
289 }
290
291 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
292 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
293 pub(crate) enum SentHTLCId {
294         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
295         OutboundRoute { session_priv: SecretKey },
296 }
297 impl SentHTLCId {
298         pub(crate) fn from_source(source: &HTLCSource) -> Self {
299                 match source {
300                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
301                                 short_channel_id: hop_data.short_channel_id,
302                                 htlc_id: hop_data.htlc_id,
303                         },
304                         HTLCSource::OutboundRoute { session_priv, .. } =>
305                                 Self::OutboundRoute { session_priv: *session_priv },
306                 }
307         }
308 }
309 impl_writeable_tlv_based_enum!(SentHTLCId,
310         (0, PreviousHopData) => {
311                 (0, short_channel_id, required),
312                 (2, htlc_id, required),
313         },
314         (2, OutboundRoute) => {
315                 (0, session_priv, required),
316         };
317 );
318
319
320 /// Tracks the inbound corresponding to an outbound HTLC
321 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
322 #[derive(Clone, Debug, PartialEq, Eq)]
323 pub(crate) enum HTLCSource {
324         PreviousHopData(HTLCPreviousHopData),
325         OutboundRoute {
326                 path: Path,
327                 session_priv: SecretKey,
328                 /// Technically we can recalculate this from the route, but we cache it here to avoid
329                 /// doing a double-pass on route when we get a failure back
330                 first_hop_htlc_msat: u64,
331                 payment_id: PaymentId,
332         },
333 }
334 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
335 impl core::hash::Hash for HTLCSource {
336         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
337                 match self {
338                         HTLCSource::PreviousHopData(prev_hop_data) => {
339                                 0u8.hash(hasher);
340                                 prev_hop_data.hash(hasher);
341                         },
342                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
343                                 1u8.hash(hasher);
344                                 path.hash(hasher);
345                                 session_priv[..].hash(hasher);
346                                 payment_id.hash(hasher);
347                                 first_hop_htlc_msat.hash(hasher);
348                         },
349                 }
350         }
351 }
352 impl HTLCSource {
353         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
354         #[cfg(test)]
355         pub fn dummy() -> Self {
356                 HTLCSource::OutboundRoute {
357                         path: Path { hops: Vec::new(), blinded_tail: None },
358                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
359                         first_hop_htlc_msat: 0,
360                         payment_id: PaymentId([2; 32]),
361                 }
362         }
363
364         #[cfg(debug_assertions)]
365         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
366         /// transaction. Useful to ensure different datastructures match up.
367         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
368                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
369                         *first_hop_htlc_msat == htlc.amount_msat
370                 } else {
371                         // There's nothing we can check for forwarded HTLCs
372                         true
373                 }
374         }
375 }
376
377 struct InboundOnionErr {
378         err_code: u16,
379         err_data: Vec<u8>,
380         msg: &'static str,
381 }
382
383 /// This enum is used to specify which error data to send to peers when failing back an HTLC
384 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
385 ///
386 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
387 #[derive(Clone, Copy)]
388 pub enum FailureCode {
389         /// We had a temporary error processing the payment. Useful if no other error codes fit
390         /// and you want to indicate that the payer may want to retry.
391         TemporaryNodeFailure,
392         /// We have a required feature which was not in this onion. For example, you may require
393         /// some additional metadata that was not provided with this payment.
394         RequiredNodeFeatureMissing,
395         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
396         /// the HTLC is too close to the current block height for safe handling.
397         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
398         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
399         IncorrectOrUnknownPaymentDetails,
400         /// We failed to process the payload after the onion was decrypted. You may wish to
401         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
402         ///
403         /// If available, the tuple data may include the type number and byte offset in the
404         /// decrypted byte stream where the failure occurred.
405         InvalidOnionPayload(Option<(u64, u16)>),
406 }
407
408 impl Into<u16> for FailureCode {
409     fn into(self) -> u16 {
410                 match self {
411                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
412                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
413                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
414                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
415                 }
416         }
417 }
418
419 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
420 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
421 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
422 /// peer_state lock. We then return the set of things that need to be done outside the lock in
423 /// this struct and call handle_error!() on it.
424
425 struct MsgHandleErrInternal {
426         err: msgs::LightningError,
427         chan_id: Option<(ChannelId, u128)>, // If Some a channel of ours has been closed
428         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
429         channel_capacity: Option<u64>,
430 }
431 impl MsgHandleErrInternal {
432         #[inline]
433         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
434                 Self {
435                         err: LightningError {
436                                 err: err.clone(),
437                                 action: msgs::ErrorAction::SendErrorMessage {
438                                         msg: msgs::ErrorMessage {
439                                                 channel_id,
440                                                 data: err
441                                         },
442                                 },
443                         },
444                         chan_id: None,
445                         shutdown_finish: None,
446                         channel_capacity: None,
447                 }
448         }
449         #[inline]
450         fn from_no_close(err: msgs::LightningError) -> Self {
451                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
452         }
453         #[inline]
454         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 {
455                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
456                 let action = if let (Some(_), ..) = &shutdown_res {
457                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
458                         // should disconnect our peer such that we force them to broadcast their latest
459                         // commitment upon reconnecting.
460                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
461                 } else {
462                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
463                 };
464                 Self {
465                         err: LightningError { err, action },
466                         chan_id: Some((channel_id, user_channel_id)),
467                         shutdown_finish: Some((shutdown_res, channel_update)),
468                         channel_capacity: Some(channel_capacity)
469                 }
470         }
471         #[inline]
472         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
473                 Self {
474                         err: match err {
475                                 ChannelError::Warn(msg) =>  LightningError {
476                                         err: msg.clone(),
477                                         action: msgs::ErrorAction::SendWarningMessage {
478                                                 msg: msgs::WarningMessage {
479                                                         channel_id,
480                                                         data: msg
481                                                 },
482                                                 log_level: Level::Warn,
483                                         },
484                                 },
485                                 ChannelError::Ignore(msg) => LightningError {
486                                         err: msg,
487                                         action: msgs::ErrorAction::IgnoreError,
488                                 },
489                                 ChannelError::Close(msg) => LightningError {
490                                         err: msg.clone(),
491                                         action: msgs::ErrorAction::SendErrorMessage {
492                                                 msg: msgs::ErrorMessage {
493                                                         channel_id,
494                                                         data: msg
495                                                 },
496                                         },
497                                 },
498                         },
499                         chan_id: None,
500                         shutdown_finish: None,
501                         channel_capacity: None,
502                 }
503         }
504
505         fn closes_channel(&self) -> bool {
506                 self.chan_id.is_some()
507         }
508 }
509
510 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
511 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
512 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
513 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
514 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
515
516 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
517 /// be sent in the order they appear in the return value, however sometimes the order needs to be
518 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
519 /// they were originally sent). In those cases, this enum is also returned.
520 #[derive(Clone, PartialEq)]
521 pub(super) enum RAACommitmentOrder {
522         /// Send the CommitmentUpdate messages first
523         CommitmentFirst,
524         /// Send the RevokeAndACK message first
525         RevokeAndACKFirst,
526 }
527
528 /// Information about a payment which is currently being claimed.
529 struct ClaimingPayment {
530         amount_msat: u64,
531         payment_purpose: events::PaymentPurpose,
532         receiver_node_id: PublicKey,
533         htlcs: Vec<events::ClaimedHTLC>,
534         sender_intended_value: Option<u64>,
535 }
536 impl_writeable_tlv_based!(ClaimingPayment, {
537         (0, amount_msat, required),
538         (2, payment_purpose, required),
539         (4, receiver_node_id, required),
540         (5, htlcs, optional_vec),
541         (7, sender_intended_value, option),
542 });
543
544 struct ClaimablePayment {
545         purpose: events::PaymentPurpose,
546         onion_fields: Option<RecipientOnionFields>,
547         htlcs: Vec<ClaimableHTLC>,
548 }
549
550 /// Information about claimable or being-claimed payments
551 struct ClaimablePayments {
552         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
553         /// failed/claimed by the user.
554         ///
555         /// Note that, no consistency guarantees are made about the channels given here actually
556         /// existing anymore by the time you go to read them!
557         ///
558         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
559         /// we don't get a duplicate payment.
560         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
561
562         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
563         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
564         /// as an [`events::Event::PaymentClaimed`].
565         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
566 }
567
568 /// Events which we process internally but cannot be processed immediately at the generation site
569 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
570 /// running normally, and specifically must be processed before any other non-background
571 /// [`ChannelMonitorUpdate`]s are applied.
572 #[derive(Debug)]
573 enum BackgroundEvent {
574         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
575         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
576         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
577         /// channel has been force-closed we do not need the counterparty node_id.
578         ///
579         /// Note that any such events are lost on shutdown, so in general they must be updates which
580         /// are regenerated on startup.
581         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
582         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
583         /// channel to continue normal operation.
584         ///
585         /// In general this should be used rather than
586         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
587         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
588         /// error the other variant is acceptable.
589         ///
590         /// Note that any such events are lost on shutdown, so in general they must be updates which
591         /// are regenerated on startup.
592         MonitorUpdateRegeneratedOnStartup {
593                 counterparty_node_id: PublicKey,
594                 funding_txo: OutPoint,
595                 update: ChannelMonitorUpdate
596         },
597         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
598         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
599         /// on a channel.
600         MonitorUpdatesComplete {
601                 counterparty_node_id: PublicKey,
602                 channel_id: ChannelId,
603         },
604 }
605
606 #[derive(Debug)]
607 pub(crate) enum MonitorUpdateCompletionAction {
608         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
609         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
610         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
611         /// event can be generated.
612         PaymentClaimed { payment_hash: PaymentHash },
613         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
614         /// operation of another channel.
615         ///
616         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
617         /// from completing a monitor update which removes the payment preimage until the inbound edge
618         /// completes a monitor update containing the payment preimage. In that case, after the inbound
619         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
620         /// outbound edge.
621         EmitEventAndFreeOtherChannel {
622                 event: events::Event,
623                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
624         },
625         /// Indicates we should immediately resume the operation of another channel, unless there is
626         /// some other reason why the channel is blocked. In practice this simply means immediately
627         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
628         ///
629         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
630         /// from completing a monitor update which removes the payment preimage until the inbound edge
631         /// completes a monitor update containing the payment preimage. However, we use this variant
632         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
633         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
634         ///
635         /// This variant should thus never be written to disk, as it is processed inline rather than
636         /// stored for later processing.
637         FreeOtherChannelImmediately {
638                 downstream_counterparty_node_id: PublicKey,
639                 downstream_funding_outpoint: OutPoint,
640                 blocking_action: RAAMonitorUpdateBlockingAction,
641         },
642 }
643
644 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
645         (0, PaymentClaimed) => { (0, payment_hash, required) },
646         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
647         // *immediately*. However, for simplicity we implement read/write here.
648         (1, FreeOtherChannelImmediately) => {
649                 (0, downstream_counterparty_node_id, required),
650                 (2, downstream_funding_outpoint, required),
651                 (4, blocking_action, required),
652         },
653         (2, EmitEventAndFreeOtherChannel) => {
654                 (0, event, upgradable_required),
655                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
656                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
657                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
658                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
659                 // downgrades to prior versions.
660                 (1, downstream_counterparty_and_funding_outpoint, option),
661         },
662 );
663
664 #[derive(Clone, Debug, PartialEq, Eq)]
665 pub(crate) enum EventCompletionAction {
666         ReleaseRAAChannelMonitorUpdate {
667                 counterparty_node_id: PublicKey,
668                 channel_funding_outpoint: OutPoint,
669         },
670 }
671 impl_writeable_tlv_based_enum!(EventCompletionAction,
672         (0, ReleaseRAAChannelMonitorUpdate) => {
673                 (0, channel_funding_outpoint, required),
674                 (2, counterparty_node_id, required),
675         };
676 );
677
678 #[derive(Clone, PartialEq, Eq, Debug)]
679 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
680 /// the blocked action here. See enum variants for more info.
681 pub(crate) enum RAAMonitorUpdateBlockingAction {
682         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
683         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
684         /// durably to disk.
685         ForwardedPaymentInboundClaim {
686                 /// The upstream channel ID (i.e. the inbound edge).
687                 channel_id: ChannelId,
688                 /// The HTLC ID on the inbound edge.
689                 htlc_id: u64,
690         },
691 }
692
693 impl RAAMonitorUpdateBlockingAction {
694         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
695                 Self::ForwardedPaymentInboundClaim {
696                         channel_id: prev_hop.outpoint.to_channel_id(),
697                         htlc_id: prev_hop.htlc_id,
698                 }
699         }
700 }
701
702 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
703         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
704 ;);
705
706
707 /// State we hold per-peer.
708 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
709         /// `channel_id` -> `ChannelPhase`
710         ///
711         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
712         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
713         /// `temporary_channel_id` -> `InboundChannelRequest`.
714         ///
715         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
716         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
717         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
718         /// the channel is rejected, then the entry is simply removed.
719         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
720         /// The latest `InitFeatures` we heard from the peer.
721         latest_features: InitFeatures,
722         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
723         /// for broadcast messages, where ordering isn't as strict).
724         pub(super) pending_msg_events: Vec<MessageSendEvent>,
725         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
726         /// user but which have not yet completed.
727         ///
728         /// Note that the channel may no longer exist. For example if the channel was closed but we
729         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
730         /// for a missing channel.
731         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
732         /// Map from a specific channel to some action(s) that should be taken when all pending
733         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
734         ///
735         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
736         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
737         /// channels with a peer this will just be one allocation and will amount to a linear list of
738         /// channels to walk, avoiding the whole hashing rigmarole.
739         ///
740         /// Note that the channel may no longer exist. For example, if a channel was closed but we
741         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
742         /// for a missing channel. While a malicious peer could construct a second channel with the
743         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
744         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
745         /// duplicates do not occur, so such channels should fail without a monitor update completing.
746         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
747         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
748         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
749         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
750         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
751         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
752         /// The peer is currently connected (i.e. we've seen a
753         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
754         /// [`ChannelMessageHandler::peer_disconnected`].
755         is_connected: bool,
756 }
757
758 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
759         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
760         /// If true is passed for `require_disconnected`, the function will return false if we haven't
761         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
762         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
763                 if require_disconnected && self.is_connected {
764                         return false
765                 }
766                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
767                         && self.monitor_update_blocked_actions.is_empty()
768                         && self.in_flight_monitor_updates.is_empty()
769         }
770
771         // Returns a count of all channels we have with this peer, including unfunded channels.
772         fn total_channel_count(&self) -> usize {
773                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
774         }
775
776         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
777         fn has_channel(&self, channel_id: &ChannelId) -> bool {
778                 self.channel_by_id.contains_key(channel_id) ||
779                         self.inbound_channel_request_by_id.contains_key(channel_id)
780         }
781 }
782
783 /// A not-yet-accepted inbound (from counterparty) channel. Once
784 /// accepted, the parameters will be used to construct a channel.
785 pub(super) struct InboundChannelRequest {
786         /// The original OpenChannel message.
787         pub open_channel_msg: msgs::OpenChannel,
788         /// The number of ticks remaining before the request expires.
789         pub ticks_remaining: i32,
790 }
791
792 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
793 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
794 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
795
796 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
797 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
798 ///
799 /// For users who don't want to bother doing their own payment preimage storage, we also store that
800 /// here.
801 ///
802 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
803 /// and instead encoding it in the payment secret.
804 struct PendingInboundPayment {
805         /// The payment secret that the sender must use for us to accept this payment
806         payment_secret: PaymentSecret,
807         /// Time at which this HTLC expires - blocks with a header time above this value will result in
808         /// this payment being removed.
809         expiry_time: u64,
810         /// Arbitrary identifier the user specifies (or not)
811         user_payment_id: u64,
812         // Other required attributes of the payment, optionally enforced:
813         payment_preimage: Option<PaymentPreimage>,
814         min_value_msat: Option<u64>,
815 }
816
817 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
818 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
819 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
820 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
821 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
822 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
823 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
824 /// of [`KeysManager`] and [`DefaultRouter`].
825 ///
826 /// This is not exported to bindings users as Arcs don't make sense in bindings
827 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
828         Arc<M>,
829         Arc<T>,
830         Arc<KeysManager>,
831         Arc<KeysManager>,
832         Arc<KeysManager>,
833         Arc<F>,
834         Arc<DefaultRouter<
835                 Arc<NetworkGraph<Arc<L>>>,
836                 Arc<L>,
837                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
838                 ProbabilisticScoringFeeParameters,
839                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
840         >>,
841         Arc<L>
842 >;
843
844 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
845 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
846 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
847 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
848 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
849 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
850 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
851 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
852 /// of [`KeysManager`] and [`DefaultRouter`].
853 ///
854 /// This is not exported to bindings users as Arcs don't make sense in bindings
855 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
856         ChannelManager<
857                 &'a M,
858                 &'b T,
859                 &'c KeysManager,
860                 &'c KeysManager,
861                 &'c KeysManager,
862                 &'d F,
863                 &'e DefaultRouter<
864                         &'f NetworkGraph<&'g L>,
865                         &'g L,
866                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
867                         ProbabilisticScoringFeeParameters,
868                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
869                 >,
870                 &'g L
871         >;
872
873 /// A trivial trait which describes any [`ChannelManager`].
874 ///
875 /// This is not exported to bindings users as general cover traits aren't useful in other
876 /// languages.
877 pub trait AChannelManager {
878         /// A type implementing [`chain::Watch`].
879         type Watch: chain::Watch<Self::Signer> + ?Sized;
880         /// A type that may be dereferenced to [`Self::Watch`].
881         type M: Deref<Target = Self::Watch>;
882         /// A type implementing [`BroadcasterInterface`].
883         type Broadcaster: BroadcasterInterface + ?Sized;
884         /// A type that may be dereferenced to [`Self::Broadcaster`].
885         type T: Deref<Target = Self::Broadcaster>;
886         /// A type implementing [`EntropySource`].
887         type EntropySource: EntropySource + ?Sized;
888         /// A type that may be dereferenced to [`Self::EntropySource`].
889         type ES: Deref<Target = Self::EntropySource>;
890         /// A type implementing [`NodeSigner`].
891         type NodeSigner: NodeSigner + ?Sized;
892         /// A type that may be dereferenced to [`Self::NodeSigner`].
893         type NS: Deref<Target = Self::NodeSigner>;
894         /// A type implementing [`WriteableEcdsaChannelSigner`].
895         type Signer: WriteableEcdsaChannelSigner + Sized;
896         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
897         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
898         /// A type that may be dereferenced to [`Self::SignerProvider`].
899         type SP: Deref<Target = Self::SignerProvider>;
900         /// A type implementing [`FeeEstimator`].
901         type FeeEstimator: FeeEstimator + ?Sized;
902         /// A type that may be dereferenced to [`Self::FeeEstimator`].
903         type F: Deref<Target = Self::FeeEstimator>;
904         /// A type implementing [`Router`].
905         type Router: Router + ?Sized;
906         /// A type that may be dereferenced to [`Self::Router`].
907         type R: Deref<Target = Self::Router>;
908         /// A type implementing [`Logger`].
909         type Logger: Logger + ?Sized;
910         /// A type that may be dereferenced to [`Self::Logger`].
911         type L: Deref<Target = Self::Logger>;
912         /// Returns a reference to the actual [`ChannelManager`] object.
913         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
914 }
915
916 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
917 for ChannelManager<M, T, ES, NS, SP, F, R, L>
918 where
919         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
920         T::Target: BroadcasterInterface,
921         ES::Target: EntropySource,
922         NS::Target: NodeSigner,
923         SP::Target: SignerProvider,
924         F::Target: FeeEstimator,
925         R::Target: Router,
926         L::Target: Logger,
927 {
928         type Watch = M::Target;
929         type M = M;
930         type Broadcaster = T::Target;
931         type T = T;
932         type EntropySource = ES::Target;
933         type ES = ES;
934         type NodeSigner = NS::Target;
935         type NS = NS;
936         type Signer = <SP::Target as SignerProvider>::Signer;
937         type SignerProvider = SP::Target;
938         type SP = SP;
939         type FeeEstimator = F::Target;
940         type F = F;
941         type Router = R::Target;
942         type R = R;
943         type Logger = L::Target;
944         type L = L;
945         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
946 }
947
948 /// Manager which keeps track of a number of channels and sends messages to the appropriate
949 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
950 ///
951 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
952 /// to individual Channels.
953 ///
954 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
955 /// all peers during write/read (though does not modify this instance, only the instance being
956 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
957 /// called [`funding_transaction_generated`] for outbound channels) being closed.
958 ///
959 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
960 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
961 /// [`ChannelMonitorUpdate`] before returning from
962 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
963 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
964 /// `ChannelManager` operations from occurring during the serialization process). If the
965 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
966 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
967 /// will be lost (modulo on-chain transaction fees).
968 ///
969 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
970 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
971 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
972 ///
973 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
974 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
975 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
976 /// offline for a full minute. In order to track this, you must call
977 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
978 ///
979 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
980 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
981 /// not have a channel with being unable to connect to us or open new channels with us if we have
982 /// many peers with unfunded channels.
983 ///
984 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
985 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
986 /// never limited. Please ensure you limit the count of such channels yourself.
987 ///
988 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
989 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
990 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
991 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
992 /// you're using lightning-net-tokio.
993 ///
994 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
995 /// [`funding_created`]: msgs::FundingCreated
996 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
997 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
998 /// [`update_channel`]: chain::Watch::update_channel
999 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1000 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1001 /// [`read`]: ReadableArgs::read
1002 //
1003 // Lock order:
1004 // The tree structure below illustrates the lock order requirements for the different locks of the
1005 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1006 // and should then be taken in the order of the lowest to the highest level in the tree.
1007 // Note that locks on different branches shall not be taken at the same time, as doing so will
1008 // create a new lock order for those specific locks in the order they were taken.
1009 //
1010 // Lock order tree:
1011 //
1012 // `pending_offers_messages`
1013 //
1014 // `total_consistency_lock`
1015 //  |
1016 //  |__`forward_htlcs`
1017 //  |   |
1018 //  |   |__`pending_intercepted_htlcs`
1019 //  |
1020 //  |__`per_peer_state`
1021 //      |
1022 //      |__`pending_inbound_payments`
1023 //          |
1024 //          |__`claimable_payments`
1025 //          |
1026 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1027 //              |
1028 //              |__`peer_state`
1029 //                  |
1030 //                  |__`id_to_peer`
1031 //                  |
1032 //                  |__`short_to_chan_info`
1033 //                  |
1034 //                  |__`outbound_scid_aliases`
1035 //                  |
1036 //                  |__`best_block`
1037 //                  |
1038 //                  |__`pending_events`
1039 //                      |
1040 //                      |__`pending_background_events`
1041 //
1042 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1043 where
1044         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1045         T::Target: BroadcasterInterface,
1046         ES::Target: EntropySource,
1047         NS::Target: NodeSigner,
1048         SP::Target: SignerProvider,
1049         F::Target: FeeEstimator,
1050         R::Target: Router,
1051         L::Target: Logger,
1052 {
1053         default_configuration: UserConfig,
1054         chain_hash: ChainHash,
1055         fee_estimator: LowerBoundedFeeEstimator<F>,
1056         chain_monitor: M,
1057         tx_broadcaster: T,
1058         #[allow(unused)]
1059         router: R,
1060
1061         /// See `ChannelManager` struct-level documentation for lock order requirements.
1062         #[cfg(test)]
1063         pub(super) best_block: RwLock<BestBlock>,
1064         #[cfg(not(test))]
1065         best_block: RwLock<BestBlock>,
1066         secp_ctx: Secp256k1<secp256k1::All>,
1067
1068         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1069         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1070         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1071         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1072         ///
1073         /// See `ChannelManager` struct-level documentation for lock order requirements.
1074         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1075
1076         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1077         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1078         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1079         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1080         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1081         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1082         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1083         /// after reloading from disk while replaying blocks against ChannelMonitors.
1084         ///
1085         /// See `PendingOutboundPayment` documentation for more info.
1086         ///
1087         /// See `ChannelManager` struct-level documentation for lock order requirements.
1088         pending_outbound_payments: OutboundPayments,
1089
1090         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1091         ///
1092         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1093         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1094         /// and via the classic SCID.
1095         ///
1096         /// Note that no consistency guarantees are made about the existence of a channel with the
1097         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1098         ///
1099         /// See `ChannelManager` struct-level documentation for lock order requirements.
1100         #[cfg(test)]
1101         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1102         #[cfg(not(test))]
1103         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1104         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1105         /// until the user tells us what we should do with them.
1106         ///
1107         /// See `ChannelManager` struct-level documentation for lock order requirements.
1108         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1109
1110         /// The sets of payments which are claimable or currently being claimed. See
1111         /// [`ClaimablePayments`]' individual field docs for more info.
1112         ///
1113         /// See `ChannelManager` struct-level documentation for lock order requirements.
1114         claimable_payments: Mutex<ClaimablePayments>,
1115
1116         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1117         /// and some closed channels which reached a usable state prior to being closed. This is used
1118         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1119         /// active channel list on load.
1120         ///
1121         /// See `ChannelManager` struct-level documentation for lock order requirements.
1122         outbound_scid_aliases: Mutex<HashSet<u64>>,
1123
1124         /// `channel_id` -> `counterparty_node_id`.
1125         ///
1126         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1127         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1128         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1129         ///
1130         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1131         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1132         /// the handling of the events.
1133         ///
1134         /// Note that no consistency guarantees are made about the existence of a peer with the
1135         /// `counterparty_node_id` in our other maps.
1136         ///
1137         /// TODO:
1138         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1139         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1140         /// would break backwards compatability.
1141         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1142         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1143         /// required to access the channel with the `counterparty_node_id`.
1144         ///
1145         /// See `ChannelManager` struct-level documentation for lock order requirements.
1146         id_to_peer: Mutex<HashMap<ChannelId, PublicKey>>,
1147
1148         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1149         ///
1150         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1151         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1152         /// confirmation depth.
1153         ///
1154         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1155         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1156         /// channel with the `channel_id` in our other maps.
1157         ///
1158         /// See `ChannelManager` struct-level documentation for lock order requirements.
1159         #[cfg(test)]
1160         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1161         #[cfg(not(test))]
1162         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1163
1164         our_network_pubkey: PublicKey,
1165
1166         inbound_payment_key: inbound_payment::ExpandedKey,
1167
1168         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1169         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1170         /// we encrypt the namespace identifier using these bytes.
1171         ///
1172         /// [fake scids]: crate::util::scid_utils::fake_scid
1173         fake_scid_rand_bytes: [u8; 32],
1174
1175         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1176         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1177         /// keeping additional state.
1178         probing_cookie_secret: [u8; 32],
1179
1180         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1181         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1182         /// very far in the past, and can only ever be up to two hours in the future.
1183         highest_seen_timestamp: AtomicUsize,
1184
1185         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1186         /// basis, as well as the peer's latest features.
1187         ///
1188         /// If we are connected to a peer we always at least have an entry here, even if no channels
1189         /// are currently open with that peer.
1190         ///
1191         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1192         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1193         /// channels.
1194         ///
1195         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1196         ///
1197         /// See `ChannelManager` struct-level documentation for lock order requirements.
1198         #[cfg(not(any(test, feature = "_test_utils")))]
1199         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1200         #[cfg(any(test, feature = "_test_utils"))]
1201         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1202
1203         /// The set of events which we need to give to the user to handle. In some cases an event may
1204         /// require some further action after the user handles it (currently only blocking a monitor
1205         /// update from being handed to the user to ensure the included changes to the channel state
1206         /// are handled by the user before they're persisted durably to disk). In that case, the second
1207         /// element in the tuple is set to `Some` with further details of the action.
1208         ///
1209         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1210         /// could be in the middle of being processed without the direct mutex held.
1211         ///
1212         /// See `ChannelManager` struct-level documentation for lock order requirements.
1213         #[cfg(not(any(test, feature = "_test_utils")))]
1214         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1215         #[cfg(any(test, feature = "_test_utils"))]
1216         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1217
1218         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1219         pending_events_processor: AtomicBool,
1220
1221         /// If we are running during init (either directly during the deserialization method or in
1222         /// block connection methods which run after deserialization but before normal operation) we
1223         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1224         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1225         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1226         ///
1227         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1228         ///
1229         /// See `ChannelManager` struct-level documentation for lock order requirements.
1230         ///
1231         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1232         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1233         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1234         /// Essentially just when we're serializing ourselves out.
1235         /// Taken first everywhere where we are making changes before any other locks.
1236         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1237         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1238         /// Notifier the lock contains sends out a notification when the lock is released.
1239         total_consistency_lock: RwLock<()>,
1240         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1241         /// received and the monitor has been persisted.
1242         ///
1243         /// This information does not need to be persisted as funding nodes can forget
1244         /// unfunded channels upon disconnection.
1245         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1246
1247         background_events_processed_since_startup: AtomicBool,
1248
1249         event_persist_notifier: Notifier,
1250         needs_persist_flag: AtomicBool,
1251
1252         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1253
1254         entropy_source: ES,
1255         node_signer: NS,
1256         signer_provider: SP,
1257
1258         logger: L,
1259 }
1260
1261 /// Chain-related parameters used to construct a new `ChannelManager`.
1262 ///
1263 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1264 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1265 /// are not needed when deserializing a previously constructed `ChannelManager`.
1266 #[derive(Clone, Copy, PartialEq)]
1267 pub struct ChainParameters {
1268         /// The network for determining the `chain_hash` in Lightning messages.
1269         pub network: Network,
1270
1271         /// The hash and height of the latest block successfully connected.
1272         ///
1273         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1274         pub best_block: BestBlock,
1275 }
1276
1277 #[derive(Copy, Clone, PartialEq)]
1278 #[must_use]
1279 enum NotifyOption {
1280         DoPersist,
1281         SkipPersistHandleEvents,
1282         SkipPersistNoEvents,
1283 }
1284
1285 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1286 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1287 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1288 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1289 /// sending the aforementioned notification (since the lock being released indicates that the
1290 /// updates are ready for persistence).
1291 ///
1292 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1293 /// notify or not based on whether relevant changes have been made, providing a closure to
1294 /// `optionally_notify` which returns a `NotifyOption`.
1295 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1296         event_persist_notifier: &'a Notifier,
1297         needs_persist_flag: &'a AtomicBool,
1298         should_persist: F,
1299         // We hold onto this result so the lock doesn't get released immediately.
1300         _read_guard: RwLockReadGuard<'a, ()>,
1301 }
1302
1303 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1304         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1305         /// events to handle.
1306         ///
1307         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1308         /// other cases where losing the changes on restart may result in a force-close or otherwise
1309         /// isn't ideal.
1310         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1311                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1312         }
1313
1314         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1315         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1316                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1317                 let force_notify = cm.get_cm().process_background_events();
1318
1319                 PersistenceNotifierGuard {
1320                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1321                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1322                         should_persist: move || {
1323                                 // Pick the "most" action between `persist_check` and the background events
1324                                 // processing and return that.
1325                                 let notify = persist_check();
1326                                 match (notify, force_notify) {
1327                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1328                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1329                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1330                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1331                                         _ => NotifyOption::SkipPersistNoEvents,
1332                                 }
1333                         },
1334                         _read_guard: read_guard,
1335                 }
1336         }
1337
1338         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1339         /// [`ChannelManager::process_background_events`] MUST be called first (or
1340         /// [`Self::optionally_notify`] used).
1341         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1342         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1343                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1344
1345                 PersistenceNotifierGuard {
1346                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1347                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1348                         should_persist: persist_check,
1349                         _read_guard: read_guard,
1350                 }
1351         }
1352 }
1353
1354 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1355         fn drop(&mut self) {
1356                 match (self.should_persist)() {
1357                         NotifyOption::DoPersist => {
1358                                 self.needs_persist_flag.store(true, Ordering::Release);
1359                                 self.event_persist_notifier.notify()
1360                         },
1361                         NotifyOption::SkipPersistHandleEvents =>
1362                                 self.event_persist_notifier.notify(),
1363                         NotifyOption::SkipPersistNoEvents => {},
1364                 }
1365         }
1366 }
1367
1368 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1369 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1370 ///
1371 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1372 ///
1373 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1374 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1375 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1376 /// the maximum required amount in lnd as of March 2021.
1377 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1378
1379 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1380 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1381 ///
1382 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1383 ///
1384 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1385 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1386 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1387 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1388 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1389 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1390 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1391 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1392 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1393 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1394 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1395 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1396 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1397
1398 /// Minimum CLTV difference between the current block height and received inbound payments.
1399 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1400 /// this value.
1401 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1402 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1403 // a payment was being routed, so we add an extra block to be safe.
1404 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1405
1406 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1407 // ie that if the next-hop peer fails the HTLC within
1408 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1409 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1410 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1411 // LATENCY_GRACE_PERIOD_BLOCKS.
1412 #[deny(const_err)]
1413 #[allow(dead_code)]
1414 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;
1415
1416 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1417 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1418 #[deny(const_err)]
1419 #[allow(dead_code)]
1420 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1421
1422 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1423 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1424
1425 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1426 /// until we mark the channel disabled and gossip the update.
1427 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1428
1429 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1430 /// we mark the channel enabled and gossip the update.
1431 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1432
1433 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1434 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1435 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1436 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1437
1438 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1439 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1440 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1441
1442 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1443 /// many peers we reject new (inbound) connections.
1444 const MAX_NO_CHANNEL_PEERS: usize = 250;
1445
1446 /// Information needed for constructing an invoice route hint for this channel.
1447 #[derive(Clone, Debug, PartialEq)]
1448 pub struct CounterpartyForwardingInfo {
1449         /// Base routing fee in millisatoshis.
1450         pub fee_base_msat: u32,
1451         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1452         pub fee_proportional_millionths: u32,
1453         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1454         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1455         /// `cltv_expiry_delta` for more details.
1456         pub cltv_expiry_delta: u16,
1457 }
1458
1459 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1460 /// to better separate parameters.
1461 #[derive(Clone, Debug, PartialEq)]
1462 pub struct ChannelCounterparty {
1463         /// The node_id of our counterparty
1464         pub node_id: PublicKey,
1465         /// The Features the channel counterparty provided upon last connection.
1466         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1467         /// many routing-relevant features are present in the init context.
1468         pub features: InitFeatures,
1469         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1470         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1471         /// claiming at least this value on chain.
1472         ///
1473         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1474         ///
1475         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1476         pub unspendable_punishment_reserve: u64,
1477         /// Information on the fees and requirements that the counterparty requires when forwarding
1478         /// payments to us through this channel.
1479         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1480         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1481         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1482         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1483         pub outbound_htlc_minimum_msat: Option<u64>,
1484         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1485         pub outbound_htlc_maximum_msat: Option<u64>,
1486 }
1487
1488 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1489 #[derive(Clone, Debug, PartialEq)]
1490 pub struct ChannelDetails {
1491         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1492         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1493         /// Note that this means this value is *not* persistent - it can change once during the
1494         /// lifetime of the channel.
1495         pub channel_id: ChannelId,
1496         /// Parameters which apply to our counterparty. See individual fields for more information.
1497         pub counterparty: ChannelCounterparty,
1498         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1499         /// our counterparty already.
1500         ///
1501         /// Note that, if this has been set, `channel_id` will be equivalent to
1502         /// `funding_txo.unwrap().to_channel_id()`.
1503         pub funding_txo: Option<OutPoint>,
1504         /// The features which this channel operates with. See individual features for more info.
1505         ///
1506         /// `None` until negotiation completes and the channel type is finalized.
1507         pub channel_type: Option<ChannelTypeFeatures>,
1508         /// The position of the funding transaction in the chain. None if the funding transaction has
1509         /// not yet been confirmed and the channel fully opened.
1510         ///
1511         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1512         /// payments instead of this. See [`get_inbound_payment_scid`].
1513         ///
1514         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1515         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1516         ///
1517         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1518         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1519         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1520         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1521         /// [`confirmations_required`]: Self::confirmations_required
1522         pub short_channel_id: Option<u64>,
1523         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1524         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1525         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1526         /// `Some(0)`).
1527         ///
1528         /// This will be `None` as long as the channel is not available for routing outbound payments.
1529         ///
1530         /// [`short_channel_id`]: Self::short_channel_id
1531         /// [`confirmations_required`]: Self::confirmations_required
1532         pub outbound_scid_alias: Option<u64>,
1533         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1534         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1535         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1536         /// when they see a payment to be routed to us.
1537         ///
1538         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1539         /// previous values for inbound payment forwarding.
1540         ///
1541         /// [`short_channel_id`]: Self::short_channel_id
1542         pub inbound_scid_alias: Option<u64>,
1543         /// The value, in satoshis, of this channel as appears in the funding output
1544         pub channel_value_satoshis: u64,
1545         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1546         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1547         /// this value on chain.
1548         ///
1549         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1550         ///
1551         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1552         ///
1553         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1554         pub unspendable_punishment_reserve: Option<u64>,
1555         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1556         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1557         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1558         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1559         /// serialized with LDK versions prior to 0.0.113.
1560         ///
1561         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1562         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1563         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1564         pub user_channel_id: u128,
1565         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1566         /// which is applied to commitment and HTLC transactions.
1567         ///
1568         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1569         pub feerate_sat_per_1000_weight: Option<u32>,
1570         /// Our total balance.  This is the amount we would get if we close the channel.
1571         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1572         /// amount is not likely to be recoverable on close.
1573         ///
1574         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1575         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1576         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1577         /// This does not consider any on-chain fees.
1578         ///
1579         /// See also [`ChannelDetails::outbound_capacity_msat`]
1580         pub balance_msat: u64,
1581         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1582         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1583         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1584         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1585         ///
1586         /// See also [`ChannelDetails::balance_msat`]
1587         ///
1588         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1589         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1590         /// should be able to spend nearly this amount.
1591         pub outbound_capacity_msat: u64,
1592         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1593         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1594         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1595         /// to use a limit as close as possible to the HTLC limit we can currently send.
1596         ///
1597         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1598         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1599         pub next_outbound_htlc_limit_msat: u64,
1600         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1601         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1602         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1603         /// route which is valid.
1604         pub next_outbound_htlc_minimum_msat: u64,
1605         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1606         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1607         /// available for inclusion in new inbound HTLCs).
1608         /// Note that there are some corner cases not fully handled here, so the actual available
1609         /// inbound capacity may be slightly higher than this.
1610         ///
1611         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1612         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1613         /// However, our counterparty should be able to spend nearly this amount.
1614         pub inbound_capacity_msat: u64,
1615         /// The number of required confirmations on the funding transaction before the funding will be
1616         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1617         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1618         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1619         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1620         ///
1621         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1622         ///
1623         /// [`is_outbound`]: ChannelDetails::is_outbound
1624         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1625         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1626         pub confirmations_required: Option<u32>,
1627         /// The current number of confirmations on the funding transaction.
1628         ///
1629         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1630         pub confirmations: Option<u32>,
1631         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1632         /// until we can claim our funds after we force-close the channel. During this time our
1633         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1634         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1635         /// time to claim our non-HTLC-encumbered funds.
1636         ///
1637         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1638         pub force_close_spend_delay: Option<u16>,
1639         /// True if the channel was initiated (and thus funded) by us.
1640         pub is_outbound: bool,
1641         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1642         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1643         /// required confirmation count has been reached (and we were connected to the peer at some
1644         /// point after the funding transaction received enough confirmations). The required
1645         /// confirmation count is provided in [`confirmations_required`].
1646         ///
1647         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1648         pub is_channel_ready: bool,
1649         /// The stage of the channel's shutdown.
1650         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1651         pub channel_shutdown_state: Option<ChannelShutdownState>,
1652         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1653         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1654         ///
1655         /// This is a strict superset of `is_channel_ready`.
1656         pub is_usable: bool,
1657         /// True if this channel is (or will be) publicly-announced.
1658         pub is_public: bool,
1659         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1660         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1661         pub inbound_htlc_minimum_msat: Option<u64>,
1662         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1663         pub inbound_htlc_maximum_msat: Option<u64>,
1664         /// Set of configurable parameters that affect channel operation.
1665         ///
1666         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1667         pub config: Option<ChannelConfig>,
1668 }
1669
1670 impl ChannelDetails {
1671         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1672         /// This should be used for providing invoice hints or in any other context where our
1673         /// counterparty will forward a payment to us.
1674         ///
1675         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1676         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1677         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1678                 self.inbound_scid_alias.or(self.short_channel_id)
1679         }
1680
1681         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1682         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1683         /// we're sending or forwarding a payment outbound over this channel.
1684         ///
1685         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1686         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1687         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1688                 self.short_channel_id.or(self.outbound_scid_alias)
1689         }
1690
1691         fn from_channel_context<SP: Deref, F: Deref>(
1692                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1693                 fee_estimator: &LowerBoundedFeeEstimator<F>
1694         ) -> Self
1695         where
1696                 SP::Target: SignerProvider,
1697                 F::Target: FeeEstimator
1698         {
1699                 let balance = context.get_available_balances(fee_estimator);
1700                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1701                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1702                 ChannelDetails {
1703                         channel_id: context.channel_id(),
1704                         counterparty: ChannelCounterparty {
1705                                 node_id: context.get_counterparty_node_id(),
1706                                 features: latest_features,
1707                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1708                                 forwarding_info: context.counterparty_forwarding_info(),
1709                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1710                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1711                                 // message (as they are always the first message from the counterparty).
1712                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1713                                 // default `0` value set by `Channel::new_outbound`.
1714                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1715                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1716                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1717                         },
1718                         funding_txo: context.get_funding_txo(),
1719                         // Note that accept_channel (or open_channel) is always the first message, so
1720                         // `have_received_message` indicates that type negotiation has completed.
1721                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1722                         short_channel_id: context.get_short_channel_id(),
1723                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1724                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1725                         channel_value_satoshis: context.get_value_satoshis(),
1726                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1727                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1728                         balance_msat: balance.balance_msat,
1729                         inbound_capacity_msat: balance.inbound_capacity_msat,
1730                         outbound_capacity_msat: balance.outbound_capacity_msat,
1731                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1732                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1733                         user_channel_id: context.get_user_id(),
1734                         confirmations_required: context.minimum_depth(),
1735                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1736                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1737                         is_outbound: context.is_outbound(),
1738                         is_channel_ready: context.is_usable(),
1739                         is_usable: context.is_live(),
1740                         is_public: context.should_announce(),
1741                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1742                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1743                         config: Some(context.config()),
1744                         channel_shutdown_state: Some(context.shutdown_state()),
1745                 }
1746         }
1747 }
1748
1749 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1750 /// Further information on the details of the channel shutdown.
1751 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1752 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1753 /// the channel will be removed shortly.
1754 /// Also note, that in normal operation, peers could disconnect at any of these states
1755 /// and require peer re-connection before making progress onto other states
1756 pub enum ChannelShutdownState {
1757         /// Channel has not sent or received a shutdown message.
1758         NotShuttingDown,
1759         /// Local node has sent a shutdown message for this channel.
1760         ShutdownInitiated,
1761         /// Shutdown message exchanges have concluded and the channels are in the midst of
1762         /// resolving all existing open HTLCs before closing can continue.
1763         ResolvingHTLCs,
1764         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1765         NegotiatingClosingFee,
1766         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1767         /// to drop the channel.
1768         ShutdownComplete,
1769 }
1770
1771 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1772 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1773 #[derive(Debug, PartialEq)]
1774 pub enum RecentPaymentDetails {
1775         /// When an invoice was requested and thus a payment has not yet been sent.
1776         AwaitingInvoice {
1777                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1778                 /// a payment and ensure idempotency in LDK.
1779                 payment_id: PaymentId,
1780         },
1781         /// When a payment is still being sent and awaiting successful delivery.
1782         Pending {
1783                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1784                 /// a payment and ensure idempotency in LDK.
1785                 payment_id: PaymentId,
1786                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1787                 /// abandoned.
1788                 payment_hash: PaymentHash,
1789                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1790                 /// not just the amount currently inflight.
1791                 total_msat: u64,
1792         },
1793         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1794         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1795         /// payment is removed from tracking.
1796         Fulfilled {
1797                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1798                 /// a payment and ensure idempotency in LDK.
1799                 payment_id: PaymentId,
1800                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1801                 /// made before LDK version 0.0.104.
1802                 payment_hash: Option<PaymentHash>,
1803         },
1804         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1805         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1806         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1807         Abandoned {
1808                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1809                 /// a payment and ensure idempotency in LDK.
1810                 payment_id: PaymentId,
1811                 /// Hash of the payment that we have given up trying to send.
1812                 payment_hash: PaymentHash,
1813         },
1814 }
1815
1816 /// Route hints used in constructing invoices for [phantom node payents].
1817 ///
1818 /// [phantom node payments]: crate::sign::PhantomKeysManager
1819 #[derive(Clone)]
1820 pub struct PhantomRouteHints {
1821         /// The list of channels to be included in the invoice route hints.
1822         pub channels: Vec<ChannelDetails>,
1823         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1824         /// route hints.
1825         pub phantom_scid: u64,
1826         /// The pubkey of the real backing node that would ultimately receive the payment.
1827         pub real_node_pubkey: PublicKey,
1828 }
1829
1830 macro_rules! handle_error {
1831         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1832                 // In testing, ensure there are no deadlocks where the lock is already held upon
1833                 // entering the macro.
1834                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1835                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1836
1837                 match $internal {
1838                         Ok(msg) => Ok(msg),
1839                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1840                                 let mut msg_events = Vec::with_capacity(2);
1841
1842                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1843                                         $self.finish_close_channel(shutdown_res);
1844                                         if let Some(update) = update_option {
1845                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1846                                                         msg: update
1847                                                 });
1848                                         }
1849                                         if let Some((channel_id, user_channel_id)) = chan_id {
1850                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1851                                                         channel_id, user_channel_id,
1852                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1853                                                         counterparty_node_id: Some($counterparty_node_id),
1854                                                         channel_capacity_sats: channel_capacity,
1855                                                 }, None));
1856                                         }
1857                                 }
1858
1859                                 log_error!($self.logger, "{}", err.err);
1860                                 if let msgs::ErrorAction::IgnoreError = err.action {
1861                                 } else {
1862                                         msg_events.push(events::MessageSendEvent::HandleError {
1863                                                 node_id: $counterparty_node_id,
1864                                                 action: err.action.clone()
1865                                         });
1866                                 }
1867
1868                                 if !msg_events.is_empty() {
1869                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1870                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1871                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1872                                                 peer_state.pending_msg_events.append(&mut msg_events);
1873                                         }
1874                                 }
1875
1876                                 // Return error in case higher-API need one
1877                                 Err(err)
1878                         },
1879                 }
1880         } };
1881         ($self: ident, $internal: expr) => {
1882                 match $internal {
1883                         Ok(res) => Ok(res),
1884                         Err((chan, msg_handle_err)) => {
1885                                 let counterparty_node_id = chan.get_counterparty_node_id();
1886                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1887                         },
1888                 }
1889         };
1890 }
1891
1892 macro_rules! update_maps_on_chan_removal {
1893         ($self: expr, $channel_context: expr) => {{
1894                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1895                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1896                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1897                         short_to_chan_info.remove(&short_id);
1898                 } else {
1899                         // If the channel was never confirmed on-chain prior to its closure, remove the
1900                         // outbound SCID alias we used for it from the collision-prevention set. While we
1901                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1902                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1903                         // opening a million channels with us which are closed before we ever reach the funding
1904                         // stage.
1905                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1906                         debug_assert!(alias_removed);
1907                 }
1908                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1909         }}
1910 }
1911
1912 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1913 macro_rules! convert_chan_phase_err {
1914         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
1915                 match $err {
1916                         ChannelError::Warn(msg) => {
1917                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
1918                         },
1919                         ChannelError::Ignore(msg) => {
1920                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
1921                         },
1922                         ChannelError::Close(msg) => {
1923                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
1924                                 update_maps_on_chan_removal!($self, $channel.context);
1925                                 let shutdown_res = $channel.context.force_shutdown(true);
1926                                 let user_id = $channel.context.get_user_id();
1927                                 let channel_capacity_satoshis = $channel.context.get_value_satoshis();
1928
1929                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, user_id,
1930                                         shutdown_res, $channel_update, channel_capacity_satoshis))
1931                         },
1932                 }
1933         };
1934         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
1935                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
1936         };
1937         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
1938                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
1939         };
1940         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
1941                 match $channel_phase {
1942                         ChannelPhase::Funded(channel) => {
1943                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
1944                         },
1945                         ChannelPhase::UnfundedOutboundV1(channel) => {
1946                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1947                         },
1948                         ChannelPhase::UnfundedInboundV1(channel) => {
1949                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1950                         },
1951                 }
1952         };
1953 }
1954
1955 macro_rules! break_chan_phase_entry {
1956         ($self: ident, $res: expr, $entry: expr) => {
1957                 match $res {
1958                         Ok(res) => res,
1959                         Err(e) => {
1960                                 let key = *$entry.key();
1961                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1962                                 if drop {
1963                                         $entry.remove_entry();
1964                                 }
1965                                 break Err(res);
1966                         }
1967                 }
1968         }
1969 }
1970
1971 macro_rules! try_chan_phase_entry {
1972         ($self: ident, $res: expr, $entry: expr) => {
1973                 match $res {
1974                         Ok(res) => res,
1975                         Err(e) => {
1976                                 let key = *$entry.key();
1977                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1978                                 if drop {
1979                                         $entry.remove_entry();
1980                                 }
1981                                 return Err(res);
1982                         }
1983                 }
1984         }
1985 }
1986
1987 macro_rules! remove_channel_phase {
1988         ($self: expr, $entry: expr) => {
1989                 {
1990                         let channel = $entry.remove_entry().1;
1991                         update_maps_on_chan_removal!($self, &channel.context());
1992                         channel
1993                 }
1994         }
1995 }
1996
1997 macro_rules! send_channel_ready {
1998         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1999                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2000                         node_id: $channel.context.get_counterparty_node_id(),
2001                         msg: $channel_ready_msg,
2002                 });
2003                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2004                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2005                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2006                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2007                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2008                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2009                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2010                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2011                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2012                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2013                 }
2014         }}
2015 }
2016
2017 macro_rules! emit_channel_pending_event {
2018         ($locked_events: expr, $channel: expr) => {
2019                 if $channel.context.should_emit_channel_pending_event() {
2020                         $locked_events.push_back((events::Event::ChannelPending {
2021                                 channel_id: $channel.context.channel_id(),
2022                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2023                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2024                                 user_channel_id: $channel.context.get_user_id(),
2025                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2026                         }, None));
2027                         $channel.context.set_channel_pending_event_emitted();
2028                 }
2029         }
2030 }
2031
2032 macro_rules! emit_channel_ready_event {
2033         ($locked_events: expr, $channel: expr) => {
2034                 if $channel.context.should_emit_channel_ready_event() {
2035                         debug_assert!($channel.context.channel_pending_event_emitted());
2036                         $locked_events.push_back((events::Event::ChannelReady {
2037                                 channel_id: $channel.context.channel_id(),
2038                                 user_channel_id: $channel.context.get_user_id(),
2039                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2040                                 channel_type: $channel.context.get_channel_type().clone(),
2041                         }, None));
2042                         $channel.context.set_channel_ready_event_emitted();
2043                 }
2044         }
2045 }
2046
2047 macro_rules! handle_monitor_update_completion {
2048         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2049                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
2050                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2051                         $self.best_block.read().unwrap().height());
2052                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2053                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2054                         // We only send a channel_update in the case where we are just now sending a
2055                         // channel_ready and the channel is in a usable state. We may re-send a
2056                         // channel_update later through the announcement_signatures process for public
2057                         // channels, but there's no reason not to just inform our counterparty of our fees
2058                         // now.
2059                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2060                                 Some(events::MessageSendEvent::SendChannelUpdate {
2061                                         node_id: counterparty_node_id,
2062                                         msg,
2063                                 })
2064                         } else { None }
2065                 } else { None };
2066
2067                 let update_actions = $peer_state.monitor_update_blocked_actions
2068                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2069
2070                 let htlc_forwards = $self.handle_channel_resumption(
2071                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2072                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2073                         updates.funding_broadcastable, updates.channel_ready,
2074                         updates.announcement_sigs);
2075                 if let Some(upd) = channel_update {
2076                         $peer_state.pending_msg_events.push(upd);
2077                 }
2078
2079                 let channel_id = $chan.context.channel_id();
2080                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2081                 core::mem::drop($peer_state_lock);
2082                 core::mem::drop($per_peer_state_lock);
2083
2084                 // If the channel belongs to a batch funding transaction, the progress of the batch
2085                 // should be updated as we have received funding_signed and persisted the monitor.
2086                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2087                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2088                         let mut batch_completed = false;
2089                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2090                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2091                                         *chan_id == channel_id &&
2092                                         *pubkey == counterparty_node_id
2093                                 ));
2094                                 if let Some(channel_state) = channel_state {
2095                                         channel_state.2 = true;
2096                                 } else {
2097                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2098                                 }
2099                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2100                         } else {
2101                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2102                         }
2103
2104                         // When all channels in a batched funding transaction have become ready, it is not necessary
2105                         // to track the progress of the batch anymore and the state of the channels can be updated.
2106                         if batch_completed {
2107                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2108                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2109                                 let mut batch_funding_tx = None;
2110                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2111                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2112                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2113                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2114                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2115                                                         chan.set_batch_ready();
2116                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2117                                                         emit_channel_pending_event!(pending_events, chan);
2118                                                 }
2119                                         }
2120                                 }
2121                                 if let Some(tx) = batch_funding_tx {
2122                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2123                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2124                                 }
2125                         }
2126                 }
2127
2128                 $self.handle_monitor_update_completion_actions(update_actions);
2129
2130                 if let Some(forwards) = htlc_forwards {
2131                         $self.forward_htlcs(&mut [forwards][..]);
2132                 }
2133                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2134                 for failure in updates.failed_htlcs.drain(..) {
2135                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2136                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2137                 }
2138         } }
2139 }
2140
2141 macro_rules! handle_new_monitor_update {
2142         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2143                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2144                 match $update_res {
2145                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2146                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2147                                 log_error!($self.logger, "{}", err_str);
2148                                 panic!("{}", err_str);
2149                         },
2150                         ChannelMonitorUpdateStatus::InProgress => {
2151                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2152                                         &$chan.context.channel_id());
2153                                 false
2154                         },
2155                         ChannelMonitorUpdateStatus::Completed => {
2156                                 $completed;
2157                                 true
2158                         },
2159                 }
2160         } };
2161         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2162                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2163                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2164         };
2165         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2166                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2167                         .or_insert_with(Vec::new);
2168                 // During startup, we push monitor updates as background events through to here in
2169                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2170                 // filter for uniqueness here.
2171                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2172                         .unwrap_or_else(|| {
2173                                 in_flight_updates.push($update);
2174                                 in_flight_updates.len() - 1
2175                         });
2176                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2177                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2178                         {
2179                                 let _ = in_flight_updates.remove(idx);
2180                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2181                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2182                                 }
2183                         })
2184         } };
2185 }
2186
2187 macro_rules! process_events_body {
2188         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2189                 let mut processed_all_events = false;
2190                 while !processed_all_events {
2191                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2192                                 return;
2193                         }
2194
2195                         let mut result;
2196
2197                         {
2198                                 // We'll acquire our total consistency lock so that we can be sure no other
2199                                 // persists happen while processing monitor events.
2200                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2201
2202                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2203                                 // ensure any startup-generated background events are handled first.
2204                                 result = $self.process_background_events();
2205
2206                                 // TODO: This behavior should be documented. It's unintuitive that we query
2207                                 // ChannelMonitors when clearing other events.
2208                                 if $self.process_pending_monitor_events() {
2209                                         result = NotifyOption::DoPersist;
2210                                 }
2211                         }
2212
2213                         let pending_events = $self.pending_events.lock().unwrap().clone();
2214                         let num_events = pending_events.len();
2215                         if !pending_events.is_empty() {
2216                                 result = NotifyOption::DoPersist;
2217                         }
2218
2219                         let mut post_event_actions = Vec::new();
2220
2221                         for (event, action_opt) in pending_events {
2222                                 $event_to_handle = event;
2223                                 $handle_event;
2224                                 if let Some(action) = action_opt {
2225                                         post_event_actions.push(action);
2226                                 }
2227                         }
2228
2229                         {
2230                                 let mut pending_events = $self.pending_events.lock().unwrap();
2231                                 pending_events.drain(..num_events);
2232                                 processed_all_events = pending_events.is_empty();
2233                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2234                                 // updated here with the `pending_events` lock acquired.
2235                                 $self.pending_events_processor.store(false, Ordering::Release);
2236                         }
2237
2238                         if !post_event_actions.is_empty() {
2239                                 $self.handle_post_event_actions(post_event_actions);
2240                                 // If we had some actions, go around again as we may have more events now
2241                                 processed_all_events = false;
2242                         }
2243
2244                         match result {
2245                                 NotifyOption::DoPersist => {
2246                                         $self.needs_persist_flag.store(true, Ordering::Release);
2247                                         $self.event_persist_notifier.notify();
2248                                 },
2249                                 NotifyOption::SkipPersistHandleEvents =>
2250                                         $self.event_persist_notifier.notify(),
2251                                 NotifyOption::SkipPersistNoEvents => {},
2252                         }
2253                 }
2254         }
2255 }
2256
2257 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>
2258 where
2259         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2260         T::Target: BroadcasterInterface,
2261         ES::Target: EntropySource,
2262         NS::Target: NodeSigner,
2263         SP::Target: SignerProvider,
2264         F::Target: FeeEstimator,
2265         R::Target: Router,
2266         L::Target: Logger,
2267 {
2268         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2269         ///
2270         /// The current time or latest block header time can be provided as the `current_timestamp`.
2271         ///
2272         /// This is the main "logic hub" for all channel-related actions, and implements
2273         /// [`ChannelMessageHandler`].
2274         ///
2275         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2276         ///
2277         /// Users need to notify the new `ChannelManager` when a new block is connected or
2278         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2279         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2280         /// more details.
2281         ///
2282         /// [`block_connected`]: chain::Listen::block_connected
2283         /// [`block_disconnected`]: chain::Listen::block_disconnected
2284         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2285         pub fn new(
2286                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2287                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2288                 current_timestamp: u32,
2289         ) -> Self {
2290                 let mut secp_ctx = Secp256k1::new();
2291                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2292                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2293                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2294                 ChannelManager {
2295                         default_configuration: config.clone(),
2296                         chain_hash: ChainHash::using_genesis_block(params.network),
2297                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2298                         chain_monitor,
2299                         tx_broadcaster,
2300                         router,
2301
2302                         best_block: RwLock::new(params.best_block),
2303
2304                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2305                         pending_inbound_payments: Mutex::new(HashMap::new()),
2306                         pending_outbound_payments: OutboundPayments::new(),
2307                         forward_htlcs: Mutex::new(HashMap::new()),
2308                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2309                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2310                         id_to_peer: Mutex::new(HashMap::new()),
2311                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2312
2313                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2314                         secp_ctx,
2315
2316                         inbound_payment_key: expanded_inbound_key,
2317                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2318
2319                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2320
2321                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2322
2323                         per_peer_state: FairRwLock::new(HashMap::new()),
2324
2325                         pending_events: Mutex::new(VecDeque::new()),
2326                         pending_events_processor: AtomicBool::new(false),
2327                         pending_background_events: Mutex::new(Vec::new()),
2328                         total_consistency_lock: RwLock::new(()),
2329                         background_events_processed_since_startup: AtomicBool::new(false),
2330                         event_persist_notifier: Notifier::new(),
2331                         needs_persist_flag: AtomicBool::new(false),
2332                         funding_batch_states: Mutex::new(BTreeMap::new()),
2333
2334                         pending_offers_messages: Mutex::new(Vec::new()),
2335
2336                         entropy_source,
2337                         node_signer,
2338                         signer_provider,
2339
2340                         logger,
2341                 }
2342         }
2343
2344         /// Gets the current configuration applied to all new channels.
2345         pub fn get_current_default_configuration(&self) -> &UserConfig {
2346                 &self.default_configuration
2347         }
2348
2349         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2350                 let height = self.best_block.read().unwrap().height();
2351                 let mut outbound_scid_alias = 0;
2352                 let mut i = 0;
2353                 loop {
2354                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2355                                 outbound_scid_alias += 1;
2356                         } else {
2357                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2358                         }
2359                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2360                                 break;
2361                         }
2362                         i += 1;
2363                         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"); }
2364                 }
2365                 outbound_scid_alias
2366         }
2367
2368         /// Creates a new outbound channel to the given remote node and with the given value.
2369         ///
2370         /// `user_channel_id` will be provided back as in
2371         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2372         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2373         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2374         /// is simply copied to events and otherwise ignored.
2375         ///
2376         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2377         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2378         ///
2379         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2380         /// generate a shutdown scriptpubkey or destination script set by
2381         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2382         ///
2383         /// Note that we do not check if you are currently connected to the given peer. If no
2384         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2385         /// the channel eventually being silently forgotten (dropped on reload).
2386         ///
2387         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2388         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2389         /// [`ChannelDetails::channel_id`] until after
2390         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2391         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2392         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2393         ///
2394         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2395         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2396         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2397         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> {
2398                 if channel_value_satoshis < 1000 {
2399                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2400                 }
2401
2402                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2403                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2404                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2405
2406                 let per_peer_state = self.per_peer_state.read().unwrap();
2407
2408                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2409                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2410
2411                 let mut peer_state = peer_state_mutex.lock().unwrap();
2412                 let channel = {
2413                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2414                         let their_features = &peer_state.latest_features;
2415                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2416                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2417                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2418                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2419                         {
2420                                 Ok(res) => res,
2421                                 Err(e) => {
2422                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2423                                         return Err(e);
2424                                 },
2425                         }
2426                 };
2427                 let res = channel.get_open_channel(self.chain_hash);
2428
2429                 let temporary_channel_id = channel.context.channel_id();
2430                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2431                         hash_map::Entry::Occupied(_) => {
2432                                 if cfg!(fuzzing) {
2433                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2434                                 } else {
2435                                         panic!("RNG is bad???");
2436                                 }
2437                         },
2438                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2439                 }
2440
2441                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2442                         node_id: their_network_key,
2443                         msg: res,
2444                 });
2445                 Ok(temporary_channel_id)
2446         }
2447
2448         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2449                 // Allocate our best estimate of the number of channels we have in the `res`
2450                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2451                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2452                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2453                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2454                 // the same channel.
2455                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2456                 {
2457                         let best_block_height = self.best_block.read().unwrap().height();
2458                         let per_peer_state = self.per_peer_state.read().unwrap();
2459                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2460                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2461                                 let peer_state = &mut *peer_state_lock;
2462                                 res.extend(peer_state.channel_by_id.iter()
2463                                         .filter_map(|(chan_id, phase)| match phase {
2464                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2465                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2466                                                 _ => None,
2467                                         })
2468                                         .filter(f)
2469                                         .map(|(_channel_id, channel)| {
2470                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2471                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2472                                         })
2473                                 );
2474                         }
2475                 }
2476                 res
2477         }
2478
2479         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2480         /// more information.
2481         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2482                 // Allocate our best estimate of the number of channels we have in the `res`
2483                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2484                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2485                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2486                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2487                 // the same channel.
2488                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2489                 {
2490                         let best_block_height = self.best_block.read().unwrap().height();
2491                         let per_peer_state = self.per_peer_state.read().unwrap();
2492                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2493                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2494                                 let peer_state = &mut *peer_state_lock;
2495                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2496                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2497                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2498                                         res.push(details);
2499                                 }
2500                         }
2501                 }
2502                 res
2503         }
2504
2505         /// Gets the list of usable channels, in random order. Useful as an argument to
2506         /// [`Router::find_route`] to ensure non-announced channels are used.
2507         ///
2508         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2509         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2510         /// are.
2511         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2512                 // Note we use is_live here instead of usable which leads to somewhat confused
2513                 // internal/external nomenclature, but that's ok cause that's probably what the user
2514                 // really wanted anyway.
2515                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2516         }
2517
2518         /// Gets the list of channels we have with a given counterparty, in random order.
2519         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2520                 let best_block_height = self.best_block.read().unwrap().height();
2521                 let per_peer_state = self.per_peer_state.read().unwrap();
2522
2523                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2524                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2525                         let peer_state = &mut *peer_state_lock;
2526                         let features = &peer_state.latest_features;
2527                         let context_to_details = |context| {
2528                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2529                         };
2530                         return peer_state.channel_by_id
2531                                 .iter()
2532                                 .map(|(_, phase)| phase.context())
2533                                 .map(context_to_details)
2534                                 .collect();
2535                 }
2536                 vec![]
2537         }
2538
2539         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2540         /// successful path, or have unresolved HTLCs.
2541         ///
2542         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2543         /// result of a crash. If such a payment exists, is not listed here, and an
2544         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2545         ///
2546         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2547         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2548                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2549                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2550                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2551                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2552                                 },
2553                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2554                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2555                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2556                                 },
2557                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2558                                         Some(RecentPaymentDetails::Pending {
2559                                                 payment_id: *payment_id,
2560                                                 payment_hash: *payment_hash,
2561                                                 total_msat: *total_msat,
2562                                         })
2563                                 },
2564                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2565                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2566                                 },
2567                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2568                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2569                                 },
2570                                 PendingOutboundPayment::Legacy { .. } => None
2571                         })
2572                         .collect()
2573         }
2574
2575         /// Helper function that issues the channel close events
2576         fn issue_channel_close_events(&self, context: &ChannelContext<SP>, closure_reason: ClosureReason) {
2577                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2578                 match context.unbroadcasted_funding() {
2579                         Some(transaction) => {
2580                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2581                                         channel_id: context.channel_id(), transaction
2582                                 }, None));
2583                         },
2584                         None => {},
2585                 }
2586                 pending_events_lock.push_back((events::Event::ChannelClosed {
2587                         channel_id: context.channel_id(),
2588                         user_channel_id: context.get_user_id(),
2589                         reason: closure_reason,
2590                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2591                         channel_capacity_sats: Some(context.get_value_satoshis()),
2592                 }, None));
2593         }
2594
2595         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> {
2596                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2597
2598                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2599                 let mut shutdown_result = None;
2600                 loop {
2601                         let per_peer_state = self.per_peer_state.read().unwrap();
2602
2603                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2604                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2605
2606                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2607                         let peer_state = &mut *peer_state_lock;
2608
2609                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2610                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2611                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2612                                                 let funding_txo_opt = chan.context.get_funding_txo();
2613                                                 let their_features = &peer_state.latest_features;
2614                                                 let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
2615                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2616                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2617                                                 failed_htlcs = htlcs;
2618
2619                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2620                                                 // here as we don't need the monitor update to complete until we send a
2621                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2622                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2623                                                         node_id: *counterparty_node_id,
2624                                                         msg: shutdown_msg,
2625                                                 });
2626
2627                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2628                                                         "We can't both complete shutdown and generate a monitor update");
2629
2630                                                 // Update the monitor with the shutdown script if necessary.
2631                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2632                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2633                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2634                                                         break;
2635                                                 }
2636
2637                                                 if chan.is_shutdown() {
2638                                                         if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2639                                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2640                                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2641                                                                                 msg: channel_update
2642                                                                         });
2643                                                                 }
2644                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2645                                                                 shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
2646                                                         }
2647                                                 }
2648                                                 break;
2649                                         }
2650                                 },
2651                                 hash_map::Entry::Vacant(_) => {
2652                                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2653                                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2654                                         //
2655                                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2656                                         mem::drop(peer_state_lock);
2657                                         mem::drop(per_peer_state);
2658                                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2659                                 },
2660                         }
2661                 }
2662
2663                 for htlc_source in failed_htlcs.drain(..) {
2664                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2665                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2666                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2667                 }
2668
2669                 if let Some(shutdown_result) = shutdown_result {
2670                         self.finish_close_channel(shutdown_result);
2671                 }
2672
2673                 Ok(())
2674         }
2675
2676         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2677         /// will be accepted on the given channel, and after additional timeout/the closing of all
2678         /// pending HTLCs, the channel will be closed on chain.
2679         ///
2680         ///  * If we are the channel initiator, we will pay between our [`Background`] and
2681         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2682         ///    estimate.
2683         ///  * If our counterparty is the channel initiator, we will require a channel closing
2684         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
2685         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2686         ///    counterparty to pay as much fee as they'd like, however.
2687         ///
2688         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2689         ///
2690         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2691         /// generate a shutdown scriptpubkey or destination script set by
2692         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2693         /// channel.
2694         ///
2695         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2696         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2697         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2698         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2699         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2700                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2701         }
2702
2703         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2704         /// will be accepted on the given channel, and after additional timeout/the closing of all
2705         /// pending HTLCs, the channel will be closed on chain.
2706         ///
2707         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2708         /// the channel being closed or not:
2709         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2710         ///    transaction. The upper-bound is set by
2711         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2712         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2713         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2714         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2715         ///    will appear on a force-closure transaction, whichever is lower).
2716         ///
2717         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2718         /// Will fail if a shutdown script has already been set for this channel by
2719         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2720         /// also be compatible with our and the counterparty's features.
2721         ///
2722         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2723         ///
2724         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2725         /// generate a shutdown scriptpubkey or destination script set by
2726         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2727         /// channel.
2728         ///
2729         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2730         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2731         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2732         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2733         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> {
2734                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2735         }
2736
2737         fn finish_close_channel(&self, shutdown_res: ShutdownResult) {
2738                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2739                 #[cfg(debug_assertions)]
2740                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2741                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2742                 }
2743
2744                 let (monitor_update_option, mut failed_htlcs, unbroadcasted_batch_funding_txid) = shutdown_res;
2745                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
2746                 for htlc_source in failed_htlcs.drain(..) {
2747                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2748                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2749                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2750                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2751                 }
2752                 if let Some((_, funding_txo, monitor_update)) = monitor_update_option {
2753                         // There isn't anything we can do if we get an update failure - we're already
2754                         // force-closing. The monitor update on the required in-memory copy should broadcast
2755                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2756                         // ignore the result here.
2757                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2758                 }
2759                 let mut shutdown_results = Vec::new();
2760                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2761                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2762                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2763                         let per_peer_state = self.per_peer_state.read().unwrap();
2764                         let mut has_uncompleted_channel = None;
2765                         for (channel_id, counterparty_node_id, state) in affected_channels {
2766                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2767                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2768                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2769                                                 update_maps_on_chan_removal!(self, &chan.context());
2770                                                 self.issue_channel_close_events(&chan.context(), ClosureReason::FundingBatchClosure);
2771                                                 shutdown_results.push(chan.context_mut().force_shutdown(false));
2772                                         }
2773                                 }
2774                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2775                         }
2776                         debug_assert!(
2777                                 has_uncompleted_channel.unwrap_or(true),
2778                                 "Closing a batch where all channels have completed initial monitor update",
2779                         );
2780                 }
2781                 for shutdown_result in shutdown_results.drain(..) {
2782                         self.finish_close_channel(shutdown_result);
2783                 }
2784         }
2785
2786         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2787         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2788         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2789         -> Result<PublicKey, APIError> {
2790                 let per_peer_state = self.per_peer_state.read().unwrap();
2791                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2792                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2793                 let (update_opt, counterparty_node_id) = {
2794                         let mut peer_state = peer_state_mutex.lock().unwrap();
2795                         let closure_reason = if let Some(peer_msg) = peer_msg {
2796                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2797                         } else {
2798                                 ClosureReason::HolderForceClosed
2799                         };
2800                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2801                                 log_error!(self.logger, "Force-closing channel {}", channel_id);
2802                                 self.issue_channel_close_events(&chan_phase_entry.get().context(), closure_reason);
2803                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2804                                 mem::drop(peer_state);
2805                                 mem::drop(per_peer_state);
2806                                 match chan_phase {
2807                                         ChannelPhase::Funded(mut chan) => {
2808                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast));
2809                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2810                                         },
2811                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2812                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false));
2813                                                 // Unfunded channel has no update
2814                                                 (None, chan_phase.context().get_counterparty_node_id())
2815                                         },
2816                                 }
2817                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2818                                 log_error!(self.logger, "Force-closing channel {}", &channel_id);
2819                                 // N.B. that we don't send any channel close event here: we
2820                                 // don't have a user_channel_id, and we never sent any opening
2821                                 // events anyway.
2822                                 (None, *peer_node_id)
2823                         } else {
2824                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2825                         }
2826                 };
2827                 if let Some(update) = update_opt {
2828                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2829                         // not try to broadcast it via whatever peer we have.
2830                         let per_peer_state = self.per_peer_state.read().unwrap();
2831                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2832                                 .ok_or(per_peer_state.values().next());
2833                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2834                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2835                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2836                                         msg: update
2837                                 });
2838                         }
2839                 }
2840
2841                 Ok(counterparty_node_id)
2842         }
2843
2844         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2845                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2846                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2847                         Ok(counterparty_node_id) => {
2848                                 let per_peer_state = self.per_peer_state.read().unwrap();
2849                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2850                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2851                                         peer_state.pending_msg_events.push(
2852                                                 events::MessageSendEvent::HandleError {
2853                                                         node_id: counterparty_node_id,
2854                                                         action: msgs::ErrorAction::DisconnectPeer {
2855                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2856                                                         },
2857                                                 }
2858                                         );
2859                                 }
2860                                 Ok(())
2861                         },
2862                         Err(e) => Err(e)
2863                 }
2864         }
2865
2866         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2867         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2868         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2869         /// channel.
2870         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2871         -> Result<(), APIError> {
2872                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2873         }
2874
2875         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2876         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2877         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2878         ///
2879         /// You can always get the latest local transaction(s) to broadcast from
2880         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2881         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2882         -> Result<(), APIError> {
2883                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2884         }
2885
2886         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2887         /// for each to the chain and rejecting new HTLCs on each.
2888         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2889                 for chan in self.list_channels() {
2890                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2891                 }
2892         }
2893
2894         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2895         /// local transaction(s).
2896         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2897                 for chan in self.list_channels() {
2898                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2899                 }
2900         }
2901
2902         fn construct_fwd_pending_htlc_info(
2903                 &self, msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
2904                 new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
2905                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
2906         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2907                 debug_assert!(next_packet_pubkey_opt.is_some());
2908                 let outgoing_packet = msgs::OnionPacket {
2909                         version: 0,
2910                         public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
2911                         hop_data: new_packet_bytes,
2912                         hmac: hop_hmac,
2913                 };
2914
2915                 let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
2916                         msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
2917                                 (short_channel_id, amt_to_forward, outgoing_cltv_value),
2918                         msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
2919                                 return Err(InboundOnionErr {
2920                                         msg: "Final Node OnionHopData provided for us as an intermediary node",
2921                                         err_code: 0x4000 | 22,
2922                                         err_data: Vec::new(),
2923                                 }),
2924                 };
2925
2926                 Ok(PendingHTLCInfo {
2927                         routing: PendingHTLCRouting::Forward {
2928                                 onion_packet: outgoing_packet,
2929                                 short_channel_id,
2930                         },
2931                         payment_hash: msg.payment_hash,
2932                         incoming_shared_secret: shared_secret,
2933                         incoming_amt_msat: Some(msg.amount_msat),
2934                         outgoing_amt_msat: amt_to_forward,
2935                         outgoing_cltv_value,
2936                         skimmed_fee_msat: None,
2937                 })
2938         }
2939
2940         fn construct_recv_pending_htlc_info(
2941                 &self, hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
2942                 amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
2943                 counterparty_skimmed_fee_msat: Option<u64>,
2944         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2945                 let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
2946                         msgs::InboundOnionPayload::Receive {
2947                                 payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
2948                         } =>
2949                                 (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
2950                         msgs::InboundOnionPayload::BlindedReceive {
2951                                 amt_msat, total_msat, outgoing_cltv_value, payment_secret, ..
2952                         } => {
2953                                 let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
2954                                 (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
2955                         }
2956                         msgs::InboundOnionPayload::Forward { .. } => {
2957                                 return Err(InboundOnionErr {
2958                                         err_code: 0x4000|22,
2959                                         err_data: Vec::new(),
2960                                         msg: "Got non final data with an HMAC of 0",
2961                                 })
2962                         },
2963                 };
2964                 // final_incorrect_cltv_expiry
2965                 if outgoing_cltv_value > cltv_expiry {
2966                         return Err(InboundOnionErr {
2967                                 msg: "Upstream node set CLTV to less than the CLTV set by the sender",
2968                                 err_code: 18,
2969                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2970                         })
2971                 }
2972                 // final_expiry_too_soon
2973                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2974                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2975                 //
2976                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2977                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2978                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2979                 let current_height: u32 = self.best_block.read().unwrap().height();
2980                 if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
2981                         let mut err_data = Vec::with_capacity(12);
2982                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2983                         err_data.extend_from_slice(&current_height.to_be_bytes());
2984                         return Err(InboundOnionErr {
2985                                 err_code: 0x4000 | 15, err_data,
2986                                 msg: "The final CLTV expiry is too soon to handle",
2987                         });
2988                 }
2989                 if (!allow_underpay && onion_amt_msat > amt_msat) ||
2990                         (allow_underpay && onion_amt_msat >
2991                          amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
2992                 {
2993                         return Err(InboundOnionErr {
2994                                 err_code: 19,
2995                                 err_data: amt_msat.to_be_bytes().to_vec(),
2996                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2997                         });
2998                 }
2999
3000                 let routing = if let Some(payment_preimage) = keysend_preimage {
3001                         // We need to check that the sender knows the keysend preimage before processing this
3002                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
3003                         // could discover the final destination of X, by probing the adjacent nodes on the route
3004                         // with a keysend payment of identical payment hash to X and observing the processing
3005                         // time discrepancies due to a hash collision with X.
3006                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
3007                         if hashed_preimage != payment_hash {
3008                                 return Err(InboundOnionErr {
3009                                         err_code: 0x4000|22,
3010                                         err_data: Vec::new(),
3011                                         msg: "Payment preimage didn't match payment hash",
3012                                 });
3013                         }
3014                         if !self.default_configuration.accept_mpp_keysend && payment_data.is_some() {
3015                                 return Err(InboundOnionErr {
3016                                         err_code: 0x4000|22,
3017                                         err_data: Vec::new(),
3018                                         msg: "We don't support MPP keysend payments",
3019                                 });
3020                         }
3021                         PendingHTLCRouting::ReceiveKeysend {
3022                                 payment_data,
3023                                 payment_preimage,
3024                                 payment_metadata,
3025                                 incoming_cltv_expiry: outgoing_cltv_value,
3026                                 custom_tlvs,
3027                         }
3028                 } else if let Some(data) = payment_data {
3029                         PendingHTLCRouting::Receive {
3030                                 payment_data: data,
3031                                 payment_metadata,
3032                                 incoming_cltv_expiry: outgoing_cltv_value,
3033                                 phantom_shared_secret,
3034                                 custom_tlvs,
3035                         }
3036                 } else {
3037                         return Err(InboundOnionErr {
3038                                 err_code: 0x4000|0x2000|3,
3039                                 err_data: Vec::new(),
3040                                 msg: "We require payment_secrets",
3041                         });
3042                 };
3043                 Ok(PendingHTLCInfo {
3044                         routing,
3045                         payment_hash,
3046                         incoming_shared_secret: shared_secret,
3047                         incoming_amt_msat: Some(amt_msat),
3048                         outgoing_amt_msat: onion_amt_msat,
3049                         outgoing_cltv_value,
3050                         skimmed_fee_msat: counterparty_skimmed_fee_msat,
3051                 })
3052         }
3053
3054         fn decode_update_add_htlc_onion(
3055                 &self, msg: &msgs::UpdateAddHTLC
3056         ) -> Result<(onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg> {
3057                 macro_rules! return_malformed_err {
3058                         ($msg: expr, $err_code: expr) => {
3059                                 {
3060                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3061                                         return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3062                                                 channel_id: msg.channel_id,
3063                                                 htlc_id: msg.htlc_id,
3064                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
3065                                                 failure_code: $err_code,
3066                                         }));
3067                                 }
3068                         }
3069                 }
3070
3071                 if let Err(_) = msg.onion_routing_packet.public_key {
3072                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
3073                 }
3074
3075                 let shared_secret = self.node_signer.ecdh(
3076                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
3077                 ).unwrap().secret_bytes();
3078
3079                 if msg.onion_routing_packet.version != 0 {
3080                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
3081                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
3082                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
3083                         //receiving node would have to brute force to figure out which version was put in the
3084                         //packet by the node that send us the message, in the case of hashing the hop_data, the
3085                         //node knows the HMAC matched, so they already know what is there...
3086                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
3087                 }
3088                 macro_rules! return_err {
3089                         ($msg: expr, $err_code: expr, $data: expr) => {
3090                                 {
3091                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3092                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3093                                                 channel_id: msg.channel_id,
3094                                                 htlc_id: msg.htlc_id,
3095                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3096                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3097                                         }));
3098                                 }
3099                         }
3100                 }
3101
3102                 let next_hop = match onion_utils::decode_next_payment_hop(
3103                         shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
3104                         msg.payment_hash, &self.node_signer
3105                 ) {
3106                         Ok(res) => res,
3107                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3108                                 return_malformed_err!(err_msg, err_code);
3109                         },
3110                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3111                                 return_err!(err_msg, err_code, &[0; 0]);
3112                         },
3113                 };
3114                 let (outgoing_scid, outgoing_amt_msat, outgoing_cltv_value, next_packet_pk_opt) = match next_hop {
3115                         onion_utils::Hop::Forward {
3116                                 next_hop_data: msgs::InboundOnionPayload::Forward {
3117                                         short_channel_id, amt_to_forward, outgoing_cltv_value
3118                                 }, ..
3119                         } => {
3120                                 let next_packet_pk = onion_utils::next_hop_pubkey(&self.secp_ctx,
3121                                         msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
3122                                 (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(next_packet_pk))
3123                         },
3124                         // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
3125                         // inbound channel's state.
3126                         onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
3127                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
3128                                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
3129                         {
3130                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
3131                         }
3132                 };
3133
3134                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3135                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3136                 if let Some((err, mut code, chan_update)) = loop {
3137                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3138                         let forwarding_chan_info_opt = match id_option {
3139                                 None => { // unknown_next_peer
3140                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3141                                         // phantom or an intercept.
3142                                         if (self.default_configuration.accept_intercept_htlcs &&
3143                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3144                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3145                                         {
3146                                                 None
3147                                         } else {
3148                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3149                                         }
3150                                 },
3151                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3152                         };
3153                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3154                                 let per_peer_state = self.per_peer_state.read().unwrap();
3155                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3156                                 if peer_state_mutex_opt.is_none() {
3157                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3158                                 }
3159                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3160                                 let peer_state = &mut *peer_state_lock;
3161                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3162                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3163                                 ).flatten() {
3164                                         None => {
3165                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3166                                                 // have no consistency guarantees.
3167                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3168                                         },
3169                                         Some(chan) => chan
3170                                 };
3171                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3172                                         // Note that the behavior here should be identical to the above block - we
3173                                         // should NOT reveal the existence or non-existence of a private channel if
3174                                         // we don't allow forwards outbound over them.
3175                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3176                                 }
3177                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3178                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3179                                         // "refuse to forward unless the SCID alias was used", so we pretend
3180                                         // we don't have the channel here.
3181                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3182                                 }
3183                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3184
3185                                 // Note that we could technically not return an error yet here and just hope
3186                                 // that the connection is reestablished or monitor updated by the time we get
3187                                 // around to doing the actual forward, but better to fail early if we can and
3188                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3189                                 // on a small/per-node/per-channel scale.
3190                                 if !chan.context.is_live() { // channel_disabled
3191                                         // If the channel_update we're going to return is disabled (i.e. the
3192                                         // peer has been disabled for some time), return `channel_disabled`,
3193                                         // otherwise return `temporary_channel_failure`.
3194                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3195                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3196                                         } else {
3197                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3198                                         }
3199                                 }
3200                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3201                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3202                                 }
3203                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3204                                         break Some((err, code, chan_update_opt));
3205                                 }
3206                                 chan_update_opt
3207                         } else {
3208                                 if (msg.cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
3209                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3210                                         // forwarding over a real channel we can't generate a channel_update
3211                                         // for it. Instead we just return a generic temporary_node_failure.
3212                                         break Some((
3213                                                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
3214                                                         0x2000 | 2, None,
3215                                         ));
3216                                 }
3217                                 None
3218                         };
3219
3220                         let cur_height = self.best_block.read().unwrap().height() + 1;
3221                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
3222                         // but we want to be robust wrt to counterparty packet sanitization (see
3223                         // HTLC_FAIL_BACK_BUFFER rationale).
3224                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
3225                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
3226                         }
3227                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
3228                                 break Some(("CLTV expiry is too far in the future", 21, None));
3229                         }
3230                         // If the HTLC expires ~now, don't bother trying to forward it to our
3231                         // counterparty. They should fail it anyway, but we don't want to bother with
3232                         // the round-trips or risk them deciding they definitely want the HTLC and
3233                         // force-closing to ensure they get it if we're offline.
3234                         // We previously had a much more aggressive check here which tried to ensure
3235                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
3236                         // but there is no need to do that, and since we're a bit conservative with our
3237                         // risk threshold it just results in failing to forward payments.
3238                         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
3239                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
3240                         }
3241
3242                         break None;
3243                 }
3244                 {
3245                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3246                         if let Some(chan_update) = chan_update {
3247                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3248                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3249                                 }
3250                                 else if code == 0x1000 | 13 {
3251                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3252                                 }
3253                                 else if code == 0x1000 | 20 {
3254                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3255                                         0u16.write(&mut res).expect("Writes cannot fail");
3256                                 }
3257                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3258                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3259                                 chan_update.write(&mut res).expect("Writes cannot fail");
3260                         } else if code & 0x1000 == 0x1000 {
3261                                 // If we're trying to return an error that requires a `channel_update` but
3262                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3263                                 // generate an update), just use the generic "temporary_node_failure"
3264                                 // instead.
3265                                 code = 0x2000 | 2;
3266                         }
3267                         return_err!(err, code, &res.0[..]);
3268                 }
3269                 Ok((next_hop, shared_secret, next_packet_pk_opt))
3270         }
3271
3272         fn construct_pending_htlc_status<'a>(
3273                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3274                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3275         ) -> PendingHTLCStatus {
3276                 macro_rules! return_err {
3277                         ($msg: expr, $err_code: expr, $data: expr) => {
3278                                 {
3279                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3280                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3281                                                 channel_id: msg.channel_id,
3282                                                 htlc_id: msg.htlc_id,
3283                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3284                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3285                                         }));
3286                                 }
3287                         }
3288                 }
3289                 match decoded_hop {
3290                         onion_utils::Hop::Receive(next_hop_data) => {
3291                                 // OUR PAYMENT!
3292                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3293                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat)
3294                                 {
3295                                         Ok(info) => {
3296                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3297                                                 // message, however that would leak that we are the recipient of this payment, so
3298                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3299                                                 // delay) once they've send us a commitment_signed!
3300                                                 PendingHTLCStatus::Forward(info)
3301                                         },
3302                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3303                                 }
3304                         },
3305                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3306                                 match self.construct_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3307                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3308                                         Ok(info) => PendingHTLCStatus::Forward(info),
3309                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3310                                 }
3311                         }
3312                 }
3313         }
3314
3315         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3316         /// public, and thus should be called whenever the result is going to be passed out in a
3317         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3318         ///
3319         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3320         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3321         /// storage and the `peer_state` lock has been dropped.
3322         ///
3323         /// [`channel_update`]: msgs::ChannelUpdate
3324         /// [`internal_closing_signed`]: Self::internal_closing_signed
3325         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3326                 if !chan.context.should_announce() {
3327                         return Err(LightningError {
3328                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3329                                 action: msgs::ErrorAction::IgnoreError
3330                         });
3331                 }
3332                 if chan.context.get_short_channel_id().is_none() {
3333                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3334                 }
3335                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3336                 self.get_channel_update_for_unicast(chan)
3337         }
3338
3339         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3340         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3341         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3342         /// provided evidence that they know about the existence of the channel.
3343         ///
3344         /// Note that through [`internal_closing_signed`], this function is called without the
3345         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3346         /// removed from the storage and the `peer_state` lock has been dropped.
3347         ///
3348         /// [`channel_update`]: msgs::ChannelUpdate
3349         /// [`internal_closing_signed`]: Self::internal_closing_signed
3350         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3351                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", &chan.context.channel_id());
3352                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3353                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3354                         Some(id) => id,
3355                 };
3356
3357                 self.get_channel_update_for_onion(short_channel_id, chan)
3358         }
3359
3360         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3361                 log_trace!(self.logger, "Generating channel update for channel {}", &chan.context.channel_id());
3362                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3363
3364                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3365                         ChannelUpdateStatus::Enabled => true,
3366                         ChannelUpdateStatus::DisabledStaged(_) => true,
3367                         ChannelUpdateStatus::Disabled => false,
3368                         ChannelUpdateStatus::EnabledStaged(_) => false,
3369                 };
3370
3371                 let unsigned = msgs::UnsignedChannelUpdate {
3372                         chain_hash: self.chain_hash,
3373                         short_channel_id,
3374                         timestamp: chan.context.get_update_time_counter(),
3375                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3376                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3377                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3378                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3379                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3380                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3381                         excess_data: Vec::new(),
3382                 };
3383                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3384                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3385                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3386                 // channel.
3387                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3388
3389                 Ok(msgs::ChannelUpdate {
3390                         signature: sig,
3391                         contents: unsigned
3392                 })
3393         }
3394
3395         #[cfg(test)]
3396         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> {
3397                 let _lck = self.total_consistency_lock.read().unwrap();
3398                 self.send_payment_along_path(SendAlongPathArgs {
3399                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3400                         session_priv_bytes
3401                 })
3402         }
3403
3404         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3405                 let SendAlongPathArgs {
3406                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3407                         session_priv_bytes
3408                 } = args;
3409                 // The top-level caller should hold the total_consistency_lock read lock.
3410                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3411
3412                 log_trace!(self.logger,
3413                         "Attempting to send payment with payment hash {} along path with next hop {}",
3414                         payment_hash, path.hops.first().unwrap().short_channel_id);
3415                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3416                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3417
3418                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3419                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3420                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3421
3422                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3423                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3424
3425                 let err: Result<(), _> = loop {
3426                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3427                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3428                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3429                         };
3430
3431                         let per_peer_state = self.per_peer_state.read().unwrap();
3432                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3433                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3434                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3435                         let peer_state = &mut *peer_state_lock;
3436                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3437                                 match chan_phase_entry.get_mut() {
3438                                         ChannelPhase::Funded(chan) => {
3439                                                 if !chan.context.is_live() {
3440                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3441                                                 }
3442                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3443                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3444                                                         htlc_cltv, HTLCSource::OutboundRoute {
3445                                                                 path: path.clone(),
3446                                                                 session_priv: session_priv.clone(),
3447                                                                 first_hop_htlc_msat: htlc_msat,
3448                                                                 payment_id,
3449                                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3450                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3451                                                         Some(monitor_update) => {
3452                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3453                                                                         false => {
3454                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3455                                                                                 // docs) that we will resend the commitment update once monitor
3456                                                                                 // updating completes. Therefore, we must return an error
3457                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3458                                                                                 // which we do in the send_payment check for
3459                                                                                 // MonitorUpdateInProgress, below.
3460                                                                                 return Err(APIError::MonitorUpdateInProgress);
3461                                                                         },
3462                                                                         true => {},
3463                                                                 }
3464                                                         },
3465                                                         None => {},
3466                                                 }
3467                                         },
3468                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3469                                 };
3470                         } else {
3471                                 // The channel was likely removed after we fetched the id from the
3472                                 // `short_to_chan_info` map, but before we successfully locked the
3473                                 // `channel_by_id` map.
3474                                 // This can occur as no consistency guarantees exists between the two maps.
3475                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3476                         }
3477                         return Ok(());
3478                 };
3479
3480                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3481                         Ok(_) => unreachable!(),
3482                         Err(e) => {
3483                                 Err(APIError::ChannelUnavailable { err: e.err })
3484                         },
3485                 }
3486         }
3487
3488         /// Sends a payment along a given route.
3489         ///
3490         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3491         /// fields for more info.
3492         ///
3493         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3494         /// [`PeerManager::process_events`]).
3495         ///
3496         /// # Avoiding Duplicate Payments
3497         ///
3498         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3499         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3500         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3501         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3502         /// second payment with the same [`PaymentId`].
3503         ///
3504         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3505         /// tracking of payments, including state to indicate once a payment has completed. Because you
3506         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3507         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3508         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3509         ///
3510         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3511         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3512         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3513         /// [`ChannelManager::list_recent_payments`] for more information.
3514         ///
3515         /// # Possible Error States on [`PaymentSendFailure`]
3516         ///
3517         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3518         /// each entry matching the corresponding-index entry in the route paths, see
3519         /// [`PaymentSendFailure`] for more info.
3520         ///
3521         /// In general, a path may raise:
3522         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3523         ///    node public key) is specified.
3524         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3525         ///    closed, doesn't exist, or the peer is currently disconnected.
3526         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3527         ///    relevant updates.
3528         ///
3529         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3530         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3531         /// different route unless you intend to pay twice!
3532         ///
3533         /// [`RouteHop`]: crate::routing::router::RouteHop
3534         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3535         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3536         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3537         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3538         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3539         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3540                 let best_block_height = self.best_block.read().unwrap().height();
3541                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3542                 self.pending_outbound_payments
3543                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3544                                 &self.entropy_source, &self.node_signer, best_block_height,
3545                                 |args| self.send_payment_along_path(args))
3546         }
3547
3548         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3549         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3550         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3551                 let best_block_height = self.best_block.read().unwrap().height();
3552                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3553                 self.pending_outbound_payments
3554                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3555                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3556                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3557                                 &self.pending_events, |args| self.send_payment_along_path(args))
3558         }
3559
3560         #[cfg(test)]
3561         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> {
3562                 let best_block_height = self.best_block.read().unwrap().height();
3563                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3564                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3565                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3566                         best_block_height, |args| self.send_payment_along_path(args))
3567         }
3568
3569         #[cfg(test)]
3570         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> {
3571                 let best_block_height = self.best_block.read().unwrap().height();
3572                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3573         }
3574
3575         #[cfg(test)]
3576         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3577                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3578         }
3579
3580
3581         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3582         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3583         /// retries are exhausted.
3584         ///
3585         /// # Event Generation
3586         ///
3587         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3588         /// as there are no remaining pending HTLCs for this payment.
3589         ///
3590         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3591         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3592         /// determine the ultimate status of a payment.
3593         ///
3594         /// # Restart Behavior
3595         ///
3596         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3597         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated.
3598         pub fn abandon_payment(&self, payment_id: PaymentId) {
3599                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3600                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3601         }
3602
3603         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3604         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3605         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3606         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3607         /// never reach the recipient.
3608         ///
3609         /// See [`send_payment`] documentation for more details on the return value of this function
3610         /// and idempotency guarantees provided by the [`PaymentId`] key.
3611         ///
3612         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3613         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3614         ///
3615         /// [`send_payment`]: Self::send_payment
3616         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3617                 let best_block_height = self.best_block.read().unwrap().height();
3618                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3619                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3620                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3621                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3622         }
3623
3624         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3625         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3626         ///
3627         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3628         /// payments.
3629         ///
3630         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3631         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> {
3632                 let best_block_height = self.best_block.read().unwrap().height();
3633                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3634                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3635                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3636                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3637                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3638         }
3639
3640         /// Send a payment that is probing the given route for liquidity. We calculate the
3641         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3642         /// us to easily discern them from real payments.
3643         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3644                 let best_block_height = self.best_block.read().unwrap().height();
3645                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3646                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3647                         &self.entropy_source, &self.node_signer, best_block_height,
3648                         |args| self.send_payment_along_path(args))
3649         }
3650
3651         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3652         /// payment probe.
3653         #[cfg(test)]
3654         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3655                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3656         }
3657
3658         /// Sends payment probes over all paths of a route that would be used to pay the given
3659         /// amount to the given `node_id`.
3660         ///
3661         /// See [`ChannelManager::send_preflight_probes`] for more information.
3662         pub fn send_spontaneous_preflight_probes(
3663                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3664                 liquidity_limit_multiplier: Option<u64>,
3665         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3666                 let payment_params =
3667                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3668
3669                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3670
3671                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3672         }
3673
3674         /// Sends payment probes over all paths of a route that would be used to pay a route found
3675         /// according to the given [`RouteParameters`].
3676         ///
3677         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3678         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3679         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3680         /// confirmation in a wallet UI.
3681         ///
3682         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3683         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3684         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3685         /// payment. To mitigate this issue, channels with available liquidity less than the required
3686         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3687         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3688         pub fn send_preflight_probes(
3689                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3690         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3691                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3692
3693                 let payer = self.get_our_node_id();
3694                 let usable_channels = self.list_usable_channels();
3695                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3696                 let inflight_htlcs = self.compute_inflight_htlcs();
3697
3698                 let route = self
3699                         .router
3700                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3701                         .map_err(|e| {
3702                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3703                                 ProbeSendFailure::RouteNotFound
3704                         })?;
3705
3706                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3707
3708                 let mut res = Vec::new();
3709
3710                 for mut path in route.paths {
3711                         // If the last hop is probably an unannounced channel we refrain from probing all the
3712                         // way through to the end and instead probe up to the second-to-last channel.
3713                         while let Some(last_path_hop) = path.hops.last() {
3714                                 if last_path_hop.maybe_announced_channel {
3715                                         // We found a potentially announced last hop.
3716                                         break;
3717                                 } else {
3718                                         // Drop the last hop, as it's likely unannounced.
3719                                         log_debug!(
3720                                                 self.logger,
3721                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3722                                                 last_path_hop.short_channel_id
3723                                         );
3724                                         let final_value_msat = path.final_value_msat();
3725                                         path.hops.pop();
3726                                         if let Some(new_last) = path.hops.last_mut() {
3727                                                 new_last.fee_msat += final_value_msat;
3728                                         }
3729                                 }
3730                         }
3731
3732                         if path.hops.len() < 2 {
3733                                 log_debug!(
3734                                         self.logger,
3735                                         "Skipped sending payment probe over path with less than two hops."
3736                                 );
3737                                 continue;
3738                         }
3739
3740                         if let Some(first_path_hop) = path.hops.first() {
3741                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3742                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3743                                 }) {
3744                                         let path_value = path.final_value_msat() + path.fee_msat();
3745                                         let used_liquidity =
3746                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3747
3748                                         if first_hop.next_outbound_htlc_limit_msat
3749                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3750                                         {
3751                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3752                                                 continue;
3753                                         } else {
3754                                                 *used_liquidity += path_value;
3755                                         }
3756                                 }
3757                         }
3758
3759                         res.push(self.send_probe(path).map_err(|e| {
3760                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3761                                 ProbeSendFailure::SendingFailed(e)
3762                         })?);
3763                 }
3764
3765                 Ok(res)
3766         }
3767
3768         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3769         /// which checks the correctness of the funding transaction given the associated channel.
3770         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3771                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3772                 mut find_funding_output: FundingOutput,
3773         ) -> Result<(), APIError> {
3774                 let per_peer_state = self.per_peer_state.read().unwrap();
3775                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3776                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3777
3778                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3779                 let peer_state = &mut *peer_state_lock;
3780                 let (chan, msg) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3781                         Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
3782                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3783
3784                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &self.logger)
3785                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3786                                                 let channel_id = chan.context.channel_id();
3787                                                 let user_id = chan.context.get_user_id();
3788                                                 let shutdown_res = chan.context.force_shutdown(false);
3789                                                 let channel_capacity = chan.context.get_value_satoshis();
3790                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3791                                         } else { unreachable!(); });
3792                                 match funding_res {
3793                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3794                                         Err((chan, err)) => {
3795                                                 mem::drop(peer_state_lock);
3796                                                 mem::drop(per_peer_state);
3797
3798                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3799                                                 return Err(APIError::ChannelUnavailable {
3800                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3801                                                 });
3802                                         },
3803                                 }
3804                         },
3805                         Some(phase) => {
3806                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3807                                 return Err(APIError::APIMisuseError {
3808                                         err: format!(
3809                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3810                                                 temporary_channel_id, counterparty_node_id),
3811                                 })
3812                         },
3813                         None => return Err(APIError::ChannelUnavailable {err: format!(
3814                                 "Channel with id {} not found for the passed counterparty node_id {}",
3815                                 temporary_channel_id, counterparty_node_id),
3816                                 }),
3817                 };
3818
3819                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3820                         node_id: chan.context.get_counterparty_node_id(),
3821                         msg,
3822                 });
3823                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3824                         hash_map::Entry::Occupied(_) => {
3825                                 panic!("Generated duplicate funding txid?");
3826                         },
3827                         hash_map::Entry::Vacant(e) => {
3828                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3829                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3830                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3831                                 }
3832                                 e.insert(ChannelPhase::Funded(chan));
3833                         }
3834                 }
3835                 Ok(())
3836         }
3837
3838         #[cfg(test)]
3839         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3840                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3841                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3842                 })
3843         }
3844
3845         /// Call this upon creation of a funding transaction for the given channel.
3846         ///
3847         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3848         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3849         ///
3850         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3851         /// across the p2p network.
3852         ///
3853         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3854         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3855         ///
3856         /// May panic if the output found in the funding transaction is duplicative with some other
3857         /// channel (note that this should be trivially prevented by using unique funding transaction
3858         /// keys per-channel).
3859         ///
3860         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3861         /// counterparty's signature the funding transaction will automatically be broadcast via the
3862         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3863         ///
3864         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3865         /// not currently support replacing a funding transaction on an existing channel. Instead,
3866         /// create a new channel with a conflicting funding transaction.
3867         ///
3868         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3869         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3870         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3871         /// for more details.
3872         ///
3873         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3874         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3875         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3876                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3877         }
3878
3879         /// Call this upon creation of a batch funding transaction for the given channels.
3880         ///
3881         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3882         /// each individual channel and transaction output.
3883         ///
3884         /// Do NOT broadcast the funding transaction yourself. This batch funding transcaction
3885         /// will only be broadcast when we have safely received and persisted the counterparty's
3886         /// signature for each channel.
3887         ///
3888         /// If there is an error, all channels in the batch are to be considered closed.
3889         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3890                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3891                 let mut result = Ok(());
3892
3893                 if !funding_transaction.is_coin_base() {
3894                         for inp in funding_transaction.input.iter() {
3895                                 if inp.witness.is_empty() {
3896                                         result = result.and(Err(APIError::APIMisuseError {
3897                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3898                                         }));
3899                                 }
3900                         }
3901                 }
3902                 if funding_transaction.output.len() > u16::max_value() as usize {
3903                         result = result.and(Err(APIError::APIMisuseError {
3904                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3905                         }));
3906                 }
3907                 {
3908                         let height = self.best_block.read().unwrap().height();
3909                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3910                         // lower than the next block height. However, the modules constituting our Lightning
3911                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3912                         // module is ahead of LDK, only allow one more block of headroom.
3913                         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 {
3914                                 result = result.and(Err(APIError::APIMisuseError {
3915                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3916                                 }));
3917                         }
3918                 }
3919
3920                 let txid = funding_transaction.txid();
3921                 let is_batch_funding = temporary_channels.len() > 1;
3922                 let mut funding_batch_states = if is_batch_funding {
3923                         Some(self.funding_batch_states.lock().unwrap())
3924                 } else {
3925                         None
3926                 };
3927                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3928                         match states.entry(txid) {
3929                                 btree_map::Entry::Occupied(_) => {
3930                                         result = result.clone().and(Err(APIError::APIMisuseError {
3931                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3932                                         }));
3933                                         None
3934                                 },
3935                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3936                         }
3937                 });
3938                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels.iter() {
3939                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3940                                 temporary_channel_id,
3941                                 counterparty_node_id,
3942                                 funding_transaction.clone(),
3943                                 is_batch_funding,
3944                                 |chan, tx| {
3945                                         let mut output_index = None;
3946                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3947                                         for (idx, outp) in tx.output.iter().enumerate() {
3948                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3949                                                         if output_index.is_some() {
3950                                                                 return Err(APIError::APIMisuseError {
3951                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3952                                                                 });
3953                                                         }
3954                                                         output_index = Some(idx as u16);
3955                                                 }
3956                                         }
3957                                         if output_index.is_none() {
3958                                                 return Err(APIError::APIMisuseError {
3959                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3960                                                 });
3961                                         }
3962                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3963                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3964                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3965                                         }
3966                                         Ok(outpoint)
3967                                 })
3968                         );
3969                 }
3970                 if let Err(ref e) = result {
3971                         // Remaining channels need to be removed on any error.
3972                         let e = format!("Error in transaction funding: {:?}", e);
3973                         let mut channels_to_remove = Vec::new();
3974                         channels_to_remove.extend(funding_batch_states.as_mut()
3975                                 .and_then(|states| states.remove(&txid))
3976                                 .into_iter().flatten()
3977                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3978                         );
3979                         channels_to_remove.extend(temporary_channels.iter()
3980                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3981                         );
3982                         let mut shutdown_results = Vec::new();
3983                         {
3984                                 let per_peer_state = self.per_peer_state.read().unwrap();
3985                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3986                                         per_peer_state.get(&counterparty_node_id)
3987                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3988                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3989                                                 .map(|mut chan| {
3990                                                         update_maps_on_chan_removal!(self, &chan.context());
3991                                                         self.issue_channel_close_events(&chan.context(), ClosureReason::ProcessingError { err: e.clone() });
3992                                                         shutdown_results.push(chan.context_mut().force_shutdown(false));
3993                                                 });
3994                                 }
3995                         }
3996                         for shutdown_result in shutdown_results.drain(..) {
3997                                 self.finish_close_channel(shutdown_result);
3998                         }
3999                 }
4000                 result
4001         }
4002
4003         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
4004         ///
4005         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4006         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4007         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4008         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4009         ///
4010         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4011         /// `counterparty_node_id` is provided.
4012         ///
4013         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4014         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4015         ///
4016         /// If an error is returned, none of the updates should be considered applied.
4017         ///
4018         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4019         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4020         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4021         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4022         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4023         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4024         /// [`APIMisuseError`]: APIError::APIMisuseError
4025         pub fn update_partial_channel_config(
4026                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
4027         ) -> Result<(), APIError> {
4028                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
4029                         return Err(APIError::APIMisuseError {
4030                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
4031                         });
4032                 }
4033
4034                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4035                 let per_peer_state = self.per_peer_state.read().unwrap();
4036                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4037                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4038                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4039                 let peer_state = &mut *peer_state_lock;
4040                 for channel_id in channel_ids {
4041                         if !peer_state.has_channel(channel_id) {
4042                                 return Err(APIError::ChannelUnavailable {
4043                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4044                                 });
4045                         };
4046                 }
4047                 for channel_id in channel_ids {
4048                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4049                                 let mut config = channel_phase.context().config();
4050                                 config.apply(config_update);
4051                                 if !channel_phase.context_mut().update_config(&config) {
4052                                         continue;
4053                                 }
4054                                 if let ChannelPhase::Funded(channel) = channel_phase {
4055                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4056                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4057                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4058                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4059                                                         node_id: channel.context.get_counterparty_node_id(),
4060                                                         msg,
4061                                                 });
4062                                         }
4063                                 }
4064                                 continue;
4065                         } else {
4066                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4067                                 debug_assert!(false);
4068                                 return Err(APIError::ChannelUnavailable {
4069                                         err: format!(
4070                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4071                                                 channel_id, counterparty_node_id),
4072                                 });
4073                         };
4074                 }
4075                 Ok(())
4076         }
4077
4078         /// Atomically updates the [`ChannelConfig`] for the given channels.
4079         ///
4080         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4081         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4082         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4083         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4084         ///
4085         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4086         /// `counterparty_node_id` is provided.
4087         ///
4088         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4089         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4090         ///
4091         /// If an error is returned, none of the updates should be considered applied.
4092         ///
4093         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4094         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4095         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4096         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4097         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4098         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4099         /// [`APIMisuseError`]: APIError::APIMisuseError
4100         pub fn update_channel_config(
4101                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4102         ) -> Result<(), APIError> {
4103                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4104         }
4105
4106         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4107         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4108         ///
4109         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4110         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4111         ///
4112         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4113         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4114         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4115         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4116         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4117         ///
4118         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4119         /// you from forwarding more than you received. See
4120         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4121         /// than expected.
4122         ///
4123         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4124         /// backwards.
4125         ///
4126         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4127         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4128         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4129         // TODO: when we move to deciding the best outbound channel at forward time, only take
4130         // `next_node_id` and not `next_hop_channel_id`
4131         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> {
4132                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4133
4134                 let next_hop_scid = {
4135                         let peer_state_lock = self.per_peer_state.read().unwrap();
4136                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4137                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4138                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4139                         let peer_state = &mut *peer_state_lock;
4140                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4141                                 Some(ChannelPhase::Funded(chan)) => {
4142                                         if !chan.context.is_usable() {
4143                                                 return Err(APIError::ChannelUnavailable {
4144                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4145                                                 })
4146                                         }
4147                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4148                                 },
4149                                 Some(_) => return Err(APIError::ChannelUnavailable {
4150                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4151                                                 next_hop_channel_id, next_node_id)
4152                                 }),
4153                                 None => return Err(APIError::ChannelUnavailable {
4154                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}",
4155                                                 next_hop_channel_id, next_node_id)
4156                                 })
4157                         }
4158                 };
4159
4160                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4161                         .ok_or_else(|| APIError::APIMisuseError {
4162                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4163                         })?;
4164
4165                 let routing = match payment.forward_info.routing {
4166                         PendingHTLCRouting::Forward { onion_packet, .. } => {
4167                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
4168                         },
4169                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4170                 };
4171                 let skimmed_fee_msat =
4172                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4173                 let pending_htlc_info = PendingHTLCInfo {
4174                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4175                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4176                 };
4177
4178                 let mut per_source_pending_forward = [(
4179                         payment.prev_short_channel_id,
4180                         payment.prev_funding_outpoint,
4181                         payment.prev_user_channel_id,
4182                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4183                 )];
4184                 self.forward_htlcs(&mut per_source_pending_forward);
4185                 Ok(())
4186         }
4187
4188         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4189         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4190         ///
4191         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4192         /// backwards.
4193         ///
4194         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4195         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4196                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4197
4198                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4199                         .ok_or_else(|| APIError::APIMisuseError {
4200                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4201                         })?;
4202
4203                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4204                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4205                                 short_channel_id: payment.prev_short_channel_id,
4206                                 user_channel_id: Some(payment.prev_user_channel_id),
4207                                 outpoint: payment.prev_funding_outpoint,
4208                                 htlc_id: payment.prev_htlc_id,
4209                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4210                                 phantom_shared_secret: None,
4211                         });
4212
4213                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4214                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4215                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4216                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4217
4218                 Ok(())
4219         }
4220
4221         /// Processes HTLCs which are pending waiting on random forward delay.
4222         ///
4223         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4224         /// Will likely generate further events.
4225         pub fn process_pending_htlc_forwards(&self) {
4226                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4227
4228                 let mut new_events = VecDeque::new();
4229                 let mut failed_forwards = Vec::new();
4230                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4231                 {
4232                         let mut forward_htlcs = HashMap::new();
4233                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4234
4235                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4236                                 if short_chan_id != 0 {
4237                                         macro_rules! forwarding_channel_not_found {
4238                                                 () => {
4239                                                         for forward_info in pending_forwards.drain(..) {
4240                                                                 match forward_info {
4241                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4242                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4243                                                                                 forward_info: PendingHTLCInfo {
4244                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4245                                                                                         outgoing_cltv_value, ..
4246                                                                                 }
4247                                                                         }) => {
4248                                                                                 macro_rules! failure_handler {
4249                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4250                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4251
4252                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4253                                                                                                         short_channel_id: prev_short_channel_id,
4254                                                                                                         user_channel_id: Some(prev_user_channel_id),
4255                                                                                                         outpoint: prev_funding_outpoint,
4256                                                                                                         htlc_id: prev_htlc_id,
4257                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4258                                                                                                         phantom_shared_secret: $phantom_ss,
4259                                                                                                 });
4260
4261                                                                                                 let reason = if $next_hop_unknown {
4262                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4263                                                                                                 } else {
4264                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4265                                                                                                 };
4266
4267                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4268                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4269                                                                                                         reason
4270                                                                                                 ));
4271                                                                                                 continue;
4272                                                                                         }
4273                                                                                 }
4274                                                                                 macro_rules! fail_forward {
4275                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4276                                                                                                 {
4277                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4278                                                                                                 }
4279                                                                                         }
4280                                                                                 }
4281                                                                                 macro_rules! failed_payment {
4282                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4283                                                                                                 {
4284                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4285                                                                                                 }
4286                                                                                         }
4287                                                                                 }
4288                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
4289                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4290                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4291                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4292                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4293                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4294                                                                                                         payment_hash, &self.node_signer
4295                                                                                                 ) {
4296                                                                                                         Ok(res) => res,
4297                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4298                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
4299                                                                                                                 // In this scenario, the phantom would have sent us an
4300                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4301                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4302                                                                                                                 // of the onion.
4303                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4304                                                                                                         },
4305                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4306                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4307                                                                                                         },
4308                                                                                                 };
4309                                                                                                 match next_hop {
4310                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4311                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data,
4312                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4313                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None)
4314                                                                                                                 {
4315                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4316                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4317                                                                                                                 }
4318                                                                                                         },
4319                                                                                                         _ => panic!(),
4320                                                                                                 }
4321                                                                                         } else {
4322                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4323                                                                                         }
4324                                                                                 } else {
4325                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4326                                                                                 }
4327                                                                         },
4328                                                                         HTLCForwardInfo::FailHTLC { .. } => {
4329                                                                                 // Channel went away before we could fail it. This implies
4330                                                                                 // the channel is now on chain and our counterparty is
4331                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4332                                                                                 // problem, not ours.
4333                                                                         }
4334                                                                 }
4335                                                         }
4336                                                 }
4337                                         }
4338                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4339                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4340                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4341                                                 None => {
4342                                                         forwarding_channel_not_found!();
4343                                                         continue;
4344                                                 }
4345                                         };
4346                                         let per_peer_state = self.per_peer_state.read().unwrap();
4347                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4348                                         if peer_state_mutex_opt.is_none() {
4349                                                 forwarding_channel_not_found!();
4350                                                 continue;
4351                                         }
4352                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4353                                         let peer_state = &mut *peer_state_lock;
4354                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4355                                                 for forward_info in pending_forwards.drain(..) {
4356                                                         match forward_info {
4357                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4358                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4359                                                                         forward_info: PendingHTLCInfo {
4360                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4361                                                                                 routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
4362                                                                         },
4363                                                                 }) => {
4364                                                                         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);
4365                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4366                                                                                 short_channel_id: prev_short_channel_id,
4367                                                                                 user_channel_id: Some(prev_user_channel_id),
4368                                                                                 outpoint: prev_funding_outpoint,
4369                                                                                 htlc_id: prev_htlc_id,
4370                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4371                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4372                                                                                 phantom_shared_secret: None,
4373                                                                         });
4374                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4375                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4376                                                                                 onion_packet, skimmed_fee_msat, &self.fee_estimator,
4377                                                                                 &self.logger)
4378                                                                         {
4379                                                                                 if let ChannelError::Ignore(msg) = e {
4380                                                                                         log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4381                                                                                 } else {
4382                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4383                                                                                 }
4384                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4385                                                                                 failed_forwards.push((htlc_source, payment_hash,
4386                                                                                         HTLCFailReason::reason(failure_code, data),
4387                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4388                                                                                 ));
4389                                                                                 continue;
4390                                                                         }
4391                                                                 },
4392                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4393                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4394                                                                 },
4395                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4396                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4397                                                                         if let Err(e) = chan.queue_fail_htlc(
4398                                                                                 htlc_id, err_packet, &self.logger
4399                                                                         ) {
4400                                                                                 if let ChannelError::Ignore(msg) = e {
4401                                                                                         log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4402                                                                                 } else {
4403                                                                                         panic!("Stated return value requirements in queue_fail_htlc() were not met");
4404                                                                                 }
4405                                                                                 // fail-backs are best-effort, we probably already have one
4406                                                                                 // pending, and if not that's OK, if not, the channel is on
4407                                                                                 // the chain and sending the HTLC-Timeout is their problem.
4408                                                                                 continue;
4409                                                                         }
4410                                                                 },
4411                                                         }
4412                                                 }
4413                                         } else {
4414                                                 forwarding_channel_not_found!();
4415                                                 continue;
4416                                         }
4417                                 } else {
4418                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4419                                                 match forward_info {
4420                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4421                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4422                                                                 forward_info: PendingHTLCInfo {
4423                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4424                                                                         skimmed_fee_msat, ..
4425                                                                 }
4426                                                         }) => {
4427                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4428                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4429                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4430                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4431                                                                                                 payment_metadata, custom_tlvs };
4432                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4433                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4434                                                                         },
4435                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4436                                                                                 let onion_fields = RecipientOnionFields {
4437                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4438                                                                                         payment_metadata,
4439                                                                                         custom_tlvs,
4440                                                                                 };
4441                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4442                                                                                         payment_data, None, onion_fields)
4443                                                                         },
4444                                                                         _ => {
4445                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4446                                                                         }
4447                                                                 };
4448                                                                 let claimable_htlc = ClaimableHTLC {
4449                                                                         prev_hop: HTLCPreviousHopData {
4450                                                                                 short_channel_id: prev_short_channel_id,
4451                                                                                 user_channel_id: Some(prev_user_channel_id),
4452                                                                                 outpoint: prev_funding_outpoint,
4453                                                                                 htlc_id: prev_htlc_id,
4454                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4455                                                                                 phantom_shared_secret,
4456                                                                         },
4457                                                                         // We differentiate the received value from the sender intended value
4458                                                                         // if possible so that we don't prematurely mark MPP payments complete
4459                                                                         // if routing nodes overpay
4460                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4461                                                                         sender_intended_value: outgoing_amt_msat,
4462                                                                         timer_ticks: 0,
4463                                                                         total_value_received: None,
4464                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4465                                                                         cltv_expiry,
4466                                                                         onion_payload,
4467                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4468                                                                 };
4469
4470                                                                 let mut committed_to_claimable = false;
4471
4472                                                                 macro_rules! fail_htlc {
4473                                                                         ($htlc: expr, $payment_hash: expr) => {
4474                                                                                 debug_assert!(!committed_to_claimable);
4475                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4476                                                                                 htlc_msat_height_data.extend_from_slice(
4477                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4478                                                                                 );
4479                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4480                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4481                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4482                                                                                                 outpoint: prev_funding_outpoint,
4483                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4484                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4485                                                                                                 phantom_shared_secret,
4486                                                                                         }), payment_hash,
4487                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4488                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4489                                                                                 ));
4490                                                                                 continue 'next_forwardable_htlc;
4491                                                                         }
4492                                                                 }
4493                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4494                                                                 let mut receiver_node_id = self.our_network_pubkey;
4495                                                                 if phantom_shared_secret.is_some() {
4496                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4497                                                                                 .expect("Failed to get node_id for phantom node recipient");
4498                                                                 }
4499
4500                                                                 macro_rules! check_total_value {
4501                                                                         ($purpose: expr) => {{
4502                                                                                 let mut payment_claimable_generated = false;
4503                                                                                 let is_keysend = match $purpose {
4504                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4505                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4506                                                                                 };
4507                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4508                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4509                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4510                                                                                 }
4511                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4512                                                                                         .entry(payment_hash)
4513                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4514                                                                                         .or_insert_with(|| {
4515                                                                                                 committed_to_claimable = true;
4516                                                                                                 ClaimablePayment {
4517                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4518                                                                                                 }
4519                                                                                         });
4520                                                                                 if $purpose != claimable_payment.purpose {
4521                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4522                                                                                         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));
4523                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4524                                                                                 }
4525                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4526                                                                                         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);
4527                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4528                                                                                 }
4529                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4530                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4531                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4532                                                                                         }
4533                                                                                 } else {
4534                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4535                                                                                 }
4536                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4537                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4538                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4539                                                                                 for htlc in htlcs.iter() {
4540                                                                                         total_value += htlc.sender_intended_value;
4541                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4542                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4543                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4544                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4545                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4546                                                                                         }
4547                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4548                                                                                 }
4549                                                                                 // The condition determining whether an MPP is complete must
4550                                                                                 // match exactly the condition used in `timer_tick_occurred`
4551                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4552                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4553                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4554                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4555                                                                                                 &payment_hash);
4556                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4557                                                                                 } else if total_value >= claimable_htlc.total_msat {
4558                                                                                         #[allow(unused_assignments)] {
4559                                                                                                 committed_to_claimable = true;
4560                                                                                         }
4561                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4562                                                                                         htlcs.push(claimable_htlc);
4563                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4564                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4565                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4566                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4567                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4568                                                                                                 counterparty_skimmed_fee_msat);
4569                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4570                                                                                                 receiver_node_id: Some(receiver_node_id),
4571                                                                                                 payment_hash,
4572                                                                                                 purpose: $purpose,
4573                                                                                                 amount_msat,
4574                                                                                                 counterparty_skimmed_fee_msat,
4575                                                                                                 via_channel_id: Some(prev_channel_id),
4576                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4577                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4578                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4579                                                                                         }, None));
4580                                                                                         payment_claimable_generated = true;
4581                                                                                 } else {
4582                                                                                         // Nothing to do - we haven't reached the total
4583                                                                                         // payment value yet, wait until we receive more
4584                                                                                         // MPP parts.
4585                                                                                         htlcs.push(claimable_htlc);
4586                                                                                         #[allow(unused_assignments)] {
4587                                                                                                 committed_to_claimable = true;
4588                                                                                         }
4589                                                                                 }
4590                                                                                 payment_claimable_generated
4591                                                                         }}
4592                                                                 }
4593
4594                                                                 // Check that the payment hash and secret are known. Note that we
4595                                                                 // MUST take care to handle the "unknown payment hash" and
4596                                                                 // "incorrect payment secret" cases here identically or we'd expose
4597                                                                 // that we are the ultimate recipient of the given payment hash.
4598                                                                 // Further, we must not expose whether we have any other HTLCs
4599                                                                 // associated with the same payment_hash pending or not.
4600                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4601                                                                 match payment_secrets.entry(payment_hash) {
4602                                                                         hash_map::Entry::Vacant(_) => {
4603                                                                                 match claimable_htlc.onion_payload {
4604                                                                                         OnionPayload::Invoice { .. } => {
4605                                                                                                 let payment_data = payment_data.unwrap();
4606                                                                                                 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) {
4607                                                                                                         Ok(result) => result,
4608                                                                                                         Err(()) => {
4609                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4610                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4611                                                                                                         }
4612                                                                                                 };
4613                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4614                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4615                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4616                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4617                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4618                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4619                                                                                                         }
4620                                                                                                 }
4621                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4622                                                                                                         payment_preimage: payment_preimage.clone(),
4623                                                                                                         payment_secret: payment_data.payment_secret,
4624                                                                                                 };
4625                                                                                                 check_total_value!(purpose);
4626                                                                                         },
4627                                                                                         OnionPayload::Spontaneous(preimage) => {
4628                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4629                                                                                                 check_total_value!(purpose);
4630                                                                                         }
4631                                                                                 }
4632                                                                         },
4633                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4634                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4635                                                                                         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);
4636                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4637                                                                                 }
4638                                                                                 let payment_data = payment_data.unwrap();
4639                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4640                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4641                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4642                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4643                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4644                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4645                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4646                                                                                 } else {
4647                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4648                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4649                                                                                                 payment_secret: payment_data.payment_secret,
4650                                                                                         };
4651                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4652                                                                                         if payment_claimable_generated {
4653                                                                                                 inbound_payment.remove_entry();
4654                                                                                         }
4655                                                                                 }
4656                                                                         },
4657                                                                 };
4658                                                         },
4659                                                         HTLCForwardInfo::FailHTLC { .. } => {
4660                                                                 panic!("Got pending fail of our own HTLC");
4661                                                         }
4662                                                 }
4663                                         }
4664                                 }
4665                         }
4666                 }
4667
4668                 let best_block_height = self.best_block.read().unwrap().height();
4669                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4670                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4671                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4672
4673                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4674                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4675                 }
4676                 self.forward_htlcs(&mut phantom_receives);
4677
4678                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4679                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4680                 // nice to do the work now if we can rather than while we're trying to get messages in the
4681                 // network stack.
4682                 self.check_free_holding_cells();
4683
4684                 if new_events.is_empty() { return }
4685                 let mut events = self.pending_events.lock().unwrap();
4686                 events.append(&mut new_events);
4687         }
4688
4689         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4690         ///
4691         /// Expects the caller to have a total_consistency_lock read lock.
4692         fn process_background_events(&self) -> NotifyOption {
4693                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4694
4695                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4696
4697                 let mut background_events = Vec::new();
4698                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4699                 if background_events.is_empty() {
4700                         return NotifyOption::SkipPersistNoEvents;
4701                 }
4702
4703                 for event in background_events.drain(..) {
4704                         match event {
4705                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4706                                         // The channel has already been closed, so no use bothering to care about the
4707                                         // monitor updating completing.
4708                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4709                                 },
4710                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4711                                         let mut updated_chan = false;
4712                                         {
4713                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4714                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4715                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4716                                                         let peer_state = &mut *peer_state_lock;
4717                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4718                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4719                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4720                                                                                 updated_chan = true;
4721                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4722                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4723                                                                         } else {
4724                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4725                                                                         }
4726                                                                 },
4727                                                                 hash_map::Entry::Vacant(_) => {},
4728                                                         }
4729                                                 }
4730                                         }
4731                                         if !updated_chan {
4732                                                 // TODO: Track this as in-flight even though the channel is closed.
4733                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4734                                         }
4735                                 },
4736                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4737                                         let per_peer_state = self.per_peer_state.read().unwrap();
4738                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4739                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4740                                                 let peer_state = &mut *peer_state_lock;
4741                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4742                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4743                                                 } else {
4744                                                         let update_actions = peer_state.monitor_update_blocked_actions
4745                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4746                                                         mem::drop(peer_state_lock);
4747                                                         mem::drop(per_peer_state);
4748                                                         self.handle_monitor_update_completion_actions(update_actions);
4749                                                 }
4750                                         }
4751                                 },
4752                         }
4753                 }
4754                 NotifyOption::DoPersist
4755         }
4756
4757         #[cfg(any(test, feature = "_test_utils"))]
4758         /// Process background events, for functional testing
4759         pub fn test_process_background_events(&self) {
4760                 let _lck = self.total_consistency_lock.read().unwrap();
4761                 let _ = self.process_background_events();
4762         }
4763
4764         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4765                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4766                 // If the feerate has decreased by less than half, don't bother
4767                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4768                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4769                                 log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4770                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4771                         }
4772                         return NotifyOption::SkipPersistNoEvents;
4773                 }
4774                 if !chan.context.is_live() {
4775                         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).",
4776                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4777                         return NotifyOption::SkipPersistNoEvents;
4778                 }
4779                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4780                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4781
4782                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4783                 NotifyOption::DoPersist
4784         }
4785
4786         #[cfg(fuzzing)]
4787         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4788         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4789         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4790         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4791         pub fn maybe_update_chan_fees(&self) {
4792                 PersistenceNotifierGuard::optionally_notify(self, || {
4793                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4794
4795                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4796                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4797
4798                         let per_peer_state = self.per_peer_state.read().unwrap();
4799                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4800                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4801                                 let peer_state = &mut *peer_state_lock;
4802                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4803                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4804                                 ) {
4805                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4806                                                 min_mempool_feerate
4807                                         } else {
4808                                                 normal_feerate
4809                                         };
4810                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4811                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4812                                 }
4813                         }
4814
4815                         should_persist
4816                 });
4817         }
4818
4819         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4820         ///
4821         /// This currently includes:
4822         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4823         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4824         ///    than a minute, informing the network that they should no longer attempt to route over
4825         ///    the channel.
4826         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4827         ///    with the current [`ChannelConfig`].
4828         ///  * Removing peers which have disconnected but and no longer have any channels.
4829         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4830         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4831         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4832         ///    The latter is determined using the system clock in `std` and the highest seen block time
4833         ///    minus two hours in `no-std`.
4834         ///
4835         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4836         /// estimate fetches.
4837         ///
4838         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4839         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4840         pub fn timer_tick_occurred(&self) {
4841                 PersistenceNotifierGuard::optionally_notify(self, || {
4842                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4843
4844                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4845                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4846
4847                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4848                         let mut timed_out_mpp_htlcs = Vec::new();
4849                         let mut pending_peers_awaiting_removal = Vec::new();
4850                         let mut shutdown_channels = Vec::new();
4851
4852                         let mut process_unfunded_channel_tick = |
4853                                 chan_id: &ChannelId,
4854                                 context: &mut ChannelContext<SP>,
4855                                 unfunded_context: &mut UnfundedChannelContext,
4856                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4857                                 counterparty_node_id: PublicKey,
4858                         | {
4859                                 context.maybe_expire_prev_config();
4860                                 if unfunded_context.should_expire_unfunded_channel() {
4861                                         log_error!(self.logger,
4862                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4863                                         update_maps_on_chan_removal!(self, &context);
4864                                         self.issue_channel_close_events(&context, ClosureReason::HolderForceClosed);
4865                                         shutdown_channels.push(context.force_shutdown(false));
4866                                         pending_msg_events.push(MessageSendEvent::HandleError {
4867                                                 node_id: counterparty_node_id,
4868                                                 action: msgs::ErrorAction::SendErrorMessage {
4869                                                         msg: msgs::ErrorMessage {
4870                                                                 channel_id: *chan_id,
4871                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4872                                                         },
4873                                                 },
4874                                         });
4875                                         false
4876                                 } else {
4877                                         true
4878                                 }
4879                         };
4880
4881                         {
4882                                 let per_peer_state = self.per_peer_state.read().unwrap();
4883                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4884                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4885                                         let peer_state = &mut *peer_state_lock;
4886                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4887                                         let counterparty_node_id = *counterparty_node_id;
4888                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4889                                                 match phase {
4890                                                         ChannelPhase::Funded(chan) => {
4891                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4892                                                                         min_mempool_feerate
4893                                                                 } else {
4894                                                                         normal_feerate
4895                                                                 };
4896                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4897                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4898
4899                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4900                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4901                                                                         handle_errors.push((Err(err), counterparty_node_id));
4902                                                                         if needs_close { return false; }
4903                                                                 }
4904
4905                                                                 match chan.channel_update_status() {
4906                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4907                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4908                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4909                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4910                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4911                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4912                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4913                                                                                 n += 1;
4914                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4915                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4916                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4917                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4918                                                                                                         msg: update
4919                                                                                                 });
4920                                                                                         }
4921                                                                                         should_persist = NotifyOption::DoPersist;
4922                                                                                 } else {
4923                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4924                                                                                 }
4925                                                                         },
4926                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4927                                                                                 n += 1;
4928                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4929                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4930                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4931                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4932                                                                                                         msg: update
4933                                                                                                 });
4934                                                                                         }
4935                                                                                         should_persist = NotifyOption::DoPersist;
4936                                                                                 } else {
4937                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4938                                                                                 }
4939                                                                         },
4940                                                                         _ => {},
4941                                                                 }
4942
4943                                                                 chan.context.maybe_expire_prev_config();
4944
4945                                                                 if chan.should_disconnect_peer_awaiting_response() {
4946                                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4947                                                                                         counterparty_node_id, chan_id);
4948                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4949                                                                                 node_id: counterparty_node_id,
4950                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4951                                                                                         msg: msgs::WarningMessage {
4952                                                                                                 channel_id: *chan_id,
4953                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4954                                                                                         },
4955                                                                                 },
4956                                                                         });
4957                                                                 }
4958
4959                                                                 true
4960                                                         },
4961                                                         ChannelPhase::UnfundedInboundV1(chan) => {
4962                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4963                                                                         pending_msg_events, counterparty_node_id)
4964                                                         },
4965                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
4966                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4967                                                                         pending_msg_events, counterparty_node_id)
4968                                                         },
4969                                                 }
4970                                         });
4971
4972                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4973                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4974                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
4975                                                         peer_state.pending_msg_events.push(
4976                                                                 events::MessageSendEvent::HandleError {
4977                                                                         node_id: counterparty_node_id,
4978                                                                         action: msgs::ErrorAction::SendErrorMessage {
4979                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4980                                                                         },
4981                                                                 }
4982                                                         );
4983                                                 }
4984                                         }
4985                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4986
4987                                         if peer_state.ok_to_remove(true) {
4988                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4989                                         }
4990                                 }
4991                         }
4992
4993                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4994                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4995                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4996                         // we therefore need to remove the peer from `peer_state` separately.
4997                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4998                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4999                         // negative effects on parallelism as much as possible.
5000                         if pending_peers_awaiting_removal.len() > 0 {
5001                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
5002                                 for counterparty_node_id in pending_peers_awaiting_removal {
5003                                         match per_peer_state.entry(counterparty_node_id) {
5004                                                 hash_map::Entry::Occupied(entry) => {
5005                                                         // Remove the entry if the peer is still disconnected and we still
5006                                                         // have no channels to the peer.
5007                                                         let remove_entry = {
5008                                                                 let peer_state = entry.get().lock().unwrap();
5009                                                                 peer_state.ok_to_remove(true)
5010                                                         };
5011                                                         if remove_entry {
5012                                                                 entry.remove_entry();
5013                                                         }
5014                                                 },
5015                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
5016                                         }
5017                                 }
5018                         }
5019
5020                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
5021                                 if payment.htlcs.is_empty() {
5022                                         // This should be unreachable
5023                                         debug_assert!(false);
5024                                         return false;
5025                                 }
5026                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
5027                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
5028                                         // In this case we're not going to handle any timeouts of the parts here.
5029                                         // This condition determining whether the MPP is complete here must match
5030                                         // exactly the condition used in `process_pending_htlc_forwards`.
5031                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5032                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5033                                         {
5034                                                 return true;
5035                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5036                                                 htlc.timer_ticks += 1;
5037                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5038                                         }) {
5039                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5040                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5041                                                 return false;
5042                                         }
5043                                 }
5044                                 true
5045                         });
5046
5047                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5048                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5049                                 let reason = HTLCFailReason::from_failure_code(23);
5050                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5051                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5052                         }
5053
5054                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5055                                 let _ = handle_error!(self, err, counterparty_node_id);
5056                         }
5057
5058                         for shutdown_res in shutdown_channels {
5059                                 self.finish_close_channel(shutdown_res);
5060                         }
5061
5062                         #[cfg(feature = "std")]
5063                         let duration_since_epoch = std::time::SystemTime::now()
5064                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5065                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5066                         #[cfg(not(feature = "std"))]
5067                         let duration_since_epoch = Duration::from_secs(
5068                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5069                         );
5070
5071                         self.pending_outbound_payments.remove_stale_payments(
5072                                 duration_since_epoch, &self.pending_events
5073                         );
5074
5075                         // Technically we don't need to do this here, but if we have holding cell entries in a
5076                         // channel that need freeing, it's better to do that here and block a background task
5077                         // than block the message queueing pipeline.
5078                         if self.check_free_holding_cells() {
5079                                 should_persist = NotifyOption::DoPersist;
5080                         }
5081
5082                         should_persist
5083                 });
5084         }
5085
5086         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5087         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5088         /// along the path (including in our own channel on which we received it).
5089         ///
5090         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5091         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5092         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5093         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5094         ///
5095         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5096         /// [`ChannelManager::claim_funds`]), you should still monitor for
5097         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5098         /// startup during which time claims that were in-progress at shutdown may be replayed.
5099         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5100                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5101         }
5102
5103         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5104         /// reason for the failure.
5105         ///
5106         /// See [`FailureCode`] for valid failure codes.
5107         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5108                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5109
5110                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5111                 if let Some(payment) = removed_source {
5112                         for htlc in payment.htlcs {
5113                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5114                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5115                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5116                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5117                         }
5118                 }
5119         }
5120
5121         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5122         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5123                 match failure_code {
5124                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5125                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5126                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5127                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5128                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5129                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5130                         },
5131                         FailureCode::InvalidOnionPayload(data) => {
5132                                 let fail_data = match data {
5133                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5134                                         None => Vec::new(),
5135                                 };
5136                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5137                         }
5138                 }
5139         }
5140
5141         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5142         /// that we want to return and a channel.
5143         ///
5144         /// This is for failures on the channel on which the HTLC was *received*, not failures
5145         /// forwarding
5146         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5147                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5148                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5149                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5150                 // an inbound SCID alias before the real SCID.
5151                 let scid_pref = if chan.context.should_announce() {
5152                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5153                 } else {
5154                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5155                 };
5156                 if let Some(scid) = scid_pref {
5157                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5158                 } else {
5159                         (0x4000|10, Vec::new())
5160                 }
5161         }
5162
5163
5164         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5165         /// that we want to return and a channel.
5166         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5167                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5168                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5169                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5170                         if desired_err_code == 0x1000 | 20 {
5171                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5172                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5173                                 0u16.write(&mut enc).expect("Writes cannot fail");
5174                         }
5175                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5176                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5177                         upd.write(&mut enc).expect("Writes cannot fail");
5178                         (desired_err_code, enc.0)
5179                 } else {
5180                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5181                         // which means we really shouldn't have gotten a payment to be forwarded over this
5182                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5183                         // PERM|no_such_channel should be fine.
5184                         (0x4000|10, Vec::new())
5185                 }
5186         }
5187
5188         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5189         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5190         // be surfaced to the user.
5191         fn fail_holding_cell_htlcs(
5192                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5193                 counterparty_node_id: &PublicKey
5194         ) {
5195                 let (failure_code, onion_failure_data) = {
5196                         let per_peer_state = self.per_peer_state.read().unwrap();
5197                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5198                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5199                                 let peer_state = &mut *peer_state_lock;
5200                                 match peer_state.channel_by_id.entry(channel_id) {
5201                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5202                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5203                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5204                                                 } else {
5205                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5206                                                         debug_assert!(false);
5207                                                         (0x4000|10, Vec::new())
5208                                                 }
5209                                         },
5210                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5211                                 }
5212                         } else { (0x4000|10, Vec::new()) }
5213                 };
5214
5215                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5216                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5217                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5218                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5219                 }
5220         }
5221
5222         /// Fails an HTLC backwards to the sender of it to us.
5223         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5224         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5225                 // Ensure that no peer state channel storage lock is held when calling this function.
5226                 // This ensures that future code doesn't introduce a lock-order requirement for
5227                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5228                 // this function with any `per_peer_state` peer lock acquired would.
5229                 #[cfg(debug_assertions)]
5230                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5231                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5232                 }
5233
5234                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5235                 //identify whether we sent it or not based on the (I presume) very different runtime
5236                 //between the branches here. We should make this async and move it into the forward HTLCs
5237                 //timer handling.
5238
5239                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5240                 // from block_connected which may run during initialization prior to the chain_monitor
5241                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5242                 match source {
5243                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5244                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5245                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5246                                         &self.pending_events, &self.logger)
5247                                 { self.push_pending_forwards_ev(); }
5248                         },
5249                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint, .. }) => {
5250                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", &payment_hash, onion_error);
5251                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
5252
5253                                 let mut push_forward_ev = false;
5254                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5255                                 if forward_htlcs.is_empty() {
5256                                         push_forward_ev = true;
5257                                 }
5258                                 match forward_htlcs.entry(*short_channel_id) {
5259                                         hash_map::Entry::Occupied(mut entry) => {
5260                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
5261                                         },
5262                                         hash_map::Entry::Vacant(entry) => {
5263                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
5264                                         }
5265                                 }
5266                                 mem::drop(forward_htlcs);
5267                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5268                                 let mut pending_events = self.pending_events.lock().unwrap();
5269                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5270                                         prev_channel_id: outpoint.to_channel_id(),
5271                                         failed_next_destination: destination,
5272                                 }, None));
5273                         },
5274                 }
5275         }
5276
5277         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5278         /// [`MessageSendEvent`]s needed to claim the payment.
5279         ///
5280         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5281         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5282         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5283         /// successful. It will generally be available in the next [`process_pending_events`] call.
5284         ///
5285         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5286         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5287         /// event matches your expectation. If you fail to do so and call this method, you may provide
5288         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5289         ///
5290         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5291         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5292         /// [`claim_funds_with_known_custom_tlvs`].
5293         ///
5294         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5295         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5296         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5297         /// [`process_pending_events`]: EventsProvider::process_pending_events
5298         /// [`create_inbound_payment`]: Self::create_inbound_payment
5299         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5300         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5301         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5302                 self.claim_payment_internal(payment_preimage, false);
5303         }
5304
5305         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5306         /// even type numbers.
5307         ///
5308         /// # Note
5309         ///
5310         /// You MUST check you've understood all even TLVs before using this to
5311         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5312         ///
5313         /// [`claim_funds`]: Self::claim_funds
5314         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5315                 self.claim_payment_internal(payment_preimage, true);
5316         }
5317
5318         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5319                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5320
5321                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5322
5323                 let mut sources = {
5324                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5325                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5326                                 let mut receiver_node_id = self.our_network_pubkey;
5327                                 for htlc in payment.htlcs.iter() {
5328                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5329                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5330                                                         .expect("Failed to get node_id for phantom node recipient");
5331                                                 receiver_node_id = phantom_pubkey;
5332                                                 break;
5333                                         }
5334                                 }
5335
5336                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5337                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5338                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5339                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5340                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5341                                 });
5342                                 if dup_purpose.is_some() {
5343                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5344                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5345                                                 &payment_hash);
5346                                 }
5347
5348                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5349                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5350                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5351                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5352                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5353                                                 mem::drop(claimable_payments);
5354                                                 for htlc in payment.htlcs {
5355                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5356                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5357                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5358                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5359                                                 }
5360                                                 return;
5361                                         }
5362                                 }
5363
5364                                 payment.htlcs
5365                         } else { return; }
5366                 };
5367                 debug_assert!(!sources.is_empty());
5368
5369                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5370                 // and when we got here we need to check that the amount we're about to claim matches the
5371                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5372                 // the MPP parts all have the same `total_msat`.
5373                 let mut claimable_amt_msat = 0;
5374                 let mut prev_total_msat = None;
5375                 let mut expected_amt_msat = None;
5376                 let mut valid_mpp = true;
5377                 let mut errs = Vec::new();
5378                 let per_peer_state = self.per_peer_state.read().unwrap();
5379                 for htlc in sources.iter() {
5380                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5381                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5382                                 debug_assert!(false);
5383                                 valid_mpp = false;
5384                                 break;
5385                         }
5386                         prev_total_msat = Some(htlc.total_msat);
5387
5388                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5389                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5390                                 debug_assert!(false);
5391                                 valid_mpp = false;
5392                                 break;
5393                         }
5394                         expected_amt_msat = htlc.total_value_received;
5395                         claimable_amt_msat += htlc.value;
5396                 }
5397                 mem::drop(per_peer_state);
5398                 if sources.is_empty() || expected_amt_msat.is_none() {
5399                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5400                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5401                         return;
5402                 }
5403                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5404                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5405                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5406                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5407                         return;
5408                 }
5409                 if valid_mpp {
5410                         for htlc in sources.drain(..) {
5411                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5412                                         htlc.prev_hop, payment_preimage,
5413                                         |_, definitely_duplicate| {
5414                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5415                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5416                                         }
5417                                 ) {
5418                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5419                                                 // We got a temporary failure updating monitor, but will claim the
5420                                                 // HTLC when the monitor updating is restored (or on chain).
5421                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5422                                         } else { errs.push((pk, err)); }
5423                                 }
5424                         }
5425                 }
5426                 if !valid_mpp {
5427                         for htlc in sources.drain(..) {
5428                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5429                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5430                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5431                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5432                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5433                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5434                         }
5435                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5436                 }
5437
5438                 // Now we can handle any errors which were generated.
5439                 for (counterparty_node_id, err) in errs.drain(..) {
5440                         let res: Result<(), _> = Err(err);
5441                         let _ = handle_error!(self, res, counterparty_node_id);
5442                 }
5443         }
5444
5445         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5446                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5447         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5448                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5449
5450                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5451                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5452                 // `BackgroundEvent`s.
5453                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5454
5455                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5456                 // the required mutexes are not held before we start.
5457                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5458                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5459
5460                 {
5461                         let per_peer_state = self.per_peer_state.read().unwrap();
5462                         let chan_id = prev_hop.outpoint.to_channel_id();
5463                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5464                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5465                                 None => None
5466                         };
5467
5468                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5469                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5470                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5471                         ).unwrap_or(None);
5472
5473                         if peer_state_opt.is_some() {
5474                                 let mut peer_state_lock = peer_state_opt.unwrap();
5475                                 let peer_state = &mut *peer_state_lock;
5476                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5477                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5478                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5479                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5480
5481                                                 match fulfill_res {
5482                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5483                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5484                                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5485                                                                                 chan_id, action);
5486                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5487                                                                 }
5488                                                                 if !during_init {
5489                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5490                                                                                 peer_state, per_peer_state, chan);
5491                                                                 } else {
5492                                                                         // If we're running during init we cannot update a monitor directly -
5493                                                                         // they probably haven't actually been loaded yet. Instead, push the
5494                                                                         // monitor update as a background event.
5495                                                                         self.pending_background_events.lock().unwrap().push(
5496                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5497                                                                                         counterparty_node_id,
5498                                                                                         funding_txo: prev_hop.outpoint,
5499                                                                                         update: monitor_update.clone(),
5500                                                                                 });
5501                                                                 }
5502                                                         }
5503                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5504                                                                 let action = if let Some(action) = completion_action(None, true) {
5505                                                                         action
5506                                                                 } else {
5507                                                                         return Ok(());
5508                                                                 };
5509                                                                 mem::drop(peer_state_lock);
5510
5511                                                                 log_trace!(self.logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5512                                                                         chan_id, action);
5513                                                                 let (node_id, funding_outpoint, blocker) =
5514                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5515                                                                         downstream_counterparty_node_id: node_id,
5516                                                                         downstream_funding_outpoint: funding_outpoint,
5517                                                                         blocking_action: blocker,
5518                                                                 } = action {
5519                                                                         (node_id, funding_outpoint, blocker)
5520                                                                 } else {
5521                                                                         debug_assert!(false,
5522                                                                                 "Duplicate claims should always free another channel immediately");
5523                                                                         return Ok(());
5524                                                                 };
5525                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5526                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5527                                                                         if let Some(blockers) = peer_state
5528                                                                                 .actions_blocking_raa_monitor_updates
5529                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5530                                                                         {
5531                                                                                 let mut found_blocker = false;
5532                                                                                 blockers.retain(|iter| {
5533                                                                                         // Note that we could actually be blocked, in
5534                                                                                         // which case we need to only remove the one
5535                                                                                         // blocker which was added duplicatively.
5536                                                                                         let first_blocker = !found_blocker;
5537                                                                                         if *iter == blocker { found_blocker = true; }
5538                                                                                         *iter != blocker || !first_blocker
5539                                                                                 });
5540                                                                                 debug_assert!(found_blocker);
5541                                                                         }
5542                                                                 } else {
5543                                                                         debug_assert!(false);
5544                                                                 }
5545                                                         }
5546                                                 }
5547                                         }
5548                                         return Ok(());
5549                                 }
5550                         }
5551                 }
5552                 let preimage_update = ChannelMonitorUpdate {
5553                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5554                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5555                                 payment_preimage,
5556                         }],
5557                 };
5558
5559                 if !during_init {
5560                         // We update the ChannelMonitor on the backward link, after
5561                         // receiving an `update_fulfill_htlc` from the forward link.
5562                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5563                         if update_res != ChannelMonitorUpdateStatus::Completed {
5564                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5565                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5566                                 // channel, or we must have an ability to receive the same event and try
5567                                 // again on restart.
5568                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5569                                         payment_preimage, update_res);
5570                         }
5571                 } else {
5572                         // If we're running during init we cannot update a monitor directly - they probably
5573                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5574                         // event.
5575                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5576                         // channel is already closed) we need to ultimately handle the monitor update
5577                         // completion action only after we've completed the monitor update. This is the only
5578                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5579                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5580                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5581                         // complete the monitor update completion action from `completion_action`.
5582                         self.pending_background_events.lock().unwrap().push(
5583                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5584                                         prev_hop.outpoint, preimage_update,
5585                                 )));
5586                 }
5587                 // Note that we do process the completion action here. This totally could be a
5588                 // duplicate claim, but we have no way of knowing without interrogating the
5589                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5590                 // generally always allowed to be duplicative (and it's specifically noted in
5591                 // `PaymentForwarded`).
5592                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5593                 Ok(())
5594         }
5595
5596         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5597                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5598         }
5599
5600         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5601                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5602                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5603         ) {
5604                 match source {
5605                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5606                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5607                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5608                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5609                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5610                                 }
5611                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5612                                         channel_funding_outpoint: next_channel_outpoint,
5613                                         counterparty_node_id: path.hops[0].pubkey,
5614                                 };
5615                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5616                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5617                                         &self.logger);
5618                         },
5619                         HTLCSource::PreviousHopData(hop_data) => {
5620                                 let prev_outpoint = hop_data.outpoint;
5621                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5622                                 #[cfg(debug_assertions)]
5623                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5624                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5625                                         |htlc_claim_value_msat, definitely_duplicate| {
5626                                                 let chan_to_release =
5627                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5628                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5629                                                         } else {
5630                                                                 // We can only get `None` here if we are processing a
5631                                                                 // `ChannelMonitor`-originated event, in which case we
5632                                                                 // don't care about ensuring we wake the downstream
5633                                                                 // channel's monitor updating - the channel is already
5634                                                                 // closed.
5635                                                                 None
5636                                                         };
5637
5638                                                 if definitely_duplicate && startup_replay {
5639                                                         // On startup we may get redundant claims which are related to
5640                                                         // monitor updates still in flight. In that case, we shouldn't
5641                                                         // immediately free, but instead let that monitor update complete
5642                                                         // in the background.
5643                                                         #[cfg(debug_assertions)] {
5644                                                                 let background_events = self.pending_background_events.lock().unwrap();
5645                                                                 // There should be a `BackgroundEvent` pending...
5646                                                                 assert!(background_events.iter().any(|ev| {
5647                                                                         match ev {
5648                                                                                 // to apply a monitor update that blocked the claiming channel,
5649                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5650                                                                                         funding_txo, update, ..
5651                                                                                 } => {
5652                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5653                                                                                                 assert!(update.updates.iter().any(|upd|
5654                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5655                                                                                                                 payment_preimage: update_preimage
5656                                                                                                         } = upd {
5657                                                                                                                 payment_preimage == *update_preimage
5658                                                                                                         } else { false }
5659                                                                                                 ), "{:?}", update);
5660                                                                                                 true
5661                                                                                         } else { false }
5662                                                                                 },
5663                                                                                 // or the channel we'd unblock is already closed,
5664                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5665                                                                                         (funding_txo, monitor_update)
5666                                                                                 ) => {
5667                                                                                         if *funding_txo == next_channel_outpoint {
5668                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5669                                                                                                 assert!(matches!(
5670                                                                                                         monitor_update.updates[0],
5671                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5672                                                                                                 ));
5673                                                                                                 true
5674                                                                                         } else { false }
5675                                                                                 },
5676                                                                                 // or the monitor update has completed and will unblock
5677                                                                                 // immediately once we get going.
5678                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5679                                                                                         channel_id, ..
5680                                                                                 } =>
5681                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5682                                                                         }
5683                                                                 }), "{:?}", *background_events);
5684                                                         }
5685                                                         None
5686                                                 } else if definitely_duplicate {
5687                                                         if let Some(other_chan) = chan_to_release {
5688                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5689                                                                         downstream_counterparty_node_id: other_chan.0,
5690                                                                         downstream_funding_outpoint: other_chan.1,
5691                                                                         blocking_action: other_chan.2,
5692                                                                 })
5693                                                         } else { None }
5694                                                 } else {
5695                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5696                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5697                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5698                                                                 } else { None }
5699                                                         } else { None };
5700                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5701                                                                 event: events::Event::PaymentForwarded {
5702                                                                         fee_earned_msat,
5703                                                                         claim_from_onchain_tx: from_onchain,
5704                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5705                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5706                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5707                                                                 },
5708                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5709                                                         })
5710                                                 }
5711                                         });
5712                                 if let Err((pk, err)) = res {
5713                                         let result: Result<(), _> = Err(err);
5714                                         let _ = handle_error!(self, result, pk);
5715                                 }
5716                         },
5717                 }
5718         }
5719
5720         /// Gets the node_id held by this ChannelManager
5721         pub fn get_our_node_id(&self) -> PublicKey {
5722                 self.our_network_pubkey.clone()
5723         }
5724
5725         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5726                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5727                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5728                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5729
5730                 for action in actions.into_iter() {
5731                         match action {
5732                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5733                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5734                                         if let Some(ClaimingPayment {
5735                                                 amount_msat,
5736                                                 payment_purpose: purpose,
5737                                                 receiver_node_id,
5738                                                 htlcs,
5739                                                 sender_intended_value: sender_intended_total_msat,
5740                                         }) = payment {
5741                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5742                                                         payment_hash,
5743                                                         purpose,
5744                                                         amount_msat,
5745                                                         receiver_node_id: Some(receiver_node_id),
5746                                                         htlcs,
5747                                                         sender_intended_total_msat,
5748                                                 }, None));
5749                                         }
5750                                 },
5751                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5752                                         event, downstream_counterparty_and_funding_outpoint
5753                                 } => {
5754                                         self.pending_events.lock().unwrap().push_back((event, None));
5755                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5756                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5757                                         }
5758                                 },
5759                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5760                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5761                                 } => {
5762                                         self.handle_monitor_update_release(
5763                                                 downstream_counterparty_node_id,
5764                                                 downstream_funding_outpoint,
5765                                                 Some(blocking_action),
5766                                         );
5767                                 },
5768                         }
5769                 }
5770         }
5771
5772         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5773         /// update completion.
5774         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5775                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5776                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5777                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5778                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5779         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5780                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5781                         &channel.context.channel_id(),
5782                         if raa.is_some() { "an" } else { "no" },
5783                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5784                         if funding_broadcastable.is_some() { "" } else { "not " },
5785                         if channel_ready.is_some() { "sending" } else { "without" },
5786                         if announcement_sigs.is_some() { "sending" } else { "without" });
5787
5788                 let mut htlc_forwards = None;
5789
5790                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5791                 if !pending_forwards.is_empty() {
5792                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5793                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5794                 }
5795
5796                 if let Some(msg) = channel_ready {
5797                         send_channel_ready!(self, pending_msg_events, channel, msg);
5798                 }
5799                 if let Some(msg) = announcement_sigs {
5800                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5801                                 node_id: counterparty_node_id,
5802                                 msg,
5803                         });
5804                 }
5805
5806                 macro_rules! handle_cs { () => {
5807                         if let Some(update) = commitment_update {
5808                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5809                                         node_id: counterparty_node_id,
5810                                         updates: update,
5811                                 });
5812                         }
5813                 } }
5814                 macro_rules! handle_raa { () => {
5815                         if let Some(revoke_and_ack) = raa {
5816                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5817                                         node_id: counterparty_node_id,
5818                                         msg: revoke_and_ack,
5819                                 });
5820                         }
5821                 } }
5822                 match order {
5823                         RAACommitmentOrder::CommitmentFirst => {
5824                                 handle_cs!();
5825                                 handle_raa!();
5826                         },
5827                         RAACommitmentOrder::RevokeAndACKFirst => {
5828                                 handle_raa!();
5829                                 handle_cs!();
5830                         },
5831                 }
5832
5833                 if let Some(tx) = funding_broadcastable {
5834                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5835                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5836                 }
5837
5838                 {
5839                         let mut pending_events = self.pending_events.lock().unwrap();
5840                         emit_channel_pending_event!(pending_events, channel);
5841                         emit_channel_ready_event!(pending_events, channel);
5842                 }
5843
5844                 htlc_forwards
5845         }
5846
5847         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5848                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5849
5850                 let counterparty_node_id = match counterparty_node_id {
5851                         Some(cp_id) => cp_id.clone(),
5852                         None => {
5853                                 // TODO: Once we can rely on the counterparty_node_id from the
5854                                 // monitor event, this and the id_to_peer map should be removed.
5855                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5856                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5857                                         Some(cp_id) => cp_id.clone(),
5858                                         None => return,
5859                                 }
5860                         }
5861                 };
5862                 let per_peer_state = self.per_peer_state.read().unwrap();
5863                 let mut peer_state_lock;
5864                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5865                 if peer_state_mutex_opt.is_none() { return }
5866                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5867                 let peer_state = &mut *peer_state_lock;
5868                 let channel =
5869                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5870                                 chan
5871                         } else {
5872                                 let update_actions = peer_state.monitor_update_blocked_actions
5873                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5874                                 mem::drop(peer_state_lock);
5875                                 mem::drop(per_peer_state);
5876                                 self.handle_monitor_update_completion_actions(update_actions);
5877                                 return;
5878                         };
5879                 let remaining_in_flight =
5880                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5881                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5882                                 pending.len()
5883                         } else { 0 };
5884                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5885                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5886                         remaining_in_flight);
5887                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5888                         return;
5889                 }
5890                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5891         }
5892
5893         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5894         ///
5895         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5896         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5897         /// the channel.
5898         ///
5899         /// The `user_channel_id` parameter will be provided back in
5900         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5901         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5902         ///
5903         /// Note that this method will return an error and reject the channel, if it requires support
5904         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5905         /// used to accept such channels.
5906         ///
5907         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5908         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5909         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5910                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5911         }
5912
5913         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5914         /// it as confirmed immediately.
5915         ///
5916         /// The `user_channel_id` parameter will be provided back in
5917         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5918         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5919         ///
5920         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5921         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5922         ///
5923         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5924         /// transaction and blindly assumes that it will eventually confirm.
5925         ///
5926         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5927         /// does not pay to the correct script the correct amount, *you will lose funds*.
5928         ///
5929         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5930         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5931         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5932                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5933         }
5934
5935         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5936                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5937
5938                 let peers_without_funded_channels =
5939                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5940                 let per_peer_state = self.per_peer_state.read().unwrap();
5941                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5942                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5943                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5944                 let peer_state = &mut *peer_state_lock;
5945                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5946
5947                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5948                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5949                 // that we can delay allocating the SCID until after we're sure that the checks below will
5950                 // succeed.
5951                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5952                         Some(unaccepted_channel) => {
5953                                 let best_block_height = self.best_block.read().unwrap().height();
5954                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5955                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5956                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5957                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5958                         }
5959                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5960                 }?;
5961
5962                 if accept_0conf {
5963                         // This should have been correctly configured by the call to InboundV1Channel::new.
5964                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5965                 } else if channel.context.get_channel_type().requires_zero_conf() {
5966                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5967                                 node_id: channel.context.get_counterparty_node_id(),
5968                                 action: msgs::ErrorAction::SendErrorMessage{
5969                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5970                                 }
5971                         };
5972                         peer_state.pending_msg_events.push(send_msg_err_event);
5973                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5974                 } else {
5975                         // If this peer already has some channels, a new channel won't increase our number of peers
5976                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5977                         // channels per-peer we can accept channels from a peer with existing ones.
5978                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5979                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5980                                         node_id: channel.context.get_counterparty_node_id(),
5981                                         action: msgs::ErrorAction::SendErrorMessage{
5982                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5983                                         }
5984                                 };
5985                                 peer_state.pending_msg_events.push(send_msg_err_event);
5986                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5987                         }
5988                 }
5989
5990                 // Now that we know we have a channel, assign an outbound SCID alias.
5991                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5992                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5993
5994                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5995                         node_id: channel.context.get_counterparty_node_id(),
5996                         msg: channel.accept_inbound_channel(),
5997                 });
5998
5999                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
6000
6001                 Ok(())
6002         }
6003
6004         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
6005         /// or 0-conf channels.
6006         ///
6007         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6008         /// non-0-conf channels we have with the peer.
6009         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6010         where Filter: Fn(&PeerState<SP>) -> bool {
6011                 let mut peers_without_funded_channels = 0;
6012                 let best_block_height = self.best_block.read().unwrap().height();
6013                 {
6014                         let peer_state_lock = self.per_peer_state.read().unwrap();
6015                         for (_, peer_mtx) in peer_state_lock.iter() {
6016                                 let peer = peer_mtx.lock().unwrap();
6017                                 if !maybe_count_peer(&*peer) { continue; }
6018                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6019                                 if num_unfunded_channels == peer.total_channel_count() {
6020                                         peers_without_funded_channels += 1;
6021                                 }
6022                         }
6023                 }
6024                 return peers_without_funded_channels;
6025         }
6026
6027         fn unfunded_channel_count(
6028                 peer: &PeerState<SP>, best_block_height: u32
6029         ) -> usize {
6030                 let mut num_unfunded_channels = 0;
6031                 for (_, phase) in peer.channel_by_id.iter() {
6032                         match phase {
6033                                 ChannelPhase::Funded(chan) => {
6034                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6035                                         // which have not yet had any confirmations on-chain.
6036                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6037                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6038                                         {
6039                                                 num_unfunded_channels += 1;
6040                                         }
6041                                 },
6042                                 ChannelPhase::UnfundedInboundV1(chan) => {
6043                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6044                                                 num_unfunded_channels += 1;
6045                                         }
6046                                 },
6047                                 ChannelPhase::UnfundedOutboundV1(_) => {
6048                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6049                                         continue;
6050                                 }
6051                         }
6052                 }
6053                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6054         }
6055
6056         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6057                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6058                 // likely to be lost on restart!
6059                 if msg.chain_hash != self.chain_hash {
6060                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
6061                 }
6062
6063                 if !self.default_configuration.accept_inbound_channels {
6064                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6065                 }
6066
6067                 // Get the number of peers with channels, but without funded ones. We don't care too much
6068                 // about peers that never open a channel, so we filter by peers that have at least one
6069                 // channel, and then limit the number of those with unfunded channels.
6070                 let channeled_peers_without_funding =
6071                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6072
6073                 let per_peer_state = self.per_peer_state.read().unwrap();
6074                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6075                     .ok_or_else(|| {
6076                                 debug_assert!(false);
6077                                 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())
6078                         })?;
6079                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6080                 let peer_state = &mut *peer_state_lock;
6081
6082                 // If this peer already has some channels, a new channel won't increase our number of peers
6083                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6084                 // channels per-peer we can accept channels from a peer with existing ones.
6085                 if peer_state.total_channel_count() == 0 &&
6086                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6087                         !self.default_configuration.manually_accept_inbound_channels
6088                 {
6089                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6090                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6091                                 msg.temporary_channel_id.clone()));
6092                 }
6093
6094                 let best_block_height = self.best_block.read().unwrap().height();
6095                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6096                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6097                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6098                                 msg.temporary_channel_id.clone()));
6099                 }
6100
6101                 let channel_id = msg.temporary_channel_id;
6102                 let channel_exists = peer_state.has_channel(&channel_id);
6103                 if channel_exists {
6104                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
6105                 }
6106
6107                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6108                 if self.default_configuration.manually_accept_inbound_channels {
6109                         let mut pending_events = self.pending_events.lock().unwrap();
6110                         pending_events.push_back((events::Event::OpenChannelRequest {
6111                                 temporary_channel_id: msg.temporary_channel_id.clone(),
6112                                 counterparty_node_id: counterparty_node_id.clone(),
6113                                 funding_satoshis: msg.funding_satoshis,
6114                                 push_msat: msg.push_msat,
6115                                 channel_type: msg.channel_type.clone().unwrap(),
6116                         }, None));
6117                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6118                                 open_channel_msg: msg.clone(),
6119                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6120                         });
6121                         return Ok(());
6122                 }
6123
6124                 // Otherwise create the channel right now.
6125                 let mut random_bytes = [0u8; 16];
6126                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6127                 let user_channel_id = u128::from_be_bytes(random_bytes);
6128                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6129                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6130                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6131                 {
6132                         Err(e) => {
6133                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
6134                         },
6135                         Ok(res) => res
6136                 };
6137
6138                 let channel_type = channel.context.get_channel_type();
6139                 if channel_type.requires_zero_conf() {
6140                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6141                 }
6142                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6143                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
6144                 }
6145
6146                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6147                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6148
6149                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6150                         node_id: counterparty_node_id.clone(),
6151                         msg: channel.accept_inbound_channel(),
6152                 });
6153                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6154                 Ok(())
6155         }
6156
6157         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6158                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6159                 // likely to be lost on restart!
6160                 let (value, output_script, user_id) = {
6161                         let per_peer_state = self.per_peer_state.read().unwrap();
6162                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6163                                 .ok_or_else(|| {
6164                                         debug_assert!(false);
6165                                         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)
6166                                 })?;
6167                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6168                         let peer_state = &mut *peer_state_lock;
6169                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6170                                 hash_map::Entry::Occupied(mut phase) => {
6171                                         match phase.get_mut() {
6172                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6173                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6174                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6175                                                 },
6176                                                 _ => {
6177                                                         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));
6178                                                 }
6179                                         }
6180                                 },
6181                                 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))
6182                         }
6183                 };
6184                 let mut pending_events = self.pending_events.lock().unwrap();
6185                 pending_events.push_back((events::Event::FundingGenerationReady {
6186                         temporary_channel_id: msg.temporary_channel_id,
6187                         counterparty_node_id: *counterparty_node_id,
6188                         channel_value_satoshis: value,
6189                         output_script,
6190                         user_channel_id: user_id,
6191                 }, None));
6192                 Ok(())
6193         }
6194
6195         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6196                 let best_block = *self.best_block.read().unwrap();
6197
6198                 let per_peer_state = self.per_peer_state.read().unwrap();
6199                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6200                         .ok_or_else(|| {
6201                                 debug_assert!(false);
6202                                 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)
6203                         })?;
6204
6205                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6206                 let peer_state = &mut *peer_state_lock;
6207                 let (chan, funding_msg, monitor) =
6208                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6209                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6210                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
6211                                                 Ok(res) => res,
6212                                                 Err((mut inbound_chan, err)) => {
6213                                                         // We've already removed this inbound channel from the map in `PeerState`
6214                                                         // above so at this point we just need to clean up any lingering entries
6215                                                         // concerning this channel as it is safe to do so.
6216                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
6217                                                         let user_id = inbound_chan.context.get_user_id();
6218                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
6219                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
6220                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
6221                                                 },
6222                                         }
6223                                 },
6224                                 Some(ChannelPhase::Funded(_)) | Some(ChannelPhase::UnfundedOutboundV1(_)) => {
6225                                         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));
6226                                 },
6227                                 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))
6228                         };
6229
6230                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
6231                         hash_map::Entry::Occupied(_) => {
6232                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
6233                         },
6234                         hash_map::Entry::Vacant(e) => {
6235                                 let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
6236                                 match id_to_peer_lock.entry(chan.context.channel_id()) {
6237                                         hash_map::Entry::Occupied(_) => {
6238                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
6239                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6240                                                         funding_msg.channel_id))
6241                                         },
6242                                         hash_map::Entry::Vacant(i_e) => {
6243                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6244                                                 if let Ok(persist_state) = monitor_res {
6245                                                         i_e.insert(chan.context.get_counterparty_node_id());
6246                                                         mem::drop(id_to_peer_lock);
6247
6248                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6249                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6250                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6251                                                         // until we have persisted our monitor.
6252                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6253                                                                 node_id: counterparty_node_id.clone(),
6254                                                                 msg: funding_msg,
6255                                                         });
6256
6257                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6258                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6259                                                                         per_peer_state, chan, INITIAL_MONITOR);
6260                                                         } else {
6261                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6262                                                         }
6263                                                         Ok(())
6264                                                 } else {
6265                                                         log_error!(self.logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6266                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6267                                                                 "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6268                                                                 funding_msg.channel_id));
6269                                                 }
6270                                         }
6271                                 }
6272                         }
6273                 }
6274         }
6275
6276         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6277                 let best_block = *self.best_block.read().unwrap();
6278                 let per_peer_state = self.per_peer_state.read().unwrap();
6279                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6280                         .ok_or_else(|| {
6281                                 debug_assert!(false);
6282                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6283                         })?;
6284
6285                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6286                 let peer_state = &mut *peer_state_lock;
6287                 match peer_state.channel_by_id.entry(msg.channel_id) {
6288                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6289                                 match chan_phase_entry.get_mut() {
6290                                         ChannelPhase::Funded(ref mut chan) => {
6291                                                 let monitor = try_chan_phase_entry!(self,
6292                                                         chan.funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan_phase_entry);
6293                                                 if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6294                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6295                                                         Ok(())
6296                                                 } else {
6297                                                         try_chan_phase_entry!(self, Err(ChannelError::Close("Channel funding outpoint was a duplicate".to_owned())), chan_phase_entry)
6298                                                 }
6299                                         },
6300                                         _ => {
6301                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6302                                         },
6303                                 }
6304                         },
6305                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6306                 }
6307         }
6308
6309         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6310                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6311                 // closing a channel), so any changes are likely to be lost on restart!
6312                 let per_peer_state = self.per_peer_state.read().unwrap();
6313                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6314                         .ok_or_else(|| {
6315                                 debug_assert!(false);
6316                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6317                         })?;
6318                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6319                 let peer_state = &mut *peer_state_lock;
6320                 match peer_state.channel_by_id.entry(msg.channel_id) {
6321                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6322                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6323                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6324                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
6325                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6326                                                 log_trace!(self.logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6327                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6328                                                         node_id: counterparty_node_id.clone(),
6329                                                         msg: announcement_sigs,
6330                                                 });
6331                                         } else if chan.context.is_usable() {
6332                                                 // If we're sending an announcement_signatures, we'll send the (public)
6333                                                 // channel_update after sending a channel_announcement when we receive our
6334                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6335                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6336                                                 // announcement_signatures.
6337                                                 log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6338                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6339                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6340                                                                 node_id: counterparty_node_id.clone(),
6341                                                                 msg,
6342                                                         });
6343                                                 }
6344                                         }
6345
6346                                         {
6347                                                 let mut pending_events = self.pending_events.lock().unwrap();
6348                                                 emit_channel_ready_event!(pending_events, chan);
6349                                         }
6350
6351                                         Ok(())
6352                                 } else {
6353                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6354                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6355                                 }
6356                         },
6357                         hash_map::Entry::Vacant(_) => {
6358                                 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))
6359                         }
6360                 }
6361         }
6362
6363         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6364                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6365                 let mut finish_shutdown = None;
6366                 {
6367                         let per_peer_state = self.per_peer_state.read().unwrap();
6368                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6369                                 .ok_or_else(|| {
6370                                         debug_assert!(false);
6371                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6372                                 })?;
6373                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6374                         let peer_state = &mut *peer_state_lock;
6375                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6376                                 let phase = chan_phase_entry.get_mut();
6377                                 match phase {
6378                                         ChannelPhase::Funded(chan) => {
6379                                                 if !chan.received_shutdown() {
6380                                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
6381                                                                 msg.channel_id,
6382                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6383                                                 }
6384
6385                                                 let funding_txo_opt = chan.context.get_funding_txo();
6386                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6387                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6388                                                 dropped_htlcs = htlcs;
6389
6390                                                 if let Some(msg) = shutdown {
6391                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6392                                                         // here as we don't need the monitor update to complete until we send a
6393                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6394                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6395                                                                 node_id: *counterparty_node_id,
6396                                                                 msg,
6397                                                         });
6398                                                 }
6399                                                 // Update the monitor with the shutdown script if necessary.
6400                                                 if let Some(monitor_update) = monitor_update_opt {
6401                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6402                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6403                                                 }
6404                                         },
6405                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6406                                                 let context = phase.context_mut();
6407                                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6408                                                 self.issue_channel_close_events(&context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
6409                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6410                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false));
6411                                         },
6412                                 }
6413                         } else {
6414                                 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))
6415                         }
6416                 }
6417                 for htlc_source in dropped_htlcs.drain(..) {
6418                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6419                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6420                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6421                 }
6422                 if let Some(shutdown_res) = finish_shutdown {
6423                         self.finish_close_channel(shutdown_res);
6424                 }
6425
6426                 Ok(())
6427         }
6428
6429         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6430                 let mut shutdown_result = None;
6431                 let unbroadcasted_batch_funding_txid;
6432                 let per_peer_state = self.per_peer_state.read().unwrap();
6433                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6434                         .ok_or_else(|| {
6435                                 debug_assert!(false);
6436                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6437                         })?;
6438                 let (tx, chan_option) = {
6439                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6440                         let peer_state = &mut *peer_state_lock;
6441                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6442                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6443                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6444                                                 unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
6445                                                 let (closing_signed, tx) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6446                                                 if let Some(msg) = closing_signed {
6447                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6448                                                                 node_id: counterparty_node_id.clone(),
6449                                                                 msg,
6450                                                         });
6451                                                 }
6452                                                 if tx.is_some() {
6453                                                         // We're done with this channel, we've got a signed closing transaction and
6454                                                         // will send the closing_signed back to the remote peer upon return. This
6455                                                         // also implies there are no pending HTLCs left on the channel, so we can
6456                                                         // fully delete it from tracking (the channel monitor is still around to
6457                                                         // watch for old state broadcasts)!
6458                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)))
6459                                                 } else { (tx, None) }
6460                                         } else {
6461                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6462                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6463                                         }
6464                                 },
6465                                 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))
6466                         }
6467                 };
6468                 if let Some(broadcast_tx) = tx {
6469                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
6470                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6471                 }
6472                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6473                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6474                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6475                                 let peer_state = &mut *peer_state_lock;
6476                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6477                                         msg: update
6478                                 });
6479                         }
6480                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6481                         shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
6482                 }
6483                 mem::drop(per_peer_state);
6484                 if let Some(shutdown_result) = shutdown_result {
6485                         self.finish_close_channel(shutdown_result);
6486                 }
6487                 Ok(())
6488         }
6489
6490         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6491                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6492                 //determine the state of the payment based on our response/if we forward anything/the time
6493                 //we take to respond. We should take care to avoid allowing such an attack.
6494                 //
6495                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6496                 //us repeatedly garbled in different ways, and compare our error messages, which are
6497                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6498                 //but we should prevent it anyway.
6499
6500                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6501                 // closing a channel), so any changes are likely to be lost on restart!
6502
6503                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
6504                 let per_peer_state = self.per_peer_state.read().unwrap();
6505                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6506                         .ok_or_else(|| {
6507                                 debug_assert!(false);
6508                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6509                         })?;
6510                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6511                 let peer_state = &mut *peer_state_lock;
6512                 match peer_state.channel_by_id.entry(msg.channel_id) {
6513                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6514                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6515                                         let pending_forward_info = match decoded_hop_res {
6516                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6517                                                         self.construct_pending_htlc_status(msg, shared_secret, next_hop,
6518                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt),
6519                                                 Err(e) => PendingHTLCStatus::Fail(e)
6520                                         };
6521                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6522                                                 // If the update_add is completely bogus, the call will Err and we will close,
6523                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6524                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6525                                                 match pending_forward_info {
6526                                                         PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
6527                                                                 let reason = if (error_code & 0x1000) != 0 {
6528                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6529                                                                         HTLCFailReason::reason(real_code, error_data)
6530                                                                 } else {
6531                                                                         HTLCFailReason::from_failure_code(error_code)
6532                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6533                                                                 let msg = msgs::UpdateFailHTLC {
6534                                                                         channel_id: msg.channel_id,
6535                                                                         htlc_id: msg.htlc_id,
6536                                                                         reason
6537                                                                 };
6538                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6539                                                         },
6540                                                         _ => pending_forward_info
6541                                                 }
6542                                         };
6543                                         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);
6544                                 } else {
6545                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6546                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6547                                 }
6548                         },
6549                         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))
6550                 }
6551                 Ok(())
6552         }
6553
6554         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6555                 let funding_txo;
6556                 let (htlc_source, forwarded_htlc_value) = {
6557                         let per_peer_state = self.per_peer_state.read().unwrap();
6558                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6559                                 .ok_or_else(|| {
6560                                         debug_assert!(false);
6561                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6562                                 })?;
6563                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6564                         let peer_state = &mut *peer_state_lock;
6565                         match peer_state.channel_by_id.entry(msg.channel_id) {
6566                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6567                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6568                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6569                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6570                                                         log_trace!(self.logger,
6571                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6572                                                                 msg.channel_id);
6573                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6574                                                                 .or_insert_with(Vec::new)
6575                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6576                                                 }
6577                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6578                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6579                                                 // We do this instead in the `claim_funds_internal` by attaching a
6580                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6581                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6582                                                 // process the RAA as messages are processed from single peers serially.
6583                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6584                                                 res
6585                                         } else {
6586                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6587                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6588                                         }
6589                                 },
6590                                 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))
6591                         }
6592                 };
6593                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6594                 Ok(())
6595         }
6596
6597         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6598                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6599                 // closing a channel), so any changes are likely to be lost on restart!
6600                 let per_peer_state = self.per_peer_state.read().unwrap();
6601                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6602                         .ok_or_else(|| {
6603                                 debug_assert!(false);
6604                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6605                         })?;
6606                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6607                 let peer_state = &mut *peer_state_lock;
6608                 match peer_state.channel_by_id.entry(msg.channel_id) {
6609                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6610                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6611                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6612                                 } else {
6613                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6614                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6615                                 }
6616                         },
6617                         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))
6618                 }
6619                 Ok(())
6620         }
6621
6622         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6623                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6624                 // closing a channel), so any changes are likely to be lost on restart!
6625                 let per_peer_state = self.per_peer_state.read().unwrap();
6626                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6627                         .ok_or_else(|| {
6628                                 debug_assert!(false);
6629                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6630                         })?;
6631                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6632                 let peer_state = &mut *peer_state_lock;
6633                 match peer_state.channel_by_id.entry(msg.channel_id) {
6634                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6635                                 if (msg.failure_code & 0x8000) == 0 {
6636                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6637                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6638                                 }
6639                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6640                                         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);
6641                                 } else {
6642                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6643                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6644                                 }
6645                                 Ok(())
6646                         },
6647                         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))
6648                 }
6649         }
6650
6651         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6652                 let per_peer_state = self.per_peer_state.read().unwrap();
6653                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6654                         .ok_or_else(|| {
6655                                 debug_assert!(false);
6656                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6657                         })?;
6658                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6659                 let peer_state = &mut *peer_state_lock;
6660                 match peer_state.channel_by_id.entry(msg.channel_id) {
6661                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6662                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6663                                         let funding_txo = chan.context.get_funding_txo();
6664                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &self.logger), chan_phase_entry);
6665                                         if let Some(monitor_update) = monitor_update_opt {
6666                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6667                                                         peer_state, per_peer_state, chan);
6668                                         }
6669                                         Ok(())
6670                                 } else {
6671                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6672                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6673                                 }
6674                         },
6675                         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))
6676                 }
6677         }
6678
6679         #[inline]
6680         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6681                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6682                         let mut push_forward_event = false;
6683                         let mut new_intercept_events = VecDeque::new();
6684                         let mut failed_intercept_forwards = Vec::new();
6685                         if !pending_forwards.is_empty() {
6686                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6687                                         let scid = match forward_info.routing {
6688                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6689                                                 PendingHTLCRouting::Receive { .. } => 0,
6690                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6691                                         };
6692                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6693                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6694
6695                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6696                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6697                                         match forward_htlcs.entry(scid) {
6698                                                 hash_map::Entry::Occupied(mut entry) => {
6699                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6700                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6701                                                 },
6702                                                 hash_map::Entry::Vacant(entry) => {
6703                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6704                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6705                                                         {
6706                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6707                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6708                                                                 match pending_intercepts.entry(intercept_id) {
6709                                                                         hash_map::Entry::Vacant(entry) => {
6710                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6711                                                                                         requested_next_hop_scid: scid,
6712                                                                                         payment_hash: forward_info.payment_hash,
6713                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6714                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6715                                                                                         intercept_id
6716                                                                                 }, None));
6717                                                                                 entry.insert(PendingAddHTLCInfo {
6718                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6719                                                                         },
6720                                                                         hash_map::Entry::Occupied(_) => {
6721                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6722                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6723                                                                                         short_channel_id: prev_short_channel_id,
6724                                                                                         user_channel_id: Some(prev_user_channel_id),
6725                                                                                         outpoint: prev_funding_outpoint,
6726                                                                                         htlc_id: prev_htlc_id,
6727                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6728                                                                                         phantom_shared_secret: None,
6729                                                                                 });
6730
6731                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6732                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6733                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6734                                                                                 ));
6735                                                                         }
6736                                                                 }
6737                                                         } else {
6738                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6739                                                                 // payments are being processed.
6740                                                                 if forward_htlcs_empty {
6741                                                                         push_forward_event = true;
6742                                                                 }
6743                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6744                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6745                                                         }
6746                                                 }
6747                                         }
6748                                 }
6749                         }
6750
6751                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6752                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6753                         }
6754
6755                         if !new_intercept_events.is_empty() {
6756                                 let mut events = self.pending_events.lock().unwrap();
6757                                 events.append(&mut new_intercept_events);
6758                         }
6759                         if push_forward_event { self.push_pending_forwards_ev() }
6760                 }
6761         }
6762
6763         fn push_pending_forwards_ev(&self) {
6764                 let mut pending_events = self.pending_events.lock().unwrap();
6765                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6766                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6767                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6768                 ).count();
6769                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6770                 // events is done in batches and they are not removed until we're done processing each
6771                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6772                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6773                 // payments will need an additional forwarding event before being claimed to make them look
6774                 // real by taking more time.
6775                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6776                         pending_events.push_back((Event::PendingHTLCsForwardable {
6777                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6778                         }, None));
6779                 }
6780         }
6781
6782         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6783         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6784         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6785         /// the [`ChannelMonitorUpdate`] in question.
6786         fn raa_monitor_updates_held(&self,
6787                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6788                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6789         ) -> bool {
6790                 actions_blocking_raa_monitor_updates
6791                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6792                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6793                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6794                                 channel_funding_outpoint,
6795                                 counterparty_node_id,
6796                         })
6797                 })
6798         }
6799
6800         #[cfg(any(test, feature = "_test_utils"))]
6801         pub(crate) fn test_raa_monitor_updates_held(&self,
6802                 counterparty_node_id: PublicKey, channel_id: ChannelId
6803         ) -> bool {
6804                 let per_peer_state = self.per_peer_state.read().unwrap();
6805                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6806                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6807                         let peer_state = &mut *peer_state_lck;
6808
6809                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6810                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6811                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6812                         }
6813                 }
6814                 false
6815         }
6816
6817         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6818                 let htlcs_to_fail = {
6819                         let per_peer_state = self.per_peer_state.read().unwrap();
6820                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6821                                 .ok_or_else(|| {
6822                                         debug_assert!(false);
6823                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6824                                 }).map(|mtx| mtx.lock().unwrap())?;
6825                         let peer_state = &mut *peer_state_lock;
6826                         match peer_state.channel_by_id.entry(msg.channel_id) {
6827                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6828                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6829                                                 let funding_txo_opt = chan.context.get_funding_txo();
6830                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6831                                                         self.raa_monitor_updates_held(
6832                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6833                                                                 *counterparty_node_id)
6834                                                 } else { false };
6835                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
6836                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &self.logger, mon_update_blocked), chan_phase_entry);
6837                                                 if let Some(monitor_update) = monitor_update_opt {
6838                                                         let funding_txo = funding_txo_opt
6839                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
6840                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
6841                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6842                                                 }
6843                                                 htlcs_to_fail
6844                                         } else {
6845                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6846                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
6847                                         }
6848                                 },
6849                                 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))
6850                         }
6851                 };
6852                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6853                 Ok(())
6854         }
6855
6856         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6857                 let per_peer_state = self.per_peer_state.read().unwrap();
6858                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6859                         .ok_or_else(|| {
6860                                 debug_assert!(false);
6861                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6862                         })?;
6863                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6864                 let peer_state = &mut *peer_state_lock;
6865                 match peer_state.channel_by_id.entry(msg.channel_id) {
6866                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6867                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6868                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &self.logger), chan_phase_entry);
6869                                 } else {
6870                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6871                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
6872                                 }
6873                         },
6874                         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))
6875                 }
6876                 Ok(())
6877         }
6878
6879         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6880                 let per_peer_state = self.per_peer_state.read().unwrap();
6881                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6882                         .ok_or_else(|| {
6883                                 debug_assert!(false);
6884                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6885                         })?;
6886                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6887                 let peer_state = &mut *peer_state_lock;
6888                 match peer_state.channel_by_id.entry(msg.channel_id) {
6889                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6890                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6891                                         if !chan.context.is_usable() {
6892                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6893                                         }
6894
6895                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6896                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6897                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
6898                                                         msg, &self.default_configuration
6899                                                 ), chan_phase_entry),
6900                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6901                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6902                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
6903                                         });
6904                                 } else {
6905                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6906                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
6907                                 }
6908                         },
6909                         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))
6910                 }
6911                 Ok(())
6912         }
6913
6914         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
6915         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6916                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6917                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6918                         None => {
6919                                 // It's not a local channel
6920                                 return Ok(NotifyOption::SkipPersistNoEvents)
6921                         }
6922                 };
6923                 let per_peer_state = self.per_peer_state.read().unwrap();
6924                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6925                 if peer_state_mutex_opt.is_none() {
6926                         return Ok(NotifyOption::SkipPersistNoEvents)
6927                 }
6928                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6929                 let peer_state = &mut *peer_state_lock;
6930                 match peer_state.channel_by_id.entry(chan_id) {
6931                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6932                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6933                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
6934                                                 if chan.context.should_announce() {
6935                                                         // If the announcement is about a channel of ours which is public, some
6936                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
6937                                                         // a scary-looking error message and return Ok instead.
6938                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6939                                                 }
6940                                                 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));
6941                                         }
6942                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
6943                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
6944                                         if were_node_one == msg_from_node_one {
6945                                                 return Ok(NotifyOption::SkipPersistNoEvents);
6946                                         } else {
6947                                                 log_debug!(self.logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
6948                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
6949                                                 // If nothing changed after applying their update, we don't need to bother
6950                                                 // persisting.
6951                                                 if !did_change {
6952                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6953                                                 }
6954                                         }
6955                                 } else {
6956                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6957                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
6958                                 }
6959                         },
6960                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
6961                 }
6962                 Ok(NotifyOption::DoPersist)
6963         }
6964
6965         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
6966                 let htlc_forwards;
6967                 let need_lnd_workaround = {
6968                         let per_peer_state = self.per_peer_state.read().unwrap();
6969
6970                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6971                                 .ok_or_else(|| {
6972                                         debug_assert!(false);
6973                                         MsgHandleErrInternal::send_err_msg_no_close(
6974                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6975                                                 msg.channel_id
6976                                         )
6977                                 })?;
6978                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6979                         let peer_state = &mut *peer_state_lock;
6980                         match peer_state.channel_by_id.entry(msg.channel_id) {
6981                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6982                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6983                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
6984                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
6985                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
6986                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6987                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
6988                                                         msg, &self.logger, &self.node_signer, self.chain_hash,
6989                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
6990                                                 let mut channel_update = None;
6991                                                 if let Some(msg) = responses.shutdown_msg {
6992                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6993                                                                 node_id: counterparty_node_id.clone(),
6994                                                                 msg,
6995                                                         });
6996                                                 } else if chan.context.is_usable() {
6997                                                         // If the channel is in a usable state (ie the channel is not being shut
6998                                                         // down), send a unicast channel_update to our counterparty to make sure
6999                                                         // they have the latest channel parameters.
7000                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
7001                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
7002                                                                         node_id: chan.context.get_counterparty_node_id(),
7003                                                                         msg,
7004                                                                 });
7005                                                         }
7006                                                 }
7007                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7008                                                 htlc_forwards = self.handle_channel_resumption(
7009                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7010                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7011                                                 if let Some(upd) = channel_update {
7012                                                         peer_state.pending_msg_events.push(upd);
7013                                                 }
7014                                                 need_lnd_workaround
7015                                         } else {
7016                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7017                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7018                                         }
7019                                 },
7020                                 hash_map::Entry::Vacant(_) => {
7021                                         log_debug!(self.logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7022                                                 log_bytes!(msg.channel_id.0));
7023                                         // Unfortunately, lnd doesn't force close on errors
7024                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7025                                         // One of the few ways to get an lnd counterparty to force close is by
7026                                         // replicating what they do when restoring static channel backups (SCBs). They
7027                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7028                                         // invalid `your_last_per_commitment_secret`.
7029                                         //
7030                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7031                                         // can assume it's likely the channel closed from our point of view, but it
7032                                         // remains open on the counterparty's side. By sending this bogus
7033                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7034                                         // force close broadcasting their latest state. If the closing transaction from
7035                                         // our point of view remains unconfirmed, it'll enter a race with the
7036                                         // counterparty's to-be-broadcast latest commitment transaction.
7037                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7038                                                 node_id: *counterparty_node_id,
7039                                                 msg: msgs::ChannelReestablish {
7040                                                         channel_id: msg.channel_id,
7041                                                         next_local_commitment_number: 0,
7042                                                         next_remote_commitment_number: 0,
7043                                                         your_last_per_commitment_secret: [1u8; 32],
7044                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7045                                                         next_funding_txid: None,
7046                                                 },
7047                                         });
7048                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7049                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7050                                                         counterparty_node_id), msg.channel_id)
7051                                         )
7052                                 }
7053                         }
7054                 };
7055
7056                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7057                 if let Some(forwards) = htlc_forwards {
7058                         self.forward_htlcs(&mut [forwards][..]);
7059                         persist = NotifyOption::DoPersist;
7060                 }
7061
7062                 if let Some(channel_ready_msg) = need_lnd_workaround {
7063                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7064                 }
7065                 Ok(persist)
7066         }
7067
7068         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7069         fn process_pending_monitor_events(&self) -> bool {
7070                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7071
7072                 let mut failed_channels = Vec::new();
7073                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7074                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7075                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7076                         for monitor_event in monitor_events.drain(..) {
7077                                 match monitor_event {
7078                                         MonitorEvent::HTLCEvent(htlc_update) => {
7079                                                 if let Some(preimage) = htlc_update.payment_preimage {
7080                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7081                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
7082                                                 } else {
7083                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7084                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
7085                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7086                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7087                                                 }
7088                                         },
7089                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
7090                                                 let counterparty_node_id_opt = match counterparty_node_id {
7091                                                         Some(cp_id) => Some(cp_id),
7092                                                         None => {
7093                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7094                                                                 // monitor event, this and the id_to_peer map should be removed.
7095                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
7096                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
7097                                                         }
7098                                                 };
7099                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7100                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7101                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7102                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7103                                                                 let peer_state = &mut *peer_state_lock;
7104                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7105                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
7106                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7107                                                                                 failed_channels.push(chan.context.force_shutdown(false));
7108                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7109                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7110                                                                                                 msg: update
7111                                                                                         });
7112                                                                                 }
7113                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
7114                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7115                                                                                         node_id: chan.context.get_counterparty_node_id(),
7116                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7117                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7118                                                                                         },
7119                                                                                 });
7120                                                                         }
7121                                                                 }
7122                                                         }
7123                                                 }
7124                                         },
7125                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
7126                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
7127                                         },
7128                                 }
7129                         }
7130                 }
7131
7132                 for failure in failed_channels.drain(..) {
7133                         self.finish_close_channel(failure);
7134                 }
7135
7136                 has_pending_monitor_events
7137         }
7138
7139         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7140         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7141         /// update events as a separate process method here.
7142         #[cfg(fuzzing)]
7143         pub fn process_monitor_events(&self) {
7144                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7145                 self.process_pending_monitor_events();
7146         }
7147
7148         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7149         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7150         /// update was applied.
7151         fn check_free_holding_cells(&self) -> bool {
7152                 let mut has_monitor_update = false;
7153                 let mut failed_htlcs = Vec::new();
7154
7155                 // Walk our list of channels and find any that need to update. Note that when we do find an
7156                 // update, if it includes actions that must be taken afterwards, we have to drop the
7157                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7158                 // manage to go through all our peers without finding a single channel to update.
7159                 'peer_loop: loop {
7160                         let per_peer_state = self.per_peer_state.read().unwrap();
7161                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7162                                 'chan_loop: loop {
7163                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7164                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7165                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7166                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7167                                         ) {
7168                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7169                                                 let funding_txo = chan.context.get_funding_txo();
7170                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7171                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
7172                                                 if !holding_cell_failed_htlcs.is_empty() {
7173                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7174                                                 }
7175                                                 if let Some(monitor_update) = monitor_opt {
7176                                                         has_monitor_update = true;
7177
7178                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7179                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7180                                                         continue 'peer_loop;
7181                                                 }
7182                                         }
7183                                         break 'chan_loop;
7184                                 }
7185                         }
7186                         break 'peer_loop;
7187                 }
7188
7189                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7190                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7191                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7192                 }
7193
7194                 has_update
7195         }
7196
7197         /// Check whether any channels have finished removing all pending updates after a shutdown
7198         /// exchange and can now send a closing_signed.
7199         /// Returns whether any closing_signed messages were generated.
7200         fn maybe_generate_initial_closing_signed(&self) -> bool {
7201                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7202                 let mut has_update = false;
7203                 let mut shutdown_results = Vec::new();
7204                 {
7205                         let per_peer_state = self.per_peer_state.read().unwrap();
7206
7207                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7208                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7209                                 let peer_state = &mut *peer_state_lock;
7210                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7211                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7212                                         match phase {
7213                                                 ChannelPhase::Funded(chan) => {
7214                                                         let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
7215                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
7216                                                                 Ok((msg_opt, tx_opt)) => {
7217                                                                         if let Some(msg) = msg_opt {
7218                                                                                 has_update = true;
7219                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7220                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7221                                                                                 });
7222                                                                         }
7223                                                                         if let Some(tx) = tx_opt {
7224                                                                                 // We're done with this channel. We got a closing_signed and sent back
7225                                                                                 // a closing_signed with a closing transaction to broadcast.
7226                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7227                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7228                                                                                                 msg: update
7229                                                                                         });
7230                                                                                 }
7231
7232                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
7233
7234                                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
7235                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7236                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7237                                                                                 shutdown_results.push((None, Vec::new(), unbroadcasted_batch_funding_txid));
7238                                                                                 false
7239                                                                         } else { true }
7240                                                                 },
7241                                                                 Err(e) => {
7242                                                                         has_update = true;
7243                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7244                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7245                                                                         !close_channel
7246                                                                 }
7247                                                         }
7248                                                 },
7249                                                 _ => true, // Retain unfunded channels if present.
7250                                         }
7251                                 });
7252                         }
7253                 }
7254
7255                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7256                         let _ = handle_error!(self, err, counterparty_node_id);
7257                 }
7258
7259                 for shutdown_result in shutdown_results.drain(..) {
7260                         self.finish_close_channel(shutdown_result);
7261                 }
7262
7263                 has_update
7264         }
7265
7266         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7267         /// pushing the channel monitor update (if any) to the background events queue and removing the
7268         /// Channel object.
7269         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7270                 for mut failure in failed_channels.drain(..) {
7271                         // Either a commitment transactions has been confirmed on-chain or
7272                         // Channel::block_disconnected detected that the funding transaction has been
7273                         // reorganized out of the main chain.
7274                         // We cannot broadcast our latest local state via monitor update (as
7275                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7276                         // so we track the update internally and handle it when the user next calls
7277                         // timer_tick_occurred, guaranteeing we're running normally.
7278                         if let Some((counterparty_node_id, funding_txo, update)) = failure.0.take() {
7279                                 assert_eq!(update.updates.len(), 1);
7280                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7281                                         assert!(should_broadcast);
7282                                 } else { unreachable!(); }
7283                                 self.pending_background_events.lock().unwrap().push(
7284                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7285                                                 counterparty_node_id, funding_txo, update
7286                                         });
7287                         }
7288                         self.finish_close_channel(failure);
7289                 }
7290         }
7291
7292         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7293         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7294         /// not have an expiration unless otherwise set on the builder.
7295         ///
7296         /// Uses a one-hop [`BlindedPath`] for the offer with [`ChannelManager::get_our_node_id`] as the
7297         /// introduction node and a derived signing pubkey for recipient privacy. As such, currently,
7298         /// the node must be announced. Otherwise, there is no way to find a path to the introduction
7299         /// node in order to send the [`InvoiceRequest`].
7300         ///
7301         /// [`Offer`]: crate::offers::offer::Offer
7302         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7303         pub fn create_offer_builder(
7304                 &self, description: String
7305         ) -> OfferBuilder<DerivedMetadata, secp256k1::All> {
7306                 let node_id = self.get_our_node_id();
7307                 let expanded_key = &self.inbound_payment_key;
7308                 let entropy = &*self.entropy_source;
7309                 let secp_ctx = &self.secp_ctx;
7310                 let path = self.create_one_hop_blinded_path();
7311
7312                 OfferBuilder::deriving_signing_pubkey(description, node_id, expanded_key, entropy, secp_ctx)
7313                         .chain_hash(self.chain_hash)
7314                         .path(path)
7315         }
7316
7317         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7318         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7319         ///
7320         /// The builder will have the provided expiration set. Any changes to the expiration on the
7321         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7322         /// block time minus two hours is used for the current time when determining if the refund has
7323         /// expired.
7324         ///
7325         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund. To
7326         /// revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the invoice.
7327         ///
7328         /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
7329         /// the introduction node and a derived payer id for sender privacy. As such, currently, the
7330         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7331         /// in order to send the [`Bolt12Invoice`].
7332         ///
7333         /// [`Refund`]: crate::offers::refund::Refund
7334         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7335         pub fn create_refund_builder(
7336                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7337                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7338         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7339                 let node_id = self.get_our_node_id();
7340                 let expanded_key = &self.inbound_payment_key;
7341                 let entropy = &*self.entropy_source;
7342                 let secp_ctx = &self.secp_ctx;
7343                 let path = self.create_one_hop_blinded_path();
7344
7345                 let builder = RefundBuilder::deriving_payer_id(
7346                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7347                 )?
7348                         .chain_hash(self.chain_hash)
7349                         .absolute_expiry(absolute_expiry)
7350                         .path(path);
7351
7352                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7353                 self.pending_outbound_payments
7354                         .add_new_awaiting_invoice(
7355                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7356                         )
7357                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7358
7359                 Ok(builder)
7360         }
7361
7362         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7363         /// to pay us.
7364         ///
7365         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7366         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7367         ///
7368         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7369         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7370         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7371         /// passed directly to [`claim_funds`].
7372         ///
7373         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7374         ///
7375         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7376         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7377         ///
7378         /// # Note
7379         ///
7380         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7381         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7382         ///
7383         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7384         ///
7385         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7386         /// on versions of LDK prior to 0.0.114.
7387         ///
7388         /// [`claim_funds`]: Self::claim_funds
7389         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7390         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7391         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7392         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7393         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7394         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7395                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7396                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7397                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7398                         min_final_cltv_expiry_delta)
7399         }
7400
7401         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7402         /// stored external to LDK.
7403         ///
7404         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7405         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7406         /// the `min_value_msat` provided here, if one is provided.
7407         ///
7408         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7409         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7410         /// payments.
7411         ///
7412         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7413         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7414         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7415         /// sender "proof-of-payment" unless they have paid the required amount.
7416         ///
7417         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7418         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7419         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7420         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7421         /// invoices when no timeout is set.
7422         ///
7423         /// Note that we use block header time to time-out pending inbound payments (with some margin
7424         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7425         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7426         /// If you need exact expiry semantics, you should enforce them upon receipt of
7427         /// [`PaymentClaimable`].
7428         ///
7429         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7430         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7431         ///
7432         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7433         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7434         ///
7435         /// # Note
7436         ///
7437         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7438         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7439         ///
7440         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7441         ///
7442         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7443         /// on versions of LDK prior to 0.0.114.
7444         ///
7445         /// [`create_inbound_payment`]: Self::create_inbound_payment
7446         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7447         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7448                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7449                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7450                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7451                         min_final_cltv_expiry)
7452         }
7453
7454         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7455         /// previously returned from [`create_inbound_payment`].
7456         ///
7457         /// [`create_inbound_payment`]: Self::create_inbound_payment
7458         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7459                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7460         }
7461
7462         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7463         /// node.
7464         fn create_one_hop_blinded_path(&self) -> BlindedPath {
7465                 let entropy_source = self.entropy_source.deref();
7466                 let secp_ctx = &self.secp_ctx;
7467                 BlindedPath::one_hop_for_message(self.get_our_node_id(), entropy_source, secp_ctx).unwrap()
7468         }
7469
7470         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
7471         /// are used when constructing the phantom invoice's route hints.
7472         ///
7473         /// [phantom node payments]: crate::sign::PhantomKeysManager
7474         pub fn get_phantom_scid(&self) -> u64 {
7475                 let best_block_height = self.best_block.read().unwrap().height();
7476                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7477                 loop {
7478                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7479                         // Ensure the generated scid doesn't conflict with a real channel.
7480                         match short_to_chan_info.get(&scid_candidate) {
7481                                 Some(_) => continue,
7482                                 None => return scid_candidate
7483                         }
7484                 }
7485         }
7486
7487         /// Gets route hints for use in receiving [phantom node payments].
7488         ///
7489         /// [phantom node payments]: crate::sign::PhantomKeysManager
7490         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
7491                 PhantomRouteHints {
7492                         channels: self.list_usable_channels(),
7493                         phantom_scid: self.get_phantom_scid(),
7494                         real_node_pubkey: self.get_our_node_id(),
7495                 }
7496         }
7497
7498         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
7499         /// used when constructing the route hints for HTLCs intended to be intercepted. See
7500         /// [`ChannelManager::forward_intercepted_htlc`].
7501         ///
7502         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
7503         /// times to get a unique scid.
7504         pub fn get_intercept_scid(&self) -> u64 {
7505                 let best_block_height = self.best_block.read().unwrap().height();
7506                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7507                 loop {
7508                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7509                         // Ensure the generated scid doesn't conflict with a real channel.
7510                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
7511                         return scid_candidate
7512                 }
7513         }
7514
7515         /// Gets inflight HTLC information by processing pending outbound payments that are in
7516         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
7517         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
7518                 let mut inflight_htlcs = InFlightHtlcs::new();
7519
7520                 let per_peer_state = self.per_peer_state.read().unwrap();
7521                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7522                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7523                         let peer_state = &mut *peer_state_lock;
7524                         for chan in peer_state.channel_by_id.values().filter_map(
7525                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7526                         ) {
7527                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
7528                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
7529                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
7530                                         }
7531                                 }
7532                         }
7533                 }
7534
7535                 inflight_htlcs
7536         }
7537
7538         #[cfg(any(test, feature = "_test_utils"))]
7539         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
7540                 let events = core::cell::RefCell::new(Vec::new());
7541                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
7542                 self.process_pending_events(&event_handler);
7543                 events.into_inner()
7544         }
7545
7546         #[cfg(feature = "_test_utils")]
7547         pub fn push_pending_event(&self, event: events::Event) {
7548                 let mut events = self.pending_events.lock().unwrap();
7549                 events.push_back((event, None));
7550         }
7551
7552         #[cfg(test)]
7553         pub fn pop_pending_event(&self) -> Option<events::Event> {
7554                 let mut events = self.pending_events.lock().unwrap();
7555                 events.pop_front().map(|(e, _)| e)
7556         }
7557
7558         #[cfg(test)]
7559         pub fn has_pending_payments(&self) -> bool {
7560                 self.pending_outbound_payments.has_pending_payments()
7561         }
7562
7563         #[cfg(test)]
7564         pub fn clear_pending_payments(&self) {
7565                 self.pending_outbound_payments.clear_pending_payments()
7566         }
7567
7568         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
7569         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
7570         /// operation. It will double-check that nothing *else* is also blocking the same channel from
7571         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
7572         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
7573                 loop {
7574                         let per_peer_state = self.per_peer_state.read().unwrap();
7575                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7576                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7577                                 let peer_state = &mut *peer_state_lck;
7578
7579                                 if let Some(blocker) = completed_blocker.take() {
7580                                         // Only do this on the first iteration of the loop.
7581                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
7582                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
7583                                         {
7584                                                 blockers.retain(|iter| iter != &blocker);
7585                                         }
7586                                 }
7587
7588                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7589                                         channel_funding_outpoint, counterparty_node_id) {
7590                                         // Check that, while holding the peer lock, we don't have anything else
7591                                         // blocking monitor updates for this channel. If we do, release the monitor
7592                                         // update(s) when those blockers complete.
7593                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
7594                                                 &channel_funding_outpoint.to_channel_id());
7595                                         break;
7596                                 }
7597
7598                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
7599                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7600                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
7601                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
7602                                                         log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
7603                                                                 channel_funding_outpoint.to_channel_id());
7604                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
7605                                                                 peer_state_lck, peer_state, per_peer_state, chan);
7606                                                         if further_update_exists {
7607                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
7608                                                                 // top of the loop.
7609                                                                 continue;
7610                                                         }
7611                                                 } else {
7612                                                         log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
7613                                                                 channel_funding_outpoint.to_channel_id());
7614                                                 }
7615                                         }
7616                                 }
7617                         } else {
7618                                 log_debug!(self.logger,
7619                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
7620                                         log_pubkey!(counterparty_node_id));
7621                         }
7622                         break;
7623                 }
7624         }
7625
7626         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
7627                 for action in actions {
7628                         match action {
7629                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7630                                         channel_funding_outpoint, counterparty_node_id
7631                                 } => {
7632                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
7633                                 }
7634                         }
7635                 }
7636         }
7637
7638         /// Processes any events asynchronously in the order they were generated since the last call
7639         /// using the given event handler.
7640         ///
7641         /// See the trait-level documentation of [`EventsProvider`] for requirements.
7642         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
7643                 &self, handler: H
7644         ) {
7645                 let mut ev;
7646                 process_events_body!(self, ev, { handler(ev).await });
7647         }
7648 }
7649
7650 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>
7651 where
7652         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7653         T::Target: BroadcasterInterface,
7654         ES::Target: EntropySource,
7655         NS::Target: NodeSigner,
7656         SP::Target: SignerProvider,
7657         F::Target: FeeEstimator,
7658         R::Target: Router,
7659         L::Target: Logger,
7660 {
7661         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
7662         /// The returned array will contain `MessageSendEvent`s for different peers if
7663         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
7664         /// is always placed next to each other.
7665         ///
7666         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
7667         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
7668         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
7669         /// will randomly be placed first or last in the returned array.
7670         ///
7671         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
7672         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
7673         /// the `MessageSendEvent`s to the specific peer they were generated under.
7674         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
7675                 let events = RefCell::new(Vec::new());
7676                 PersistenceNotifierGuard::optionally_notify(self, || {
7677                         let mut result = NotifyOption::SkipPersistNoEvents;
7678
7679                         // TODO: This behavior should be documented. It's unintuitive that we query
7680                         // ChannelMonitors when clearing other events.
7681                         if self.process_pending_monitor_events() {
7682                                 result = NotifyOption::DoPersist;
7683                         }
7684
7685                         if self.check_free_holding_cells() {
7686                                 result = NotifyOption::DoPersist;
7687                         }
7688                         if self.maybe_generate_initial_closing_signed() {
7689                                 result = NotifyOption::DoPersist;
7690                         }
7691
7692                         let mut pending_events = Vec::new();
7693                         let per_peer_state = self.per_peer_state.read().unwrap();
7694                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7695                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7696                                 let peer_state = &mut *peer_state_lock;
7697                                 if peer_state.pending_msg_events.len() > 0 {
7698                                         pending_events.append(&mut peer_state.pending_msg_events);
7699                                 }
7700                         }
7701
7702                         if !pending_events.is_empty() {
7703                                 events.replace(pending_events);
7704                         }
7705
7706                         result
7707                 });
7708                 events.into_inner()
7709         }
7710 }
7711
7712 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>
7713 where
7714         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7715         T::Target: BroadcasterInterface,
7716         ES::Target: EntropySource,
7717         NS::Target: NodeSigner,
7718         SP::Target: SignerProvider,
7719         F::Target: FeeEstimator,
7720         R::Target: Router,
7721         L::Target: Logger,
7722 {
7723         /// Processes events that must be periodically handled.
7724         ///
7725         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
7726         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
7727         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
7728                 let mut ev;
7729                 process_events_body!(self, ev, handler.handle_event(ev));
7730         }
7731 }
7732
7733 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>
7734 where
7735         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7736         T::Target: BroadcasterInterface,
7737         ES::Target: EntropySource,
7738         NS::Target: NodeSigner,
7739         SP::Target: SignerProvider,
7740         F::Target: FeeEstimator,
7741         R::Target: Router,
7742         L::Target: Logger,
7743 {
7744         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7745                 {
7746                         let best_block = self.best_block.read().unwrap();
7747                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
7748                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
7749                         assert_eq!(best_block.height(), height - 1,
7750                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
7751                 }
7752
7753                 self.transactions_confirmed(header, txdata, height);
7754                 self.best_block_updated(header, height);
7755         }
7756
7757         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
7758                 let _persistence_guard =
7759                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7760                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7761                 let new_height = height - 1;
7762                 {
7763                         let mut best_block = self.best_block.write().unwrap();
7764                         assert_eq!(best_block.block_hash(), header.block_hash(),
7765                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
7766                         assert_eq!(best_block.height(), height,
7767                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
7768                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
7769                 }
7770
7771                 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));
7772         }
7773 }
7774
7775 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>
7776 where
7777         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7778         T::Target: BroadcasterInterface,
7779         ES::Target: EntropySource,
7780         NS::Target: NodeSigner,
7781         SP::Target: SignerProvider,
7782         F::Target: FeeEstimator,
7783         R::Target: Router,
7784         L::Target: Logger,
7785 {
7786         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7787                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7788                 // during initialization prior to the chain_monitor being fully configured in some cases.
7789                 // See the docs for `ChannelManagerReadArgs` for more.
7790
7791                 let block_hash = header.block_hash();
7792                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
7793
7794                 let _persistence_guard =
7795                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7796                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7797                 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)
7798                         .map(|(a, b)| (a, Vec::new(), b)));
7799
7800                 let last_best_block_height = self.best_block.read().unwrap().height();
7801                 if height < last_best_block_height {
7802                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
7803                         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));
7804                 }
7805         }
7806
7807         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
7808                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7809                 // during initialization prior to the chain_monitor being fully configured in some cases.
7810                 // See the docs for `ChannelManagerReadArgs` for more.
7811
7812                 let block_hash = header.block_hash();
7813                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
7814
7815                 let _persistence_guard =
7816                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7817                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7818                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
7819
7820                 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));
7821
7822                 macro_rules! max_time {
7823                         ($timestamp: expr) => {
7824                                 loop {
7825                                         // Update $timestamp to be the max of its current value and the block
7826                                         // timestamp. This should keep us close to the current time without relying on
7827                                         // having an explicit local time source.
7828                                         // Just in case we end up in a race, we loop until we either successfully
7829                                         // update $timestamp or decide we don't need to.
7830                                         let old_serial = $timestamp.load(Ordering::Acquire);
7831                                         if old_serial >= header.time as usize { break; }
7832                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
7833                                                 break;
7834                                         }
7835                                 }
7836                         }
7837                 }
7838                 max_time!(self.highest_seen_timestamp);
7839                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
7840                 payment_secrets.retain(|_, inbound_payment| {
7841                         inbound_payment.expiry_time > header.time as u64
7842                 });
7843         }
7844
7845         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
7846                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
7847                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
7848                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7849                         let peer_state = &mut *peer_state_lock;
7850                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
7851                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
7852                                         res.push((funding_txo.txid, Some(block_hash)));
7853                                 }
7854                         }
7855                 }
7856                 res
7857         }
7858
7859         fn transaction_unconfirmed(&self, txid: &Txid) {
7860                 let _persistence_guard =
7861                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7862                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7863                 self.do_chain_event(None, |channel| {
7864                         if let Some(funding_txo) = channel.context.get_funding_txo() {
7865                                 if funding_txo.txid == *txid {
7866                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
7867                                 } else { Ok((None, Vec::new(), None)) }
7868                         } else { Ok((None, Vec::new(), None)) }
7869                 });
7870         }
7871 }
7872
7873 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>
7874 where
7875         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7876         T::Target: BroadcasterInterface,
7877         ES::Target: EntropySource,
7878         NS::Target: NodeSigner,
7879         SP::Target: SignerProvider,
7880         F::Target: FeeEstimator,
7881         R::Target: Router,
7882         L::Target: Logger,
7883 {
7884         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
7885         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
7886         /// the function.
7887         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
7888                         (&self, height_opt: Option<u32>, f: FN) {
7889                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7890                 // during initialization prior to the chain_monitor being fully configured in some cases.
7891                 // See the docs for `ChannelManagerReadArgs` for more.
7892
7893                 let mut failed_channels = Vec::new();
7894                 let mut timed_out_htlcs = Vec::new();
7895                 {
7896                         let per_peer_state = self.per_peer_state.read().unwrap();
7897                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7898                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7899                                 let peer_state = &mut *peer_state_lock;
7900                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7901                                 peer_state.channel_by_id.retain(|_, phase| {
7902                                         match phase {
7903                                                 // Retain unfunded channels.
7904                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
7905                                                 ChannelPhase::Funded(channel) => {
7906                                                         let res = f(channel);
7907                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
7908                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
7909                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
7910                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
7911                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
7912                                                                 }
7913                                                                 if let Some(channel_ready) = channel_ready_opt {
7914                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
7915                                                                         if channel.context.is_usable() {
7916                                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
7917                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
7918                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
7919                                                                                                 node_id: channel.context.get_counterparty_node_id(),
7920                                                                                                 msg,
7921                                                                                         });
7922                                                                                 }
7923                                                                         } else {
7924                                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
7925                                                                         }
7926                                                                 }
7927
7928                                                                 {
7929                                                                         let mut pending_events = self.pending_events.lock().unwrap();
7930                                                                         emit_channel_ready_event!(pending_events, channel);
7931                                                                 }
7932
7933                                                                 if let Some(announcement_sigs) = announcement_sigs {
7934                                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
7935                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
7936                                                                                 node_id: channel.context.get_counterparty_node_id(),
7937                                                                                 msg: announcement_sigs,
7938                                                                         });
7939                                                                         if let Some(height) = height_opt {
7940                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
7941                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7942                                                                                                 msg: announcement,
7943                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7944                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7945                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
7946                                                                                         });
7947                                                                                 }
7948                                                                         }
7949                                                                 }
7950                                                                 if channel.is_our_channel_ready() {
7951                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
7952                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
7953                                                                                 // to the short_to_chan_info map here. Note that we check whether we
7954                                                                                 // can relay using the real SCID at relay-time (i.e.
7955                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
7956                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
7957                                                                                 // is always consistent.
7958                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
7959                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
7960                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
7961                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
7962                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
7963                                                                         }
7964                                                                 }
7965                                                         } else if let Err(reason) = res {
7966                                                                 update_maps_on_chan_removal!(self, &channel.context);
7967                                                                 // It looks like our counterparty went on-chain or funding transaction was
7968                                                                 // reorged out of the main chain. Close the channel.
7969                                                                 failed_channels.push(channel.context.force_shutdown(true));
7970                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
7971                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7972                                                                                 msg: update
7973                                                                         });
7974                                                                 }
7975                                                                 let reason_message = format!("{}", reason);
7976                                                                 self.issue_channel_close_events(&channel.context, reason);
7977                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7978                                                                         node_id: channel.context.get_counterparty_node_id(),
7979                                                                         action: msgs::ErrorAction::DisconnectPeer {
7980                                                                                 msg: Some(msgs::ErrorMessage {
7981                                                                                         channel_id: channel.context.channel_id(),
7982                                                                                         data: reason_message,
7983                                                                                 })
7984                                                                         },
7985                                                                 });
7986                                                                 return false;
7987                                                         }
7988                                                         true
7989                                                 }
7990                                         }
7991                                 });
7992                         }
7993                 }
7994
7995                 if let Some(height) = height_opt {
7996                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
7997                                 payment.htlcs.retain(|htlc| {
7998                                         // If height is approaching the number of blocks we think it takes us to get
7999                                         // our commitment transaction confirmed before the HTLC expires, plus the
8000                                         // number of blocks we generally consider it to take to do a commitment update,
8001                                         // just give up on it and fail the HTLC.
8002                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8003                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8004                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8005
8006                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8007                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8008                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8009                                                 false
8010                                         } else { true }
8011                                 });
8012                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8013                         });
8014
8015                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8016                         intercepted_htlcs.retain(|_, htlc| {
8017                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8018                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8019                                                 short_channel_id: htlc.prev_short_channel_id,
8020                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8021                                                 htlc_id: htlc.prev_htlc_id,
8022                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8023                                                 phantom_shared_secret: None,
8024                                                 outpoint: htlc.prev_funding_outpoint,
8025                                         });
8026
8027                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8028                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8029                                                 _ => unreachable!(),
8030                                         };
8031                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8032                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8033                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8034                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8035                                         false
8036                                 } else { true }
8037                         });
8038                 }
8039
8040                 self.handle_init_event_channel_failures(failed_channels);
8041
8042                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8043                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8044                 }
8045         }
8046
8047         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8048         /// may have events that need processing.
8049         ///
8050         /// In order to check if this [`ChannelManager`] needs persisting, call
8051         /// [`Self::get_and_clear_needs_persistence`].
8052         ///
8053         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8054         /// [`ChannelManager`] and should instead register actions to be taken later.
8055         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8056                 self.event_persist_notifier.get_future()
8057         }
8058
8059         /// Returns true if this [`ChannelManager`] needs to be persisted.
8060         pub fn get_and_clear_needs_persistence(&self) -> bool {
8061                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8062         }
8063
8064         #[cfg(any(test, feature = "_test_utils"))]
8065         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8066                 self.event_persist_notifier.notify_pending()
8067         }
8068
8069         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8070         /// [`chain::Confirm`] interfaces.
8071         pub fn current_best_block(&self) -> BestBlock {
8072                 self.best_block.read().unwrap().clone()
8073         }
8074
8075         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
8076         /// [`ChannelManager`].
8077         pub fn node_features(&self) -> NodeFeatures {
8078                 provided_node_features(&self.default_configuration)
8079         }
8080
8081         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
8082         /// [`ChannelManager`].
8083         ///
8084         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8085         /// or not. Thus, this method is not public.
8086         #[cfg(any(feature = "_test_utils", test))]
8087         pub fn invoice_features(&self) -> Bolt11InvoiceFeatures {
8088                 provided_invoice_features(&self.default_configuration)
8089         }
8090
8091         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
8092         /// [`ChannelManager`].
8093         pub fn channel_features(&self) -> ChannelFeatures {
8094                 provided_channel_features(&self.default_configuration)
8095         }
8096
8097         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
8098         /// [`ChannelManager`].
8099         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8100                 provided_channel_type_features(&self.default_configuration)
8101         }
8102
8103         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
8104         /// [`ChannelManager`].
8105         pub fn init_features(&self) -> InitFeatures {
8106                 provided_init_features(&self.default_configuration)
8107         }
8108 }
8109
8110 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8111         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8112 where
8113         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8114         T::Target: BroadcasterInterface,
8115         ES::Target: EntropySource,
8116         NS::Target: NodeSigner,
8117         SP::Target: SignerProvider,
8118         F::Target: FeeEstimator,
8119         R::Target: Router,
8120         L::Target: Logger,
8121 {
8122         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8123                 // Note that we never need to persist the updated ChannelManager for an inbound
8124                 // open_channel message - pre-funded channels are never written so there should be no
8125                 // change to the contents.
8126                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8127                         let res = self.internal_open_channel(counterparty_node_id, msg);
8128                         let persist = match &res {
8129                                 Err(e) if e.closes_channel() => {
8130                                         debug_assert!(false, "We shouldn't close a new channel");
8131                                         NotifyOption::DoPersist
8132                                 },
8133                                 _ => NotifyOption::SkipPersistHandleEvents,
8134                         };
8135                         let _ = handle_error!(self, res, *counterparty_node_id);
8136                         persist
8137                 });
8138         }
8139
8140         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8141                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8142                         "Dual-funded channels not supported".to_owned(),
8143                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8144         }
8145
8146         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8147                 // Note that we never need to persist the updated ChannelManager for an inbound
8148                 // accept_channel message - pre-funded channels are never written so there should be no
8149                 // change to the contents.
8150                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8151                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8152                         NotifyOption::SkipPersistHandleEvents
8153                 });
8154         }
8155
8156         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8157                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8158                         "Dual-funded channels not supported".to_owned(),
8159                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8160         }
8161
8162         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8163                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8164                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8165         }
8166
8167         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8168                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8169                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8170         }
8171
8172         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8173                 // Note that we never need to persist the updated ChannelManager for an inbound
8174                 // channel_ready message - while the channel's state will change, any channel_ready message
8175                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8176                 // will not force-close the channel on startup.
8177                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8178                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8179                         let persist = match &res {
8180                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8181                                 _ => NotifyOption::SkipPersistHandleEvents,
8182                         };
8183                         let _ = handle_error!(self, res, *counterparty_node_id);
8184                         persist
8185                 });
8186         }
8187
8188         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8189                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8190                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8191         }
8192
8193         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8194                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8195                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8196         }
8197
8198         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8199                 // Note that we never need to persist the updated ChannelManager for an inbound
8200                 // update_add_htlc message - the message itself doesn't change our channel state only the
8201                 // `commitment_signed` message afterwards will.
8202                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8203                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8204                         let persist = match &res {
8205                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8206                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8207                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8208                         };
8209                         let _ = handle_error!(self, res, *counterparty_node_id);
8210                         persist
8211                 });
8212         }
8213
8214         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8215                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8216                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8217         }
8218
8219         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8220                 // Note that we never need to persist the updated ChannelManager for an inbound
8221                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8222                 // `commitment_signed` message afterwards will.
8223                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8224                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8225                         let persist = match &res {
8226                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8227                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8228                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8229                         };
8230                         let _ = handle_error!(self, res, *counterparty_node_id);
8231                         persist
8232                 });
8233         }
8234
8235         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8236                 // Note that we never need to persist the updated ChannelManager for an inbound
8237                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8238                 // only the `commitment_signed` message afterwards will.
8239                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8240                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8241                         let persist = match &res {
8242                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8243                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8244                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8245                         };
8246                         let _ = handle_error!(self, res, *counterparty_node_id);
8247                         persist
8248                 });
8249         }
8250
8251         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8252                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8253                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8254         }
8255
8256         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8257                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8258                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8259         }
8260
8261         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8262                 // Note that we never need to persist the updated ChannelManager for an inbound
8263                 // update_fee message - the message itself doesn't change our channel state only the
8264                 // `commitment_signed` message afterwards will.
8265                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8266                         let res = self.internal_update_fee(counterparty_node_id, msg);
8267                         let persist = match &res {
8268                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8269                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8270                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8271                         };
8272                         let _ = handle_error!(self, res, *counterparty_node_id);
8273                         persist
8274                 });
8275         }
8276
8277         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8278                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8279                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8280         }
8281
8282         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8283                 PersistenceNotifierGuard::optionally_notify(self, || {
8284                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8285                                 persist
8286                         } else {
8287                                 NotifyOption::DoPersist
8288                         }
8289                 });
8290         }
8291
8292         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8293                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8294                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8295                         let persist = match &res {
8296                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8297                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8298                                 Ok(persist) => *persist,
8299                         };
8300                         let _ = handle_error!(self, res, *counterparty_node_id);
8301                         persist
8302                 });
8303         }
8304
8305         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8306                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8307                         self, || NotifyOption::SkipPersistHandleEvents);
8308                 let mut failed_channels = Vec::new();
8309                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8310                 let remove_peer = {
8311                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
8312                                 log_pubkey!(counterparty_node_id));
8313                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8314                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8315                                 let peer_state = &mut *peer_state_lock;
8316                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8317                                 peer_state.channel_by_id.retain(|_, phase| {
8318                                         let context = match phase {
8319                                                 ChannelPhase::Funded(chan) => {
8320                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger).is_ok() {
8321                                                                 // We only retain funded channels that are not shutdown.
8322                                                                 return true;
8323                                                         }
8324                                                         &mut chan.context
8325                                                 },
8326                                                 // Unfunded channels will always be removed.
8327                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8328                                                         &mut chan.context
8329                                                 },
8330                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8331                                                         &mut chan.context
8332                                                 },
8333                                         };
8334                                         // Clean up for removal.
8335                                         update_maps_on_chan_removal!(self, &context);
8336                                         self.issue_channel_close_events(&context, ClosureReason::DisconnectedPeer);
8337                                         failed_channels.push(context.force_shutdown(false));
8338                                         false
8339                                 });
8340                                 // Note that we don't bother generating any events for pre-accept channels -
8341                                 // they're not considered "channels" yet from the PoV of our events interface.
8342                                 peer_state.inbound_channel_request_by_id.clear();
8343                                 pending_msg_events.retain(|msg| {
8344                                         match msg {
8345                                                 // V1 Channel Establishment
8346                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8347                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8348                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8349                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8350                                                 // V2 Channel Establishment
8351                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8352                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8353                                                 // Common Channel Establishment
8354                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8355                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8356                                                 // Interactive Transaction Construction
8357                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8358                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8359                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8360                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8361                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8362                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8363                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8364                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8365                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8366                                                 // Channel Operations
8367                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8368                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8369                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8370                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8371                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8372                                                 &events::MessageSendEvent::HandleError { .. } => false,
8373                                                 // Gossip
8374                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8375                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8376                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8377                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8378                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8379                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8380                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8381                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8382                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8383                                         }
8384                                 });
8385                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8386                                 peer_state.is_connected = false;
8387                                 peer_state.ok_to_remove(true)
8388                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8389                 };
8390                 if remove_peer {
8391                         per_peer_state.remove(counterparty_node_id);
8392                 }
8393                 mem::drop(per_peer_state);
8394
8395                 for failure in failed_channels.drain(..) {
8396                         self.finish_close_channel(failure);
8397                 }
8398         }
8399
8400         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8401                 if !init_msg.features.supports_static_remote_key() {
8402                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8403                         return Err(());
8404                 }
8405
8406                 let mut res = Ok(());
8407
8408                 PersistenceNotifierGuard::optionally_notify(self, || {
8409                         // If we have too many peers connected which don't have funded channels, disconnect the
8410                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8411                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8412                         // peers connect, but we'll reject new channels from them.
8413                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8414                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8415
8416                         {
8417                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8418                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8419                                         hash_map::Entry::Vacant(e) => {
8420                                                 if inbound_peer_limited {
8421                                                         res = Err(());
8422                                                         return NotifyOption::SkipPersistNoEvents;
8423                                                 }
8424                                                 e.insert(Mutex::new(PeerState {
8425                                                         channel_by_id: HashMap::new(),
8426                                                         inbound_channel_request_by_id: HashMap::new(),
8427                                                         latest_features: init_msg.features.clone(),
8428                                                         pending_msg_events: Vec::new(),
8429                                                         in_flight_monitor_updates: BTreeMap::new(),
8430                                                         monitor_update_blocked_actions: BTreeMap::new(),
8431                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
8432                                                         is_connected: true,
8433                                                 }));
8434                                         },
8435                                         hash_map::Entry::Occupied(e) => {
8436                                                 let mut peer_state = e.get().lock().unwrap();
8437                                                 peer_state.latest_features = init_msg.features.clone();
8438
8439                                                 let best_block_height = self.best_block.read().unwrap().height();
8440                                                 if inbound_peer_limited &&
8441                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
8442                                                         peer_state.channel_by_id.len()
8443                                                 {
8444                                                         res = Err(());
8445                                                         return NotifyOption::SkipPersistNoEvents;
8446                                                 }
8447
8448                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
8449                                                 peer_state.is_connected = true;
8450                                         },
8451                                 }
8452                         }
8453
8454                         log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
8455
8456                         let per_peer_state = self.per_peer_state.read().unwrap();
8457                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8458                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8459                                 let peer_state = &mut *peer_state_lock;
8460                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8461
8462                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
8463                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else {
8464                                                 // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
8465                                                 // (so won't be recovered after a crash), they shouldn't exist here and we would never need to
8466                                                 // worry about closing and removing them.
8467                                                 debug_assert!(false);
8468                                                 None
8469                                         }
8470                                 ).for_each(|chan| {
8471                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
8472                                                 node_id: chan.context.get_counterparty_node_id(),
8473                                                 msg: chan.get_channel_reestablish(&self.logger),
8474                                         });
8475                                 });
8476                         }
8477
8478                         return NotifyOption::SkipPersistHandleEvents;
8479                         //TODO: Also re-broadcast announcement_signatures
8480                 });
8481                 res
8482         }
8483
8484         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
8485                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8486
8487                 match &msg.data as &str {
8488                         "cannot co-op close channel w/ active htlcs"|
8489                         "link failed to shutdown" =>
8490                         {
8491                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
8492                                 // send one while HTLCs are still present. The issue is tracked at
8493                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
8494                                 // to fix it but none so far have managed to land upstream. The issue appears to be
8495                                 // very low priority for the LND team despite being marked "P1".
8496                                 // We're not going to bother handling this in a sensible way, instead simply
8497                                 // repeating the Shutdown message on repeat until morale improves.
8498                                 if !msg.channel_id.is_zero() {
8499                                         let per_peer_state = self.per_peer_state.read().unwrap();
8500                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8501                                         if peer_state_mutex_opt.is_none() { return; }
8502                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
8503                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
8504                                                 if let Some(msg) = chan.get_outbound_shutdown() {
8505                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
8506                                                                 node_id: *counterparty_node_id,
8507                                                                 msg,
8508                                                         });
8509                                                 }
8510                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
8511                                                         node_id: *counterparty_node_id,
8512                                                         action: msgs::ErrorAction::SendWarningMessage {
8513                                                                 msg: msgs::WarningMessage {
8514                                                                         channel_id: msg.channel_id,
8515                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
8516                                                                 },
8517                                                                 log_level: Level::Trace,
8518                                                         }
8519                                                 });
8520                                         }
8521                                 }
8522                                 return;
8523                         }
8524                         _ => {}
8525                 }
8526
8527                 if msg.channel_id.is_zero() {
8528                         let channel_ids: Vec<ChannelId> = {
8529                                 let per_peer_state = self.per_peer_state.read().unwrap();
8530                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8531                                 if peer_state_mutex_opt.is_none() { return; }
8532                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8533                                 let peer_state = &mut *peer_state_lock;
8534                                 // Note that we don't bother generating any events for pre-accept channels -
8535                                 // they're not considered "channels" yet from the PoV of our events interface.
8536                                 peer_state.inbound_channel_request_by_id.clear();
8537                                 peer_state.channel_by_id.keys().cloned().collect()
8538                         };
8539                         for channel_id in channel_ids {
8540                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8541                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
8542                         }
8543                 } else {
8544                         {
8545                                 // First check if we can advance the channel type and try again.
8546                                 let per_peer_state = self.per_peer_state.read().unwrap();
8547                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8548                                 if peer_state_mutex_opt.is_none() { return; }
8549                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8550                                 let peer_state = &mut *peer_state_lock;
8551                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8552                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
8553                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
8554                                                         node_id: *counterparty_node_id,
8555                                                         msg,
8556                                                 });
8557                                                 return;
8558                                         }
8559                                 }
8560                         }
8561
8562                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8563                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
8564                 }
8565         }
8566
8567         fn provided_node_features(&self) -> NodeFeatures {
8568                 provided_node_features(&self.default_configuration)
8569         }
8570
8571         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
8572                 provided_init_features(&self.default_configuration)
8573         }
8574
8575         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8576                 Some(vec![self.chain_hash])
8577         }
8578
8579         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
8580                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8581                         "Dual-funded channels not supported".to_owned(),
8582                          msg.channel_id.clone())), *counterparty_node_id);
8583         }
8584
8585         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
8586                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8587                         "Dual-funded channels not supported".to_owned(),
8588                          msg.channel_id.clone())), *counterparty_node_id);
8589         }
8590
8591         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
8592                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8593                         "Dual-funded channels not supported".to_owned(),
8594                          msg.channel_id.clone())), *counterparty_node_id);
8595         }
8596
8597         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
8598                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8599                         "Dual-funded channels not supported".to_owned(),
8600                          msg.channel_id.clone())), *counterparty_node_id);
8601         }
8602
8603         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
8604                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8605                         "Dual-funded channels not supported".to_owned(),
8606                          msg.channel_id.clone())), *counterparty_node_id);
8607         }
8608
8609         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
8610                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8611                         "Dual-funded channels not supported".to_owned(),
8612                          msg.channel_id.clone())), *counterparty_node_id);
8613         }
8614
8615         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
8616                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8617                         "Dual-funded channels not supported".to_owned(),
8618                          msg.channel_id.clone())), *counterparty_node_id);
8619         }
8620
8621         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
8622                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8623                         "Dual-funded channels not supported".to_owned(),
8624                          msg.channel_id.clone())), *counterparty_node_id);
8625         }
8626
8627         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
8628                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8629                         "Dual-funded channels not supported".to_owned(),
8630                          msg.channel_id.clone())), *counterparty_node_id);
8631         }
8632 }
8633
8634 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
8635 /// [`ChannelManager`].
8636 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
8637         let mut node_features = provided_init_features(config).to_context();
8638         node_features.set_keysend_optional();
8639         node_features
8640 }
8641
8642 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
8643 /// [`ChannelManager`].
8644 ///
8645 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8646 /// or not. Thus, this method is not public.
8647 #[cfg(any(feature = "_test_utils", test))]
8648 pub(crate) fn provided_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
8649         provided_init_features(config).to_context()
8650 }
8651
8652 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
8653 /// [`ChannelManager`].
8654 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
8655         provided_init_features(config).to_context()
8656 }
8657
8658 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
8659 /// [`ChannelManager`].
8660 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
8661         ChannelTypeFeatures::from_init(&provided_init_features(config))
8662 }
8663
8664 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
8665 /// [`ChannelManager`].
8666 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
8667         // Note that if new features are added here which other peers may (eventually) require, we
8668         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
8669         // [`ErroringMessageHandler`].
8670         let mut features = InitFeatures::empty();
8671         features.set_data_loss_protect_required();
8672         features.set_upfront_shutdown_script_optional();
8673         features.set_variable_length_onion_required();
8674         features.set_static_remote_key_required();
8675         features.set_payment_secret_required();
8676         features.set_basic_mpp_optional();
8677         features.set_wumbo_optional();
8678         features.set_shutdown_any_segwit_optional();
8679         features.set_channel_type_optional();
8680         features.set_scid_privacy_optional();
8681         features.set_zero_conf_optional();
8682         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
8683                 features.set_anchors_zero_fee_htlc_tx_optional();
8684         }
8685         features
8686 }
8687
8688 const SERIALIZATION_VERSION: u8 = 1;
8689 const MIN_SERIALIZATION_VERSION: u8 = 1;
8690
8691 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
8692         (2, fee_base_msat, required),
8693         (4, fee_proportional_millionths, required),
8694         (6, cltv_expiry_delta, required),
8695 });
8696
8697 impl_writeable_tlv_based!(ChannelCounterparty, {
8698         (2, node_id, required),
8699         (4, features, required),
8700         (6, unspendable_punishment_reserve, required),
8701         (8, forwarding_info, option),
8702         (9, outbound_htlc_minimum_msat, option),
8703         (11, outbound_htlc_maximum_msat, option),
8704 });
8705
8706 impl Writeable for ChannelDetails {
8707         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8708                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8709                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8710                 let user_channel_id_low = self.user_channel_id as u64;
8711                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
8712                 write_tlv_fields!(writer, {
8713                         (1, self.inbound_scid_alias, option),
8714                         (2, self.channel_id, required),
8715                         (3, self.channel_type, option),
8716                         (4, self.counterparty, required),
8717                         (5, self.outbound_scid_alias, option),
8718                         (6, self.funding_txo, option),
8719                         (7, self.config, option),
8720                         (8, self.short_channel_id, option),
8721                         (9, self.confirmations, option),
8722                         (10, self.channel_value_satoshis, required),
8723                         (12, self.unspendable_punishment_reserve, option),
8724                         (14, user_channel_id_low, required),
8725                         (16, self.balance_msat, required),
8726                         (18, self.outbound_capacity_msat, required),
8727                         (19, self.next_outbound_htlc_limit_msat, required),
8728                         (20, self.inbound_capacity_msat, required),
8729                         (21, self.next_outbound_htlc_minimum_msat, required),
8730                         (22, self.confirmations_required, option),
8731                         (24, self.force_close_spend_delay, option),
8732                         (26, self.is_outbound, required),
8733                         (28, self.is_channel_ready, required),
8734                         (30, self.is_usable, required),
8735                         (32, self.is_public, required),
8736                         (33, self.inbound_htlc_minimum_msat, option),
8737                         (35, self.inbound_htlc_maximum_msat, option),
8738                         (37, user_channel_id_high_opt, option),
8739                         (39, self.feerate_sat_per_1000_weight, option),
8740                         (41, self.channel_shutdown_state, option),
8741                 });
8742                 Ok(())
8743         }
8744 }
8745
8746 impl Readable for ChannelDetails {
8747         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8748                 _init_and_read_len_prefixed_tlv_fields!(reader, {
8749                         (1, inbound_scid_alias, option),
8750                         (2, channel_id, required),
8751                         (3, channel_type, option),
8752                         (4, counterparty, required),
8753                         (5, outbound_scid_alias, option),
8754                         (6, funding_txo, option),
8755                         (7, config, option),
8756                         (8, short_channel_id, option),
8757                         (9, confirmations, option),
8758                         (10, channel_value_satoshis, required),
8759                         (12, unspendable_punishment_reserve, option),
8760                         (14, user_channel_id_low, required),
8761                         (16, balance_msat, required),
8762                         (18, outbound_capacity_msat, required),
8763                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
8764                         // filled in, so we can safely unwrap it here.
8765                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
8766                         (20, inbound_capacity_msat, required),
8767                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
8768                         (22, confirmations_required, option),
8769                         (24, force_close_spend_delay, option),
8770                         (26, is_outbound, required),
8771                         (28, is_channel_ready, required),
8772                         (30, is_usable, required),
8773                         (32, is_public, required),
8774                         (33, inbound_htlc_minimum_msat, option),
8775                         (35, inbound_htlc_maximum_msat, option),
8776                         (37, user_channel_id_high_opt, option),
8777                         (39, feerate_sat_per_1000_weight, option),
8778                         (41, channel_shutdown_state, option),
8779                 });
8780
8781                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8782                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8783                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
8784                 let user_channel_id = user_channel_id_low as u128 +
8785                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
8786
8787                 Ok(Self {
8788                         inbound_scid_alias,
8789                         channel_id: channel_id.0.unwrap(),
8790                         channel_type,
8791                         counterparty: counterparty.0.unwrap(),
8792                         outbound_scid_alias,
8793                         funding_txo,
8794                         config,
8795                         short_channel_id,
8796                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
8797                         unspendable_punishment_reserve,
8798                         user_channel_id,
8799                         balance_msat: balance_msat.0.unwrap(),
8800                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
8801                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
8802                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
8803                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
8804                         confirmations_required,
8805                         confirmations,
8806                         force_close_spend_delay,
8807                         is_outbound: is_outbound.0.unwrap(),
8808                         is_channel_ready: is_channel_ready.0.unwrap(),
8809                         is_usable: is_usable.0.unwrap(),
8810                         is_public: is_public.0.unwrap(),
8811                         inbound_htlc_minimum_msat,
8812                         inbound_htlc_maximum_msat,
8813                         feerate_sat_per_1000_weight,
8814                         channel_shutdown_state,
8815                 })
8816         }
8817 }
8818
8819 impl_writeable_tlv_based!(PhantomRouteHints, {
8820         (2, channels, required_vec),
8821         (4, phantom_scid, required),
8822         (6, real_node_pubkey, required),
8823 });
8824
8825 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
8826         (0, Forward) => {
8827                 (0, onion_packet, required),
8828                 (2, short_channel_id, required),
8829         },
8830         (1, Receive) => {
8831                 (0, payment_data, required),
8832                 (1, phantom_shared_secret, option),
8833                 (2, incoming_cltv_expiry, required),
8834                 (3, payment_metadata, option),
8835                 (5, custom_tlvs, optional_vec),
8836         },
8837         (2, ReceiveKeysend) => {
8838                 (0, payment_preimage, required),
8839                 (2, incoming_cltv_expiry, required),
8840                 (3, payment_metadata, option),
8841                 (4, payment_data, option), // Added in 0.0.116
8842                 (5, custom_tlvs, optional_vec),
8843         },
8844 ;);
8845
8846 impl_writeable_tlv_based!(PendingHTLCInfo, {
8847         (0, routing, required),
8848         (2, incoming_shared_secret, required),
8849         (4, payment_hash, required),
8850         (6, outgoing_amt_msat, required),
8851         (8, outgoing_cltv_value, required),
8852         (9, incoming_amt_msat, option),
8853         (10, skimmed_fee_msat, option),
8854 });
8855
8856
8857 impl Writeable for HTLCFailureMsg {
8858         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8859                 match self {
8860                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
8861                                 0u8.write(writer)?;
8862                                 channel_id.write(writer)?;
8863                                 htlc_id.write(writer)?;
8864                                 reason.write(writer)?;
8865                         },
8866                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
8867                                 channel_id, htlc_id, sha256_of_onion, failure_code
8868                         }) => {
8869                                 1u8.write(writer)?;
8870                                 channel_id.write(writer)?;
8871                                 htlc_id.write(writer)?;
8872                                 sha256_of_onion.write(writer)?;
8873                                 failure_code.write(writer)?;
8874                         },
8875                 }
8876                 Ok(())
8877         }
8878 }
8879
8880 impl Readable for HTLCFailureMsg {
8881         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8882                 let id: u8 = Readable::read(reader)?;
8883                 match id {
8884                         0 => {
8885                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
8886                                         channel_id: Readable::read(reader)?,
8887                                         htlc_id: Readable::read(reader)?,
8888                                         reason: Readable::read(reader)?,
8889                                 }))
8890                         },
8891                         1 => {
8892                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
8893                                         channel_id: Readable::read(reader)?,
8894                                         htlc_id: Readable::read(reader)?,
8895                                         sha256_of_onion: Readable::read(reader)?,
8896                                         failure_code: Readable::read(reader)?,
8897                                 }))
8898                         },
8899                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
8900                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
8901                         // messages contained in the variants.
8902                         // In version 0.0.101, support for reading the variants with these types was added, and
8903                         // we should migrate to writing these variants when UpdateFailHTLC or
8904                         // UpdateFailMalformedHTLC get TLV fields.
8905                         2 => {
8906                                 let length: BigSize = Readable::read(reader)?;
8907                                 let mut s = FixedLengthReader::new(reader, length.0);
8908                                 let res = Readable::read(&mut s)?;
8909                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
8910                                 Ok(HTLCFailureMsg::Relay(res))
8911                         },
8912                         3 => {
8913                                 let length: BigSize = Readable::read(reader)?;
8914                                 let mut s = FixedLengthReader::new(reader, length.0);
8915                                 let res = Readable::read(&mut s)?;
8916                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
8917                                 Ok(HTLCFailureMsg::Malformed(res))
8918                         },
8919                         _ => Err(DecodeError::UnknownRequiredFeature),
8920                 }
8921         }
8922 }
8923
8924 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
8925         (0, Forward),
8926         (1, Fail),
8927 );
8928
8929 impl_writeable_tlv_based!(HTLCPreviousHopData, {
8930         (0, short_channel_id, required),
8931         (1, phantom_shared_secret, option),
8932         (2, outpoint, required),
8933         (4, htlc_id, required),
8934         (6, incoming_packet_shared_secret, required),
8935         (7, user_channel_id, option),
8936 });
8937
8938 impl Writeable for ClaimableHTLC {
8939         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8940                 let (payment_data, keysend_preimage) = match &self.onion_payload {
8941                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
8942                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
8943                 };
8944                 write_tlv_fields!(writer, {
8945                         (0, self.prev_hop, required),
8946                         (1, self.total_msat, required),
8947                         (2, self.value, required),
8948                         (3, self.sender_intended_value, required),
8949                         (4, payment_data, option),
8950                         (5, self.total_value_received, option),
8951                         (6, self.cltv_expiry, required),
8952                         (8, keysend_preimage, option),
8953                         (10, self.counterparty_skimmed_fee_msat, option),
8954                 });
8955                 Ok(())
8956         }
8957 }
8958
8959 impl Readable for ClaimableHTLC {
8960         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8961                 _init_and_read_len_prefixed_tlv_fields!(reader, {
8962                         (0, prev_hop, required),
8963                         (1, total_msat, option),
8964                         (2, value_ser, required),
8965                         (3, sender_intended_value, option),
8966                         (4, payment_data_opt, option),
8967                         (5, total_value_received, option),
8968                         (6, cltv_expiry, required),
8969                         (8, keysend_preimage, option),
8970                         (10, counterparty_skimmed_fee_msat, option),
8971                 });
8972                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
8973                 let value = value_ser.0.unwrap();
8974                 let onion_payload = match keysend_preimage {
8975                         Some(p) => {
8976                                 if payment_data.is_some() {
8977                                         return Err(DecodeError::InvalidValue)
8978                                 }
8979                                 if total_msat.is_none() {
8980                                         total_msat = Some(value);
8981                                 }
8982                                 OnionPayload::Spontaneous(p)
8983                         },
8984                         None => {
8985                                 if total_msat.is_none() {
8986                                         if payment_data.is_none() {
8987                                                 return Err(DecodeError::InvalidValue)
8988                                         }
8989                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
8990                                 }
8991                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
8992                         },
8993                 };
8994                 Ok(Self {
8995                         prev_hop: prev_hop.0.unwrap(),
8996                         timer_ticks: 0,
8997                         value,
8998                         sender_intended_value: sender_intended_value.unwrap_or(value),
8999                         total_value_received,
9000                         total_msat: total_msat.unwrap(),
9001                         onion_payload,
9002                         cltv_expiry: cltv_expiry.0.unwrap(),
9003                         counterparty_skimmed_fee_msat,
9004                 })
9005         }
9006 }
9007
9008 impl Readable for HTLCSource {
9009         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9010                 let id: u8 = Readable::read(reader)?;
9011                 match id {
9012                         0 => {
9013                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9014                                 let mut first_hop_htlc_msat: u64 = 0;
9015                                 let mut path_hops = Vec::new();
9016                                 let mut payment_id = None;
9017                                 let mut payment_params: Option<PaymentParameters> = None;
9018                                 let mut blinded_tail: Option<BlindedTail> = None;
9019                                 read_tlv_fields!(reader, {
9020                                         (0, session_priv, required),
9021                                         (1, payment_id, option),
9022                                         (2, first_hop_htlc_msat, required),
9023                                         (4, path_hops, required_vec),
9024                                         (5, payment_params, (option: ReadableArgs, 0)),
9025                                         (6, blinded_tail, option),
9026                                 });
9027                                 if payment_id.is_none() {
9028                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9029                                         // instead.
9030                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9031                                 }
9032                                 let path = Path { hops: path_hops, blinded_tail };
9033                                 if path.hops.len() == 0 {
9034                                         return Err(DecodeError::InvalidValue);
9035                                 }
9036                                 if let Some(params) = payment_params.as_mut() {
9037                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9038                                                 if final_cltv_expiry_delta == &0 {
9039                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9040                                                 }
9041                                         }
9042                                 }
9043                                 Ok(HTLCSource::OutboundRoute {
9044                                         session_priv: session_priv.0.unwrap(),
9045                                         first_hop_htlc_msat,
9046                                         path,
9047                                         payment_id: payment_id.unwrap(),
9048                                 })
9049                         }
9050                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9051                         _ => Err(DecodeError::UnknownRequiredFeature),
9052                 }
9053         }
9054 }
9055
9056 impl Writeable for HTLCSource {
9057         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9058                 match self {
9059                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9060                                 0u8.write(writer)?;
9061                                 let payment_id_opt = Some(payment_id);
9062                                 write_tlv_fields!(writer, {
9063                                         (0, session_priv, required),
9064                                         (1, payment_id_opt, option),
9065                                         (2, first_hop_htlc_msat, required),
9066                                         // 3 was previously used to write a PaymentSecret for the payment.
9067                                         (4, path.hops, required_vec),
9068                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9069                                         (6, path.blinded_tail, option),
9070                                  });
9071                         }
9072                         HTLCSource::PreviousHopData(ref field) => {
9073                                 1u8.write(writer)?;
9074                                 field.write(writer)?;
9075                         }
9076                 }
9077                 Ok(())
9078         }
9079 }
9080
9081 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9082         (0, forward_info, required),
9083         (1, prev_user_channel_id, (default_value, 0)),
9084         (2, prev_short_channel_id, required),
9085         (4, prev_htlc_id, required),
9086         (6, prev_funding_outpoint, required),
9087 });
9088
9089 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
9090         (1, FailHTLC) => {
9091                 (0, htlc_id, required),
9092                 (2, err_packet, required),
9093         };
9094         (0, AddHTLC)
9095 );
9096
9097 impl_writeable_tlv_based!(PendingInboundPayment, {
9098         (0, payment_secret, required),
9099         (2, expiry_time, required),
9100         (4, user_payment_id, required),
9101         (6, payment_preimage, required),
9102         (8, min_value_msat, required),
9103 });
9104
9105 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>
9106 where
9107         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9108         T::Target: BroadcasterInterface,
9109         ES::Target: EntropySource,
9110         NS::Target: NodeSigner,
9111         SP::Target: SignerProvider,
9112         F::Target: FeeEstimator,
9113         R::Target: Router,
9114         L::Target: Logger,
9115 {
9116         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9117                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9118
9119                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9120
9121                 self.chain_hash.write(writer)?;
9122                 {
9123                         let best_block = self.best_block.read().unwrap();
9124                         best_block.height().write(writer)?;
9125                         best_block.block_hash().write(writer)?;
9126                 }
9127
9128                 let mut serializable_peer_count: u64 = 0;
9129                 {
9130                         let per_peer_state = self.per_peer_state.read().unwrap();
9131                         let mut number_of_funded_channels = 0;
9132                         for (_, peer_state_mutex) in per_peer_state.iter() {
9133                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9134                                 let peer_state = &mut *peer_state_lock;
9135                                 if !peer_state.ok_to_remove(false) {
9136                                         serializable_peer_count += 1;
9137                                 }
9138
9139                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9140                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9141                                 ).count();
9142                         }
9143
9144                         (number_of_funded_channels as u64).write(writer)?;
9145
9146                         for (_, peer_state_mutex) in per_peer_state.iter() {
9147                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9148                                 let peer_state = &mut *peer_state_lock;
9149                                 for channel in peer_state.channel_by_id.iter().filter_map(
9150                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9151                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9152                                         } else { None }
9153                                 ) {
9154                                         channel.write(writer)?;
9155                                 }
9156                         }
9157                 }
9158
9159                 {
9160                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9161                         (forward_htlcs.len() as u64).write(writer)?;
9162                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9163                                 short_channel_id.write(writer)?;
9164                                 (pending_forwards.len() as u64).write(writer)?;
9165                                 for forward in pending_forwards {
9166                                         forward.write(writer)?;
9167                                 }
9168                         }
9169                 }
9170
9171                 let per_peer_state = self.per_peer_state.write().unwrap();
9172
9173                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9174                 let claimable_payments = self.claimable_payments.lock().unwrap();
9175                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9176
9177                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9178                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9179                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9180                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9181                         payment_hash.write(writer)?;
9182                         (payment.htlcs.len() as u64).write(writer)?;
9183                         for htlc in payment.htlcs.iter() {
9184                                 htlc.write(writer)?;
9185                         }
9186                         htlc_purposes.push(&payment.purpose);
9187                         htlc_onion_fields.push(&payment.onion_fields);
9188                 }
9189
9190                 let mut monitor_update_blocked_actions_per_peer = None;
9191                 let mut peer_states = Vec::new();
9192                 for (_, peer_state_mutex) in per_peer_state.iter() {
9193                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9194                         // of a lockorder violation deadlock - no other thread can be holding any
9195                         // per_peer_state lock at all.
9196                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9197                 }
9198
9199                 (serializable_peer_count).write(writer)?;
9200                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9201                         // Peers which we have no channels to should be dropped once disconnected. As we
9202                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9203                         // consider all peers as disconnected here. There's therefore no need write peers with
9204                         // no channels.
9205                         if !peer_state.ok_to_remove(false) {
9206                                 peer_pubkey.write(writer)?;
9207                                 peer_state.latest_features.write(writer)?;
9208                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9209                                         monitor_update_blocked_actions_per_peer
9210                                                 .get_or_insert_with(Vec::new)
9211                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9212                                 }
9213                         }
9214                 }
9215
9216                 let events = self.pending_events.lock().unwrap();
9217                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9218                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9219                 // refuse to read the new ChannelManager.
9220                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9221                 if events_not_backwards_compatible {
9222                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9223                         // well save the space and not write any events here.
9224                         0u64.write(writer)?;
9225                 } else {
9226                         (events.len() as u64).write(writer)?;
9227                         for (event, _) in events.iter() {
9228                                 event.write(writer)?;
9229                         }
9230                 }
9231
9232                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
9233                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
9234                 // the closing monitor updates were always effectively replayed on startup (either directly
9235                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
9236                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
9237                 0u64.write(writer)?;
9238
9239                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
9240                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
9241                 // likely to be identical.
9242                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9243                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9244
9245                 (pending_inbound_payments.len() as u64).write(writer)?;
9246                 for (hash, pending_payment) in pending_inbound_payments.iter() {
9247                         hash.write(writer)?;
9248                         pending_payment.write(writer)?;
9249                 }
9250
9251                 // For backwards compat, write the session privs and their total length.
9252                 let mut num_pending_outbounds_compat: u64 = 0;
9253                 for (_, outbound) in pending_outbound_payments.iter() {
9254                         if !outbound.is_fulfilled() && !outbound.abandoned() {
9255                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
9256                         }
9257                 }
9258                 num_pending_outbounds_compat.write(writer)?;
9259                 for (_, outbound) in pending_outbound_payments.iter() {
9260                         match outbound {
9261                                 PendingOutboundPayment::Legacy { session_privs } |
9262                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9263                                         for session_priv in session_privs.iter() {
9264                                                 session_priv.write(writer)?;
9265                                         }
9266                                 }
9267                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
9268                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
9269                                 PendingOutboundPayment::Fulfilled { .. } => {},
9270                                 PendingOutboundPayment::Abandoned { .. } => {},
9271                         }
9272                 }
9273
9274                 // Encode without retry info for 0.0.101 compatibility.
9275                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
9276                 for (id, outbound) in pending_outbound_payments.iter() {
9277                         match outbound {
9278                                 PendingOutboundPayment::Legacy { session_privs } |
9279                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9280                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
9281                                 },
9282                                 _ => {},
9283                         }
9284                 }
9285
9286                 let mut pending_intercepted_htlcs = None;
9287                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
9288                 if our_pending_intercepts.len() != 0 {
9289                         pending_intercepted_htlcs = Some(our_pending_intercepts);
9290                 }
9291
9292                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
9293                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
9294                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
9295                         // map. Thus, if there are no entries we skip writing a TLV for it.
9296                         pending_claiming_payments = None;
9297                 }
9298
9299                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
9300                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9301                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
9302                                 if !updates.is_empty() {
9303                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
9304                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
9305                                 }
9306                         }
9307                 }
9308
9309                 write_tlv_fields!(writer, {
9310                         (1, pending_outbound_payments_no_retry, required),
9311                         (2, pending_intercepted_htlcs, option),
9312                         (3, pending_outbound_payments, required),
9313                         (4, pending_claiming_payments, option),
9314                         (5, self.our_network_pubkey, required),
9315                         (6, monitor_update_blocked_actions_per_peer, option),
9316                         (7, self.fake_scid_rand_bytes, required),
9317                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
9318                         (9, htlc_purposes, required_vec),
9319                         (10, in_flight_monitor_updates, option),
9320                         (11, self.probing_cookie_secret, required),
9321                         (13, htlc_onion_fields, optional_vec),
9322                 });
9323
9324                 Ok(())
9325         }
9326 }
9327
9328 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
9329         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9330                 (self.len() as u64).write(w)?;
9331                 for (event, action) in self.iter() {
9332                         event.write(w)?;
9333                         action.write(w)?;
9334                         #[cfg(debug_assertions)] {
9335                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
9336                                 // be persisted and are regenerated on restart. However, if such an event has a
9337                                 // post-event-handling action we'll write nothing for the event and would have to
9338                                 // either forget the action or fail on deserialization (which we do below). Thus,
9339                                 // check that the event is sane here.
9340                                 let event_encoded = event.encode();
9341                                 let event_read: Option<Event> =
9342                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
9343                                 if action.is_some() { assert!(event_read.is_some()); }
9344                         }
9345                 }
9346                 Ok(())
9347         }
9348 }
9349 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
9350         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9351                 let len: u64 = Readable::read(reader)?;
9352                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
9353                 let mut events: Self = VecDeque::with_capacity(cmp::min(
9354                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
9355                         len) as usize);
9356                 for _ in 0..len {
9357                         let ev_opt = MaybeReadable::read(reader)?;
9358                         let action = Readable::read(reader)?;
9359                         if let Some(ev) = ev_opt {
9360                                 events.push_back((ev, action));
9361                         } else if action.is_some() {
9362                                 return Err(DecodeError::InvalidValue);
9363                         }
9364                 }
9365                 Ok(events)
9366         }
9367 }
9368
9369 impl_writeable_tlv_based_enum!(ChannelShutdownState,
9370         (0, NotShuttingDown) => {},
9371         (2, ShutdownInitiated) => {},
9372         (4, ResolvingHTLCs) => {},
9373         (6, NegotiatingClosingFee) => {},
9374         (8, ShutdownComplete) => {}, ;
9375 );
9376
9377 /// Arguments for the creation of a ChannelManager that are not deserialized.
9378 ///
9379 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
9380 /// is:
9381 /// 1) Deserialize all stored [`ChannelMonitor`]s.
9382 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
9383 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
9384 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
9385 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
9386 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
9387 ///    same way you would handle a [`chain::Filter`] call using
9388 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
9389 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
9390 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
9391 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
9392 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
9393 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
9394 ///    the next step.
9395 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
9396 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
9397 ///
9398 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
9399 /// call any other methods on the newly-deserialized [`ChannelManager`].
9400 ///
9401 /// Note that because some channels may be closed during deserialization, it is critical that you
9402 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
9403 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
9404 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
9405 /// not force-close the same channels but consider them live), you may end up revoking a state for
9406 /// which you've already broadcasted the transaction.
9407 ///
9408 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
9409 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9410 where
9411         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9412         T::Target: BroadcasterInterface,
9413         ES::Target: EntropySource,
9414         NS::Target: NodeSigner,
9415         SP::Target: SignerProvider,
9416         F::Target: FeeEstimator,
9417         R::Target: Router,
9418         L::Target: Logger,
9419 {
9420         /// A cryptographically secure source of entropy.
9421         pub entropy_source: ES,
9422
9423         /// A signer that is able to perform node-scoped cryptographic operations.
9424         pub node_signer: NS,
9425
9426         /// The keys provider which will give us relevant keys. Some keys will be loaded during
9427         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
9428         /// signing data.
9429         pub signer_provider: SP,
9430
9431         /// The fee_estimator for use in the ChannelManager in the future.
9432         ///
9433         /// No calls to the FeeEstimator will be made during deserialization.
9434         pub fee_estimator: F,
9435         /// The chain::Watch for use in the ChannelManager in the future.
9436         ///
9437         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
9438         /// you have deserialized ChannelMonitors separately and will add them to your
9439         /// chain::Watch after deserializing this ChannelManager.
9440         pub chain_monitor: M,
9441
9442         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
9443         /// used to broadcast the latest local commitment transactions of channels which must be
9444         /// force-closed during deserialization.
9445         pub tx_broadcaster: T,
9446         /// The router which will be used in the ChannelManager in the future for finding routes
9447         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
9448         ///
9449         /// No calls to the router will be made during deserialization.
9450         pub router: R,
9451         /// The Logger for use in the ChannelManager and which may be used to log information during
9452         /// deserialization.
9453         pub logger: L,
9454         /// Default settings used for new channels. Any existing channels will continue to use the
9455         /// runtime settings which were stored when the ChannelManager was serialized.
9456         pub default_config: UserConfig,
9457
9458         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
9459         /// value.context.get_funding_txo() should be the key).
9460         ///
9461         /// If a monitor is inconsistent with the channel state during deserialization the channel will
9462         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
9463         /// is true for missing channels as well. If there is a monitor missing for which we find
9464         /// channel data Err(DecodeError::InvalidValue) will be returned.
9465         ///
9466         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
9467         /// this struct.
9468         ///
9469         /// This is not exported to bindings users because we have no HashMap bindings
9470         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
9471 }
9472
9473 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9474                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
9475 where
9476         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9477         T::Target: BroadcasterInterface,
9478         ES::Target: EntropySource,
9479         NS::Target: NodeSigner,
9480         SP::Target: SignerProvider,
9481         F::Target: FeeEstimator,
9482         R::Target: Router,
9483         L::Target: Logger,
9484 {
9485         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
9486         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
9487         /// populate a HashMap directly from C.
9488         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,
9489                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
9490                 Self {
9491                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
9492                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
9493                 }
9494         }
9495 }
9496
9497 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
9498 // SipmleArcChannelManager type:
9499 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9500         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
9501 where
9502         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9503         T::Target: BroadcasterInterface,
9504         ES::Target: EntropySource,
9505         NS::Target: NodeSigner,
9506         SP::Target: SignerProvider,
9507         F::Target: FeeEstimator,
9508         R::Target: Router,
9509         L::Target: Logger,
9510 {
9511         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9512                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
9513                 Ok((blockhash, Arc::new(chan_manager)))
9514         }
9515 }
9516
9517 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9518         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
9519 where
9520         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9521         T::Target: BroadcasterInterface,
9522         ES::Target: EntropySource,
9523         NS::Target: NodeSigner,
9524         SP::Target: SignerProvider,
9525         F::Target: FeeEstimator,
9526         R::Target: Router,
9527         L::Target: Logger,
9528 {
9529         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9530                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
9531
9532                 let chain_hash: ChainHash = Readable::read(reader)?;
9533                 let best_block_height: u32 = Readable::read(reader)?;
9534                 let best_block_hash: BlockHash = Readable::read(reader)?;
9535
9536                 let mut failed_htlcs = Vec::new();
9537
9538                 let channel_count: u64 = Readable::read(reader)?;
9539                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
9540                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9541                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9542                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9543                 let mut channel_closures = VecDeque::new();
9544                 let mut close_background_events = Vec::new();
9545                 for _ in 0..channel_count {
9546                         let mut channel: Channel<SP> = Channel::read(reader, (
9547                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
9548                         ))?;
9549                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
9550                         funding_txo_set.insert(funding_txo.clone());
9551                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
9552                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
9553                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
9554                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
9555                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9556                                         // But if the channel is behind of the monitor, close the channel:
9557                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
9558                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
9559                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9560                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
9561                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
9562                                         }
9563                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
9564                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
9565                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
9566                                         }
9567                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
9568                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
9569                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
9570                                         }
9571                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
9572                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
9573                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
9574                                         }
9575                                         let (monitor_update, mut new_failed_htlcs, batch_funding_txid) = channel.context.force_shutdown(true);
9576                                         if batch_funding_txid.is_some() {
9577                                                 return Err(DecodeError::InvalidValue);
9578                                         }
9579                                         if let Some((counterparty_node_id, funding_txo, update)) = monitor_update {
9580                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
9581                                                         counterparty_node_id, funding_txo, update
9582                                                 });
9583                                         }
9584                                         failed_htlcs.append(&mut new_failed_htlcs);
9585                                         channel_closures.push_back((events::Event::ChannelClosed {
9586                                                 channel_id: channel.context.channel_id(),
9587                                                 user_channel_id: channel.context.get_user_id(),
9588                                                 reason: ClosureReason::OutdatedChannelManager,
9589                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9590                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9591                                         }, None));
9592                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
9593                                                 let mut found_htlc = false;
9594                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
9595                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
9596                                                 }
9597                                                 if !found_htlc {
9598                                                         // If we have some HTLCs in the channel which are not present in the newer
9599                                                         // ChannelMonitor, they have been removed and should be failed back to
9600                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
9601                                                         // were actually claimed we'd have generated and ensured the previous-hop
9602                                                         // claim update ChannelMonitor updates were persisted prior to persising
9603                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
9604                                                         // backwards leg of the HTLC will simply be rejected.
9605                                                         log_info!(args.logger,
9606                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
9607                                                                 &channel.context.channel_id(), &payment_hash);
9608                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9609                                                 }
9610                                         }
9611                                 } else {
9612                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
9613                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
9614                                                 monitor.get_latest_update_id());
9615                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
9616                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9617                                         }
9618                                         if channel.context.is_funding_broadcast() {
9619                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
9620                                         }
9621                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
9622                                                 hash_map::Entry::Occupied(mut entry) => {
9623                                                         let by_id_map = entry.get_mut();
9624                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9625                                                 },
9626                                                 hash_map::Entry::Vacant(entry) => {
9627                                                         let mut by_id_map = HashMap::new();
9628                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9629                                                         entry.insert(by_id_map);
9630                                                 }
9631                                         }
9632                                 }
9633                         } else if channel.is_awaiting_initial_mon_persist() {
9634                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
9635                                 // was in-progress, we never broadcasted the funding transaction and can still
9636                                 // safely discard the channel.
9637                                 let _ = channel.context.force_shutdown(false);
9638                                 channel_closures.push_back((events::Event::ChannelClosed {
9639                                         channel_id: channel.context.channel_id(),
9640                                         user_channel_id: channel.context.get_user_id(),
9641                                         reason: ClosureReason::DisconnectedPeer,
9642                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9643                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9644                                 }, None));
9645                         } else {
9646                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
9647                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9648                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9649                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
9650                                 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");
9651                                 return Err(DecodeError::InvalidValue);
9652                         }
9653                 }
9654
9655                 for (funding_txo, _) in args.channel_monitors.iter() {
9656                         if !funding_txo_set.contains(funding_txo) {
9657                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
9658                                         &funding_txo.to_channel_id());
9659                                 let monitor_update = ChannelMonitorUpdate {
9660                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
9661                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
9662                                 };
9663                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
9664                         }
9665                 }
9666
9667                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
9668                 let forward_htlcs_count: u64 = Readable::read(reader)?;
9669                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
9670                 for _ in 0..forward_htlcs_count {
9671                         let short_channel_id = Readable::read(reader)?;
9672                         let pending_forwards_count: u64 = Readable::read(reader)?;
9673                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
9674                         for _ in 0..pending_forwards_count {
9675                                 pending_forwards.push(Readable::read(reader)?);
9676                         }
9677                         forward_htlcs.insert(short_channel_id, pending_forwards);
9678                 }
9679
9680                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
9681                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
9682                 for _ in 0..claimable_htlcs_count {
9683                         let payment_hash = Readable::read(reader)?;
9684                         let previous_hops_len: u64 = Readable::read(reader)?;
9685                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
9686                         for _ in 0..previous_hops_len {
9687                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
9688                         }
9689                         claimable_htlcs_list.push((payment_hash, previous_hops));
9690                 }
9691
9692                 let peer_state_from_chans = |channel_by_id| {
9693                         PeerState {
9694                                 channel_by_id,
9695                                 inbound_channel_request_by_id: HashMap::new(),
9696                                 latest_features: InitFeatures::empty(),
9697                                 pending_msg_events: Vec::new(),
9698                                 in_flight_monitor_updates: BTreeMap::new(),
9699                                 monitor_update_blocked_actions: BTreeMap::new(),
9700                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
9701                                 is_connected: false,
9702                         }
9703                 };
9704
9705                 let peer_count: u64 = Readable::read(reader)?;
9706                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
9707                 for _ in 0..peer_count {
9708                         let peer_pubkey = Readable::read(reader)?;
9709                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
9710                         let mut peer_state = peer_state_from_chans(peer_chans);
9711                         peer_state.latest_features = Readable::read(reader)?;
9712                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
9713                 }
9714
9715                 let event_count: u64 = Readable::read(reader)?;
9716                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
9717                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
9718                 for _ in 0..event_count {
9719                         match MaybeReadable::read(reader)? {
9720                                 Some(event) => pending_events_read.push_back((event, None)),
9721                                 None => continue,
9722                         }
9723                 }
9724
9725                 let background_event_count: u64 = Readable::read(reader)?;
9726                 for _ in 0..background_event_count {
9727                         match <u8 as Readable>::read(reader)? {
9728                                 0 => {
9729                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
9730                                         // however we really don't (and never did) need them - we regenerate all
9731                                         // on-startup monitor updates.
9732                                         let _: OutPoint = Readable::read(reader)?;
9733                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
9734                                 }
9735                                 _ => return Err(DecodeError::InvalidValue),
9736                         }
9737                 }
9738
9739                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
9740                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
9741
9742                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
9743                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
9744                 for _ in 0..pending_inbound_payment_count {
9745                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
9746                                 return Err(DecodeError::InvalidValue);
9747                         }
9748                 }
9749
9750                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
9751                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
9752                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
9753                 for _ in 0..pending_outbound_payments_count_compat {
9754                         let session_priv = Readable::read(reader)?;
9755                         let payment = PendingOutboundPayment::Legacy {
9756                                 session_privs: [session_priv].iter().cloned().collect()
9757                         };
9758                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
9759                                 return Err(DecodeError::InvalidValue)
9760                         };
9761                 }
9762
9763                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
9764                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
9765                 let mut pending_outbound_payments = None;
9766                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
9767                 let mut received_network_pubkey: Option<PublicKey> = None;
9768                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
9769                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
9770                 let mut claimable_htlc_purposes = None;
9771                 let mut claimable_htlc_onion_fields = None;
9772                 let mut pending_claiming_payments = Some(HashMap::new());
9773                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
9774                 let mut events_override = None;
9775                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
9776                 read_tlv_fields!(reader, {
9777                         (1, pending_outbound_payments_no_retry, option),
9778                         (2, pending_intercepted_htlcs, option),
9779                         (3, pending_outbound_payments, option),
9780                         (4, pending_claiming_payments, option),
9781                         (5, received_network_pubkey, option),
9782                         (6, monitor_update_blocked_actions_per_peer, option),
9783                         (7, fake_scid_rand_bytes, option),
9784                         (8, events_override, option),
9785                         (9, claimable_htlc_purposes, optional_vec),
9786                         (10, in_flight_monitor_updates, option),
9787                         (11, probing_cookie_secret, option),
9788                         (13, claimable_htlc_onion_fields, optional_vec),
9789                 });
9790                 if fake_scid_rand_bytes.is_none() {
9791                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
9792                 }
9793
9794                 if probing_cookie_secret.is_none() {
9795                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
9796                 }
9797
9798                 if let Some(events) = events_override {
9799                         pending_events_read = events;
9800                 }
9801
9802                 if !channel_closures.is_empty() {
9803                         pending_events_read.append(&mut channel_closures);
9804                 }
9805
9806                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
9807                         pending_outbound_payments = Some(pending_outbound_payments_compat);
9808                 } else if pending_outbound_payments.is_none() {
9809                         let mut outbounds = HashMap::new();
9810                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
9811                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
9812                         }
9813                         pending_outbound_payments = Some(outbounds);
9814                 }
9815                 let pending_outbounds = OutboundPayments {
9816                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
9817                         retry_lock: Mutex::new(())
9818                 };
9819
9820                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
9821                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
9822                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
9823                 // replayed, and for each monitor update we have to replay we have to ensure there's a
9824                 // `ChannelMonitor` for it.
9825                 //
9826                 // In order to do so we first walk all of our live channels (so that we can check their
9827                 // state immediately after doing the update replays, when we have the `update_id`s
9828                 // available) and then walk any remaining in-flight updates.
9829                 //
9830                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
9831                 let mut pending_background_events = Vec::new();
9832                 macro_rules! handle_in_flight_updates {
9833                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
9834                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
9835                         ) => { {
9836                                 let mut max_in_flight_update_id = 0;
9837                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
9838                                 for update in $chan_in_flight_upds.iter() {
9839                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
9840                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
9841                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
9842                                         pending_background_events.push(
9843                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
9844                                                         counterparty_node_id: $counterparty_node_id,
9845                                                         funding_txo: $funding_txo,
9846                                                         update: update.clone(),
9847                                                 });
9848                                 }
9849                                 if $chan_in_flight_upds.is_empty() {
9850                                         // We had some updates to apply, but it turns out they had completed before we
9851                                         // were serialized, we just weren't notified of that. Thus, we may have to run
9852                                         // the completion actions for any monitor updates, but otherwise are done.
9853                                         pending_background_events.push(
9854                                                 BackgroundEvent::MonitorUpdatesComplete {
9855                                                         counterparty_node_id: $counterparty_node_id,
9856                                                         channel_id: $funding_txo.to_channel_id(),
9857                                                 });
9858                                 }
9859                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
9860                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
9861                                         return Err(DecodeError::InvalidValue);
9862                                 }
9863                                 max_in_flight_update_id
9864                         } }
9865                 }
9866
9867                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
9868                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
9869                         let peer_state = &mut *peer_state_lock;
9870                         for phase in peer_state.channel_by_id.values() {
9871                                 if let ChannelPhase::Funded(chan) = phase {
9872                                         // Channels that were persisted have to be funded, otherwise they should have been
9873                                         // discarded.
9874                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
9875                                         let monitor = args.channel_monitors.get(&funding_txo)
9876                                                 .expect("We already checked for monitor presence when loading channels");
9877                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
9878                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
9879                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
9880                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
9881                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
9882                                                                         funding_txo, monitor, peer_state, ""));
9883                                                 }
9884                                         }
9885                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
9886                                                 // If the channel is ahead of the monitor, return InvalidValue:
9887                                                 log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
9888                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
9889                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
9890                                                 log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
9891                                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9892                                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9893                                                 log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
9894                                                 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");
9895                                                 return Err(DecodeError::InvalidValue);
9896                                         }
9897                                 } else {
9898                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
9899                                         // created in this `channel_by_id` map.
9900                                         debug_assert!(false);
9901                                         return Err(DecodeError::InvalidValue);
9902                                 }
9903                         }
9904                 }
9905
9906                 if let Some(in_flight_upds) = in_flight_monitor_updates {
9907                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
9908                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
9909                                         // Now that we've removed all the in-flight monitor updates for channels that are
9910                                         // still open, we need to replay any monitor updates that are for closed channels,
9911                                         // creating the neccessary peer_state entries as we go.
9912                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
9913                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
9914                                         });
9915                                         let mut peer_state = peer_state_mutex.lock().unwrap();
9916                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
9917                                                 funding_txo, monitor, peer_state, "closed ");
9918                                 } else {
9919                                         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!");
9920                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
9921                                                 &funding_txo.to_channel_id());
9922                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9923                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9924                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
9925                                         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");
9926                                         return Err(DecodeError::InvalidValue);
9927                                 }
9928                         }
9929                 }
9930
9931                 // Note that we have to do the above replays before we push new monitor updates.
9932                 pending_background_events.append(&mut close_background_events);
9933
9934                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
9935                 // should ensure we try them again on the inbound edge. We put them here and do so after we
9936                 // have a fully-constructed `ChannelManager` at the end.
9937                 let mut pending_claims_to_replay = Vec::new();
9938
9939                 {
9940                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
9941                         // ChannelMonitor data for any channels for which we do not have authorative state
9942                         // (i.e. those for which we just force-closed above or we otherwise don't have a
9943                         // corresponding `Channel` at all).
9944                         // This avoids several edge-cases where we would otherwise "forget" about pending
9945                         // payments which are still in-flight via their on-chain state.
9946                         // We only rebuild the pending payments map if we were most recently serialized by
9947                         // 0.0.102+
9948                         for (_, monitor) in args.channel_monitors.iter() {
9949                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
9950                                 if counterparty_opt.is_none() {
9951                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
9952                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
9953                                                         if path.hops.is_empty() {
9954                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
9955                                                                 return Err(DecodeError::InvalidValue);
9956                                                         }
9957
9958                                                         let path_amt = path.final_value_msat();
9959                                                         let mut session_priv_bytes = [0; 32];
9960                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
9961                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
9962                                                                 hash_map::Entry::Occupied(mut entry) => {
9963                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
9964                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
9965                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), &htlc.payment_hash);
9966                                                                 },
9967                                                                 hash_map::Entry::Vacant(entry) => {
9968                                                                         let path_fee = path.fee_msat();
9969                                                                         entry.insert(PendingOutboundPayment::Retryable {
9970                                                                                 retry_strategy: None,
9971                                                                                 attempts: PaymentAttempts::new(),
9972                                                                                 payment_params: None,
9973                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
9974                                                                                 payment_hash: htlc.payment_hash,
9975                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
9976                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
9977                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
9978                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
9979                                                                                 pending_amt_msat: path_amt,
9980                                                                                 pending_fee_msat: Some(path_fee),
9981                                                                                 total_msat: path_amt,
9982                                                                                 starting_block_height: best_block_height,
9983                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
9984                                                                         });
9985                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
9986                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
9987                                                                 }
9988                                                         }
9989                                                 }
9990                                         }
9991                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
9992                                                 match htlc_source {
9993                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
9994                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
9995                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
9996                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
9997                                                                 };
9998                                                                 // The ChannelMonitor is now responsible for this HTLC's
9999                                                                 // failure/success and will let us know what its outcome is. If we
10000                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10001                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10002                                                                 // the monitor was when forwarding the payment.
10003                                                                 forward_htlcs.retain(|_, forwards| {
10004                                                                         forwards.retain(|forward| {
10005                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10006                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10007                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10008                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10009                                                                                                 false
10010                                                                                         } else { true }
10011                                                                                 } else { true }
10012                                                                         });
10013                                                                         !forwards.is_empty()
10014                                                                 });
10015                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10016                                                                         if pending_forward_matches_htlc(&htlc_info) {
10017                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10018                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10019                                                                                 pending_events_read.retain(|(event, _)| {
10020                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10021                                                                                                 intercepted_id != ev_id
10022                                                                                         } else { true }
10023                                                                                 });
10024                                                                                 false
10025                                                                         } else { true }
10026                                                                 });
10027                                                         },
10028                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10029                                                                 if let Some(preimage) = preimage_opt {
10030                                                                         let pending_events = Mutex::new(pending_events_read);
10031                                                                         // Note that we set `from_onchain` to "false" here,
10032                                                                         // deliberately keeping the pending payment around forever.
10033                                                                         // Given it should only occur when we have a channel we're
10034                                                                         // force-closing for being stale that's okay.
10035                                                                         // The alternative would be to wipe the state when claiming,
10036                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10037                                                                         // it and the `PaymentSent` on every restart until the
10038                                                                         // `ChannelMonitor` is removed.
10039                                                                         let compl_action =
10040                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10041                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10042                                                                                         counterparty_node_id: path.hops[0].pubkey,
10043                                                                                 };
10044                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10045                                                                                 path, false, compl_action, &pending_events, &args.logger);
10046                                                                         pending_events_read = pending_events.into_inner().unwrap();
10047                                                                 }
10048                                                         },
10049                                                 }
10050                                         }
10051                                 }
10052
10053                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10054                                 // preimages from it which may be needed in upstream channels for forwarded
10055                                 // payments.
10056                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10057                                         .into_iter()
10058                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10059                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10060                                                         if let Some(payment_preimage) = preimage_opt {
10061                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10062                                                                         // Check if `counterparty_opt.is_none()` to see if the
10063                                                                         // downstream chan is closed (because we don't have a
10064                                                                         // channel_id -> peer map entry).
10065                                                                         counterparty_opt.is_none(),
10066                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10067                                                                         monitor.get_funding_txo().0))
10068                                                         } else { None }
10069                                                 } else {
10070                                                         // If it was an outbound payment, we've handled it above - if a preimage
10071                                                         // came in and we persisted the `ChannelManager` we either handled it and
10072                                                         // are good to go or the channel force-closed - we don't have to handle the
10073                                                         // channel still live case here.
10074                                                         None
10075                                                 }
10076                                         });
10077                                 for tuple in outbound_claimed_htlcs_iter {
10078                                         pending_claims_to_replay.push(tuple);
10079                                 }
10080                         }
10081                 }
10082
10083                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10084                         // If we have pending HTLCs to forward, assume we either dropped a
10085                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10086                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10087                         // constant as enough time has likely passed that we should simply handle the forwards
10088                         // now, or at least after the user gets a chance to reconnect to our peers.
10089                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10090                                 time_forwardable: Duration::from_secs(2),
10091                         }, None));
10092                 }
10093
10094                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10095                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10096
10097                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10098                 if let Some(purposes) = claimable_htlc_purposes {
10099                         if purposes.len() != claimable_htlcs_list.len() {
10100                                 return Err(DecodeError::InvalidValue);
10101                         }
10102                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10103                                 if onion_fields.len() != claimable_htlcs_list.len() {
10104                                         return Err(DecodeError::InvalidValue);
10105                                 }
10106                                 for (purpose, (onion, (payment_hash, htlcs))) in
10107                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10108                                 {
10109                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10110                                                 purpose, htlcs, onion_fields: onion,
10111                                         });
10112                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10113                                 }
10114                         } else {
10115                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10116                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10117                                                 purpose, htlcs, onion_fields: None,
10118                                         });
10119                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10120                                 }
10121                         }
10122                 } else {
10123                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10124                         // include a `_legacy_hop_data` in the `OnionPayload`.
10125                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10126                                 if htlcs.is_empty() {
10127                                         return Err(DecodeError::InvalidValue);
10128                                 }
10129                                 let purpose = match &htlcs[0].onion_payload {
10130                                         OnionPayload::Invoice { _legacy_hop_data } => {
10131                                                 if let Some(hop_data) = _legacy_hop_data {
10132                                                         events::PaymentPurpose::InvoicePayment {
10133                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10134                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10135                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10136                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10137                                                                                 Err(()) => {
10138                                                                                         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);
10139                                                                                         return Err(DecodeError::InvalidValue);
10140                                                                                 }
10141                                                                         }
10142                                                                 },
10143                                                                 payment_secret: hop_data.payment_secret,
10144                                                         }
10145                                                 } else { return Err(DecodeError::InvalidValue); }
10146                                         },
10147                                         OnionPayload::Spontaneous(payment_preimage) =>
10148                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10149                                 };
10150                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10151                                         purpose, htlcs, onion_fields: None,
10152                                 });
10153                         }
10154                 }
10155
10156                 let mut secp_ctx = Secp256k1::new();
10157                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10158
10159                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10160                         Ok(key) => key,
10161                         Err(()) => return Err(DecodeError::InvalidValue)
10162                 };
10163                 if let Some(network_pubkey) = received_network_pubkey {
10164                         if network_pubkey != our_network_pubkey {
10165                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10166                                 return Err(DecodeError::InvalidValue);
10167                         }
10168                 }
10169
10170                 let mut outbound_scid_aliases = HashSet::new();
10171                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10172                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10173                         let peer_state = &mut *peer_state_lock;
10174                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10175                                 if let ChannelPhase::Funded(chan) = phase {
10176                                         if chan.context.outbound_scid_alias() == 0 {
10177                                                 let mut outbound_scid_alias;
10178                                                 loop {
10179                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10180                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10181                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10182                                                 }
10183                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10184                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10185                                                 // Note that in rare cases its possible to hit this while reading an older
10186                                                 // channel if we just happened to pick a colliding outbound alias above.
10187                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10188                                                 return Err(DecodeError::InvalidValue);
10189                                         }
10190                                         if chan.context.is_usable() {
10191                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10192                                                         // Note that in rare cases its possible to hit this while reading an older
10193                                                         // channel if we just happened to pick a colliding outbound alias above.
10194                                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10195                                                         return Err(DecodeError::InvalidValue);
10196                                                 }
10197                                         }
10198                                 } else {
10199                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10200                                         // created in this `channel_by_id` map.
10201                                         debug_assert!(false);
10202                                         return Err(DecodeError::InvalidValue);
10203                                 }
10204                         }
10205                 }
10206
10207                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10208
10209                 for (_, monitor) in args.channel_monitors.iter() {
10210                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10211                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10212                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10213                                         let mut claimable_amt_msat = 0;
10214                                         let mut receiver_node_id = Some(our_network_pubkey);
10215                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
10216                                         if phantom_shared_secret.is_some() {
10217                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
10218                                                         .expect("Failed to get node_id for phantom node recipient");
10219                                                 receiver_node_id = Some(phantom_pubkey)
10220                                         }
10221                                         for claimable_htlc in &payment.htlcs {
10222                                                 claimable_amt_msat += claimable_htlc.value;
10223
10224                                                 // Add a holding-cell claim of the payment to the Channel, which should be
10225                                                 // applied ~immediately on peer reconnection. Because it won't generate a
10226                                                 // new commitment transaction we can just provide the payment preimage to
10227                                                 // the corresponding ChannelMonitor and nothing else.
10228                                                 //
10229                                                 // We do so directly instead of via the normal ChannelMonitor update
10230                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
10231                                                 // we're not allowed to call it directly yet. Further, we do the update
10232                                                 // without incrementing the ChannelMonitor update ID as there isn't any
10233                                                 // reason to.
10234                                                 // If we were to generate a new ChannelMonitor update ID here and then
10235                                                 // crash before the user finishes block connect we'd end up force-closing
10236                                                 // this channel as well. On the flip side, there's no harm in restarting
10237                                                 // without the new monitor persisted - we'll end up right back here on
10238                                                 // restart.
10239                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
10240                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
10241                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
10242                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10243                                                         let peer_state = &mut *peer_state_lock;
10244                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
10245                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
10246                                                         }
10247                                                 }
10248                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
10249                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
10250                                                 }
10251                                         }
10252                                         pending_events_read.push_back((events::Event::PaymentClaimed {
10253                                                 receiver_node_id,
10254                                                 payment_hash,
10255                                                 purpose: payment.purpose,
10256                                                 amount_msat: claimable_amt_msat,
10257                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
10258                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
10259                                         }, None));
10260                                 }
10261                         }
10262                 }
10263
10264                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
10265                         if let Some(peer_state) = per_peer_state.get(&node_id) {
10266                                 for (_, actions) in monitor_update_blocked_actions.iter() {
10267                                         for action in actions.iter() {
10268                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
10269                                                         downstream_counterparty_and_funding_outpoint:
10270                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
10271                                                 } = action {
10272                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
10273                                                                 log_trace!(args.logger,
10274                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
10275                                                                         blocked_channel_outpoint.to_channel_id());
10276                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
10277                                                                         .entry(blocked_channel_outpoint.to_channel_id())
10278                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
10279                                                         } else {
10280                                                                 // If the channel we were blocking has closed, we don't need to
10281                                                                 // worry about it - the blocked monitor update should never have
10282                                                                 // been released from the `Channel` object so it can't have
10283                                                                 // completed, and if the channel closed there's no reason to bother
10284                                                                 // anymore.
10285                                                         }
10286                                                 }
10287                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
10288                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
10289                                                 }
10290                                         }
10291                                 }
10292                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
10293                         } else {
10294                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
10295                                 return Err(DecodeError::InvalidValue);
10296                         }
10297                 }
10298
10299                 let channel_manager = ChannelManager {
10300                         chain_hash,
10301                         fee_estimator: bounded_fee_estimator,
10302                         chain_monitor: args.chain_monitor,
10303                         tx_broadcaster: args.tx_broadcaster,
10304                         router: args.router,
10305
10306                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
10307
10308                         inbound_payment_key: expanded_inbound_key,
10309                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
10310                         pending_outbound_payments: pending_outbounds,
10311                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
10312
10313                         forward_htlcs: Mutex::new(forward_htlcs),
10314                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
10315                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
10316                         id_to_peer: Mutex::new(id_to_peer),
10317                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
10318                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
10319
10320                         probing_cookie_secret: probing_cookie_secret.unwrap(),
10321
10322                         our_network_pubkey,
10323                         secp_ctx,
10324
10325                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
10326
10327                         per_peer_state: FairRwLock::new(per_peer_state),
10328
10329                         pending_events: Mutex::new(pending_events_read),
10330                         pending_events_processor: AtomicBool::new(false),
10331                         pending_background_events: Mutex::new(pending_background_events),
10332                         total_consistency_lock: RwLock::new(()),
10333                         background_events_processed_since_startup: AtomicBool::new(false),
10334
10335                         event_persist_notifier: Notifier::new(),
10336                         needs_persist_flag: AtomicBool::new(false),
10337
10338                         funding_batch_states: Mutex::new(BTreeMap::new()),
10339
10340                         pending_offers_messages: Mutex::new(Vec::new()),
10341
10342                         entropy_source: args.entropy_source,
10343                         node_signer: args.node_signer,
10344                         signer_provider: args.signer_provider,
10345
10346                         logger: args.logger,
10347                         default_configuration: args.default_config,
10348                 };
10349
10350                 for htlc_source in failed_htlcs.drain(..) {
10351                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
10352                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
10353                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
10354                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
10355                 }
10356
10357                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
10358                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
10359                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
10360                         // channel is closed we just assume that it probably came from an on-chain claim.
10361                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
10362                                 downstream_closed, true, downstream_node_id, downstream_funding);
10363                 }
10364
10365                 //TODO: Broadcast channel update for closed channels, but only after we've made a
10366                 //connection or two.
10367
10368                 Ok((best_block_hash.clone(), channel_manager))
10369         }
10370 }
10371
10372 #[cfg(test)]
10373 mod tests {
10374         use bitcoin::hashes::Hash;
10375         use bitcoin::hashes::sha256::Hash as Sha256;
10376         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10377         use core::sync::atomic::Ordering;
10378         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
10379         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
10380         use crate::ln::ChannelId;
10381         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
10382         use crate::ln::functional_test_utils::*;
10383         use crate::ln::msgs::{self, ErrorAction};
10384         use crate::ln::msgs::ChannelMessageHandler;
10385         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
10386         use crate::util::errors::APIError;
10387         use crate::util::test_utils;
10388         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
10389         use crate::sign::EntropySource;
10390
10391         #[test]
10392         fn test_notify_limits() {
10393                 // Check that a few cases which don't require the persistence of a new ChannelManager,
10394                 // indeed, do not cause the persistence of a new ChannelManager.
10395                 let chanmon_cfgs = create_chanmon_cfgs(3);
10396                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10397                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10398                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10399
10400                 // All nodes start with a persistable update pending as `create_network` connects each node
10401                 // with all other nodes to make most tests simpler.
10402                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10403                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10404                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10405
10406                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10407
10408                 // We check that the channel info nodes have doesn't change too early, even though we try
10409                 // to connect messages with new values
10410                 chan.0.contents.fee_base_msat *= 2;
10411                 chan.1.contents.fee_base_msat *= 2;
10412                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
10413                         &nodes[1].node.get_our_node_id()).pop().unwrap();
10414                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
10415                         &nodes[0].node.get_our_node_id()).pop().unwrap();
10416
10417                 // The first two nodes (which opened a channel) should now require fresh persistence
10418                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10419                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10420                 // ... but the last node should not.
10421                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10422                 // After persisting the first two nodes they should no longer need fresh persistence.
10423                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10424                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10425
10426                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
10427                 // about the channel.
10428                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
10429                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
10430                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10431
10432                 // The nodes which are a party to the channel should also ignore messages from unrelated
10433                 // parties.
10434                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10435                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10436                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10437                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10438                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10439                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10440
10441                 // At this point the channel info given by peers should still be the same.
10442                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10443                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10444
10445                 // An earlier version of handle_channel_update didn't check the directionality of the
10446                 // update message and would always update the local fee info, even if our peer was
10447                 // (spuriously) forwarding us our own channel_update.
10448                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
10449                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
10450                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
10451
10452                 // First deliver each peers' own message, checking that the node doesn't need to be
10453                 // persisted and that its channel info remains the same.
10454                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
10455                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
10456                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10457                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10458                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10459                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10460
10461                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
10462                 // the channel info has updated.
10463                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
10464                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
10465                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10466                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10467                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
10468                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
10469         }
10470
10471         #[test]
10472         fn test_keysend_dup_hash_partial_mpp() {
10473                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
10474                 // expected.
10475                 let chanmon_cfgs = create_chanmon_cfgs(2);
10476                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10477                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10478                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10479                 create_announced_chan_between_nodes(&nodes, 0, 1);
10480
10481                 // First, send a partial MPP payment.
10482                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
10483                 let mut mpp_route = route.clone();
10484                 mpp_route.paths.push(mpp_route.paths[0].clone());
10485
10486                 let payment_id = PaymentId([42; 32]);
10487                 // Use the utility function send_payment_along_path to send the payment with MPP data which
10488                 // indicates there are more HTLCs coming.
10489                 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.
10490                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
10491                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
10492                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
10493                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
10494                 check_added_monitors!(nodes[0], 1);
10495                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10496                 assert_eq!(events.len(), 1);
10497                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10498
10499                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
10500                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10501                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10502                 check_added_monitors!(nodes[0], 1);
10503                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10504                 assert_eq!(events.len(), 1);
10505                 let ev = events.drain(..).next().unwrap();
10506                 let payment_event = SendEvent::from_event(ev);
10507                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10508                 check_added_monitors!(nodes[1], 0);
10509                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10510                 expect_pending_htlcs_forwardable!(nodes[1]);
10511                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
10512                 check_added_monitors!(nodes[1], 1);
10513                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10514                 assert!(updates.update_add_htlcs.is_empty());
10515                 assert!(updates.update_fulfill_htlcs.is_empty());
10516                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10517                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10518                 assert!(updates.update_fee.is_none());
10519                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10520                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10521                 expect_payment_failed!(nodes[0], our_payment_hash, true);
10522
10523                 // Send the second half of the original MPP payment.
10524                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
10525                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
10526                 check_added_monitors!(nodes[0], 1);
10527                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10528                 assert_eq!(events.len(), 1);
10529                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
10530
10531                 // Claim the full MPP payment. Note that we can't use a test utility like
10532                 // claim_funds_along_route because the ordering of the messages causes the second half of the
10533                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
10534                 // lightning messages manually.
10535                 nodes[1].node.claim_funds(payment_preimage);
10536                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
10537                 check_added_monitors!(nodes[1], 2);
10538
10539                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10540                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
10541                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
10542                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
10543                 check_added_monitors!(nodes[0], 1);
10544                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10545                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
10546                 check_added_monitors!(nodes[1], 1);
10547                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10548                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
10549                 check_added_monitors!(nodes[1], 1);
10550                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10551                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
10552                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
10553                 check_added_monitors!(nodes[0], 1);
10554                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10555                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
10556                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10557                 check_added_monitors!(nodes[0], 1);
10558                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
10559                 check_added_monitors!(nodes[1], 1);
10560                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
10561                 check_added_monitors!(nodes[1], 1);
10562                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10563                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
10564                 check_added_monitors!(nodes[0], 1);
10565
10566                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
10567                 // path's success and a PaymentPathSuccessful event for each path's success.
10568                 let events = nodes[0].node.get_and_clear_pending_events();
10569                 assert_eq!(events.len(), 2);
10570                 match events[0] {
10571                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10572                                 assert_eq!(payment_id, *actual_payment_id);
10573                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10574                                 assert_eq!(route.paths[0], *path);
10575                         },
10576                         _ => panic!("Unexpected event"),
10577                 }
10578                 match events[1] {
10579                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10580                                 assert_eq!(payment_id, *actual_payment_id);
10581                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10582                                 assert_eq!(route.paths[0], *path);
10583                         },
10584                         _ => panic!("Unexpected event"),
10585                 }
10586         }
10587
10588         #[test]
10589         fn test_keysend_dup_payment_hash() {
10590                 do_test_keysend_dup_payment_hash(false);
10591                 do_test_keysend_dup_payment_hash(true);
10592         }
10593
10594         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
10595                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
10596                 //      outbound regular payment fails as expected.
10597                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
10598                 //      fails as expected.
10599                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
10600                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
10601                 //      reject MPP keysend payments, since in this case where the payment has no payment
10602                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
10603                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
10604                 //      payment secrets and reject otherwise.
10605                 let chanmon_cfgs = create_chanmon_cfgs(2);
10606                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10607                 let mut mpp_keysend_cfg = test_default_channel_config();
10608                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
10609                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
10610                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10611                 create_announced_chan_between_nodes(&nodes, 0, 1);
10612                 let scorer = test_utils::TestScorer::new();
10613                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10614
10615                 // To start (1), send a regular payment but don't claim it.
10616                 let expected_route = [&nodes[1]];
10617                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
10618
10619                 // Next, attempt a keysend payment and make sure it fails.
10620                 let route_params = RouteParameters::from_payment_params_and_value(
10621                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
10622                         TEST_FINAL_CLTV, false), 100_000);
10623                 let route = find_route(
10624                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10625                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10626                 ).unwrap();
10627                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10628                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10629                 check_added_monitors!(nodes[0], 1);
10630                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10631                 assert_eq!(events.len(), 1);
10632                 let ev = events.drain(..).next().unwrap();
10633                 let payment_event = SendEvent::from_event(ev);
10634                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10635                 check_added_monitors!(nodes[1], 0);
10636                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10637                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
10638                 // fails), the second will process the resulting failure and fail the HTLC backward
10639                 expect_pending_htlcs_forwardable!(nodes[1]);
10640                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10641                 check_added_monitors!(nodes[1], 1);
10642                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10643                 assert!(updates.update_add_htlcs.is_empty());
10644                 assert!(updates.update_fulfill_htlcs.is_empty());
10645                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10646                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10647                 assert!(updates.update_fee.is_none());
10648                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10649                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10650                 expect_payment_failed!(nodes[0], payment_hash, true);
10651
10652                 // Finally, claim the original payment.
10653                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10654
10655                 // To start (2), send a keysend payment but don't claim it.
10656                 let payment_preimage = PaymentPreimage([42; 32]);
10657                 let route = find_route(
10658                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10659                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10660                 ).unwrap();
10661                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10662                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10663                 check_added_monitors!(nodes[0], 1);
10664                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10665                 assert_eq!(events.len(), 1);
10666                 let event = events.pop().unwrap();
10667                 let path = vec![&nodes[1]];
10668                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10669
10670                 // Next, attempt a regular payment and make sure it fails.
10671                 let payment_secret = PaymentSecret([43; 32]);
10672                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10673                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.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 }]);
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], payment_hash, true);
10694
10695                 // Finally, succeed the keysend payment.
10696                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10697
10698                 // To start (3), send a keysend payment but don't claim it.
10699                 let payment_id_1 = PaymentId([44; 32]);
10700                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10701                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
10702                 check_added_monitors!(nodes[0], 1);
10703                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10704                 assert_eq!(events.len(), 1);
10705                 let event = events.pop().unwrap();
10706                 let path = vec![&nodes[1]];
10707                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10708
10709                 // Next, attempt a keysend payment and make sure it fails.
10710                 let route_params = RouteParameters::from_payment_params_and_value(
10711                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
10712                         100_000
10713                 );
10714                 let route = find_route(
10715                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10716                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10717                 ).unwrap();
10718                 let payment_id_2 = PaymentId([45; 32]);
10719                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10720                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
10721                 check_added_monitors!(nodes[0], 1);
10722                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10723                 assert_eq!(events.len(), 1);
10724                 let ev = events.drain(..).next().unwrap();
10725                 let payment_event = SendEvent::from_event(ev);
10726                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10727                 check_added_monitors!(nodes[1], 0);
10728                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10729                 expect_pending_htlcs_forwardable!(nodes[1]);
10730                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10731                 check_added_monitors!(nodes[1], 1);
10732                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10733                 assert!(updates.update_add_htlcs.is_empty());
10734                 assert!(updates.update_fulfill_htlcs.is_empty());
10735                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10736                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10737                 assert!(updates.update_fee.is_none());
10738                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10739                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10740                 expect_payment_failed!(nodes[0], payment_hash, true);
10741
10742                 // Finally, claim the original payment.
10743                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10744         }
10745
10746         #[test]
10747         fn test_keysend_hash_mismatch() {
10748                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
10749                 // preimage doesn't match the msg's payment hash.
10750                 let chanmon_cfgs = create_chanmon_cfgs(2);
10751                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10752                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10753                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10754
10755                 let payer_pubkey = nodes[0].node.get_our_node_id();
10756                 let payee_pubkey = nodes[1].node.get_our_node_id();
10757
10758                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10759                 let route_params = RouteParameters::from_payment_params_and_value(
10760                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10761                 let network_graph = nodes[0].network_graph.clone();
10762                 let first_hops = nodes[0].node.list_usable_channels();
10763                 let scorer = test_utils::TestScorer::new();
10764                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10765                 let route = find_route(
10766                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10767                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10768                 ).unwrap();
10769
10770                 let test_preimage = PaymentPreimage([42; 32]);
10771                 let mismatch_payment_hash = PaymentHash([43; 32]);
10772                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
10773                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
10774                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
10775                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
10776                 check_added_monitors!(nodes[0], 1);
10777
10778                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10779                 assert_eq!(updates.update_add_htlcs.len(), 1);
10780                 assert!(updates.update_fulfill_htlcs.is_empty());
10781                 assert!(updates.update_fail_htlcs.is_empty());
10782                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10783                 assert!(updates.update_fee.is_none());
10784                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
10785
10786                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
10787         }
10788
10789         #[test]
10790         fn test_keysend_msg_with_secret_err() {
10791                 // Test that we error as expected if we receive a keysend payment that includes a payment
10792                 // secret when we don't support MPP keysend.
10793                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
10794                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
10795                 let chanmon_cfgs = create_chanmon_cfgs(2);
10796                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10797                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
10798                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10799
10800                 let payer_pubkey = nodes[0].node.get_our_node_id();
10801                 let payee_pubkey = nodes[1].node.get_our_node_id();
10802
10803                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10804                 let route_params = RouteParameters::from_payment_params_and_value(
10805                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10806                 let network_graph = nodes[0].network_graph.clone();
10807                 let first_hops = nodes[0].node.list_usable_channels();
10808                 let scorer = test_utils::TestScorer::new();
10809                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10810                 let route = find_route(
10811                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10812                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10813                 ).unwrap();
10814
10815                 let test_preimage = PaymentPreimage([42; 32]);
10816                 let test_secret = PaymentSecret([43; 32]);
10817                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
10818                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
10819                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
10820                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
10821                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
10822                         PaymentId(payment_hash.0), None, session_privs).unwrap();
10823                 check_added_monitors!(nodes[0], 1);
10824
10825                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10826                 assert_eq!(updates.update_add_htlcs.len(), 1);
10827                 assert!(updates.update_fulfill_htlcs.is_empty());
10828                 assert!(updates.update_fail_htlcs.is_empty());
10829                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10830                 assert!(updates.update_fee.is_none());
10831                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
10832
10833                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
10834         }
10835
10836         #[test]
10837         fn test_multi_hop_missing_secret() {
10838                 let chanmon_cfgs = create_chanmon_cfgs(4);
10839                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10840                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10841                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10842
10843                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
10844                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
10845                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
10846                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
10847
10848                 // Marshall an MPP route.
10849                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
10850                 let path = route.paths[0].clone();
10851                 route.paths.push(path);
10852                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
10853                 route.paths[0].hops[0].short_channel_id = chan_1_id;
10854                 route.paths[0].hops[1].short_channel_id = chan_3_id;
10855                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
10856                 route.paths[1].hops[0].short_channel_id = chan_2_id;
10857                 route.paths[1].hops[1].short_channel_id = chan_4_id;
10858
10859                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
10860                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
10861                 .unwrap_err() {
10862                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
10863                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
10864                         },
10865                         _ => panic!("unexpected error")
10866                 }
10867         }
10868
10869         #[test]
10870         fn test_drop_disconnected_peers_when_removing_channels() {
10871                 let chanmon_cfgs = create_chanmon_cfgs(2);
10872                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10873                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10874                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10875
10876                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10877
10878                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10879                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10880
10881                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
10882                 check_closed_broadcast!(nodes[0], true);
10883                 check_added_monitors!(nodes[0], 1);
10884                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
10885
10886                 {
10887                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
10888                         // disconnected and the channel between has been force closed.
10889                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10890                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
10891                         assert_eq!(nodes_0_per_peer_state.len(), 1);
10892                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
10893                 }
10894
10895                 nodes[0].node.timer_tick_occurred();
10896
10897                 {
10898                         // Assert that nodes[1] has now been removed.
10899                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
10900                 }
10901         }
10902
10903         #[test]
10904         fn bad_inbound_payment_hash() {
10905                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
10906                 let chanmon_cfgs = create_chanmon_cfgs(2);
10907                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10908                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10909                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10910
10911                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
10912                 let payment_data = msgs::FinalOnionHopData {
10913                         payment_secret,
10914                         total_msat: 100_000,
10915                 };
10916
10917                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
10918                 // payment verification fails as expected.
10919                 let mut bad_payment_hash = payment_hash.clone();
10920                 bad_payment_hash.0[0] += 1;
10921                 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) {
10922                         Ok(_) => panic!("Unexpected ok"),
10923                         Err(()) => {
10924                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
10925                         }
10926                 }
10927
10928                 // Check that using the original payment hash succeeds.
10929                 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());
10930         }
10931
10932         #[test]
10933         fn test_id_to_peer_coverage() {
10934                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
10935                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
10936                 // the channel is successfully closed.
10937                 let chanmon_cfgs = create_chanmon_cfgs(2);
10938                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10939                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10940                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10941
10942                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10943                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10944                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
10945                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10946                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
10947
10948                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10949                 let channel_id = ChannelId::from_bytes(tx.txid().into_inner());
10950                 {
10951                         // Ensure that the `id_to_peer` map is empty until either party has received the
10952                         // funding transaction, and have the real `channel_id`.
10953                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
10954                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10955                 }
10956
10957                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10958                 {
10959                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
10960                         // as it has the funding transaction.
10961                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10962                         assert_eq!(nodes_0_lock.len(), 1);
10963                         assert!(nodes_0_lock.contains_key(&channel_id));
10964                 }
10965
10966                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10967
10968                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10969
10970                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
10971                 {
10972                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10973                         assert_eq!(nodes_0_lock.len(), 1);
10974                         assert!(nodes_0_lock.contains_key(&channel_id));
10975                 }
10976                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10977
10978                 {
10979                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
10980                         // as it has the funding transaction.
10981                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
10982                         assert_eq!(nodes_1_lock.len(), 1);
10983                         assert!(nodes_1_lock.contains_key(&channel_id));
10984                 }
10985                 check_added_monitors!(nodes[1], 1);
10986                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10987                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
10988                 check_added_monitors!(nodes[0], 1);
10989                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
10990                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10991                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10992                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
10993
10994                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
10995                 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()));
10996                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
10997                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
10998
10999                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11000                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11001                 {
11002                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
11003                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11004                         // fee for the closing transaction has been negotiated and the parties has the other
11005                         // party's signature for the fee negotiated closing transaction.)
11006                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
11007                         assert_eq!(nodes_0_lock.len(), 1);
11008                         assert!(nodes_0_lock.contains_key(&channel_id));
11009                 }
11010
11011                 {
11012                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11013                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11014                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11015                         // kept in the `nodes[1]`'s `id_to_peer` map.
11016                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11017                         assert_eq!(nodes_1_lock.len(), 1);
11018                         assert!(nodes_1_lock.contains_key(&channel_id));
11019                 }
11020
11021                 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()));
11022                 {
11023                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11024                         // therefore has all it needs to fully close the channel (both signatures for the
11025                         // closing transaction).
11026                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
11027                         // fully closed by `nodes[0]`.
11028                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11029
11030                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
11031                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11032                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11033                         assert_eq!(nodes_1_lock.len(), 1);
11034                         assert!(nodes_1_lock.contains_key(&channel_id));
11035                 }
11036
11037                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11038
11039                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11040                 {
11041                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
11042                         // they both have everything required to fully close the channel.
11043                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11044                 }
11045                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11046
11047                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11048                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11049         }
11050
11051         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11052                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11053                 check_api_error_message(expected_message, res_err)
11054         }
11055
11056         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11057                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11058                 check_api_error_message(expected_message, res_err)
11059         }
11060
11061         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11062                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11063                 check_api_error_message(expected_message, res_err)
11064         }
11065
11066         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11067                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11068                 check_api_error_message(expected_message, res_err)
11069         }
11070
11071         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11072                 match res_err {
11073                         Err(APIError::APIMisuseError { err }) => {
11074                                 assert_eq!(err, expected_err_message);
11075                         },
11076                         Err(APIError::ChannelUnavailable { err }) => {
11077                                 assert_eq!(err, expected_err_message);
11078                         },
11079                         Ok(_) => panic!("Unexpected Ok"),
11080                         Err(_) => panic!("Unexpected Error"),
11081                 }
11082         }
11083
11084         #[test]
11085         fn test_api_calls_with_unkown_counterparty_node() {
11086                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11087                 // expected if the `counterparty_node_id` is an unkown peer in the
11088                 // `ChannelManager::per_peer_state` map.
11089                 let chanmon_cfg = create_chanmon_cfgs(2);
11090                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11091                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11092                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11093
11094                 // Dummy values
11095                 let channel_id = ChannelId::from_bytes([4; 32]);
11096                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11097                 let intercept_id = InterceptId([0; 32]);
11098
11099                 // Test the API functions.
11100                 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);
11101
11102                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11103
11104                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11105
11106                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11107
11108                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11109
11110                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11111
11112                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11113         }
11114
11115         #[test]
11116         fn test_api_calls_with_unavailable_channel() {
11117                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11118                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11119                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11120                 // the given `channel_id`.
11121                 let chanmon_cfg = create_chanmon_cfgs(2);
11122                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11123                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11124                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11125
11126                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11127
11128                 // Dummy values
11129                 let channel_id = ChannelId::from_bytes([4; 32]);
11130
11131                 // Test the API functions.
11132                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11133
11134                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11135
11136                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11137
11138                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11139
11140                 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);
11141
11142                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11143         }
11144
11145         #[test]
11146         fn test_connection_limiting() {
11147                 // Test that we limit un-channel'd peers and un-funded channels properly.
11148                 let chanmon_cfgs = create_chanmon_cfgs(2);
11149                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11150                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11151                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11152
11153                 // Note that create_network connects the nodes together for us
11154
11155                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11156                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11157
11158                 let mut funding_tx = None;
11159                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11160                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11161                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11162
11163                         if idx == 0 {
11164                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11165                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11166                                 funding_tx = Some(tx.clone());
11167                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11168                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11169
11170                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11171                                 check_added_monitors!(nodes[1], 1);
11172                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11173
11174                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11175
11176                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11177                                 check_added_monitors!(nodes[0], 1);
11178                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11179                         }
11180                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11181                 }
11182
11183                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11184                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11185                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11186                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11187                         open_channel_msg.temporary_channel_id);
11188
11189                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11190                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11191                 // limit.
11192                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11193                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11194                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11195                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11196                         peer_pks.push(random_pk);
11197                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11198                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11199                         }, true).unwrap();
11200                 }
11201                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11202                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11203                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11204                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11205                 }, true).unwrap_err();
11206
11207                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11208                 // them if we have too many un-channel'd peers.
11209                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11210                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11211                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
11212                 for ev in chan_closed_events {
11213                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
11214                 }
11215                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11216                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11217                 }, true).unwrap();
11218                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11219                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11220                 }, true).unwrap_err();
11221
11222                 // but of course if the connection is outbound its allowed...
11223                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11224                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11225                 }, false).unwrap();
11226                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11227
11228                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
11229                 // Even though we accept one more connection from new peers, we won't actually let them
11230                 // open channels.
11231                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
11232                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11233                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
11234                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
11235                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11236                 }
11237                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11238                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11239                         open_channel_msg.temporary_channel_id);
11240
11241                 // Of course, however, outbound channels are always allowed
11242                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
11243                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
11244
11245                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
11246                 // "protected" and can connect again.
11247                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
11248                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11249                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11250                 }, true).unwrap();
11251                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
11252
11253                 // Further, because the first channel was funded, we can open another channel with
11254                 // last_random_pk.
11255                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11256                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11257         }
11258
11259         #[test]
11260         fn test_outbound_chans_unlimited() {
11261                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
11262                 let chanmon_cfgs = create_chanmon_cfgs(2);
11263                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11264                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11265                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11266
11267                 // Note that create_network connects the nodes together for us
11268
11269                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11270                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11271
11272                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11273                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11274                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11275                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11276                 }
11277
11278                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
11279                 // rejected.
11280                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11281                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11282                         open_channel_msg.temporary_channel_id);
11283
11284                 // but we can still open an outbound channel.
11285                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11286                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
11287
11288                 // but even with such an outbound channel, additional inbound channels will still fail.
11289                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11290                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11291                         open_channel_msg.temporary_channel_id);
11292         }
11293
11294         #[test]
11295         fn test_0conf_limiting() {
11296                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11297                 // flag set and (sometimes) accept channels as 0conf.
11298                 let chanmon_cfgs = create_chanmon_cfgs(2);
11299                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11300                 let mut settings = test_default_channel_config();
11301                 settings.manually_accept_inbound_channels = true;
11302                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
11303                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11304
11305                 // Note that create_network connects the nodes together for us
11306
11307                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11308                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11309
11310                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
11311                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11312                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11313                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11314                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11315                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11316                         }, true).unwrap();
11317
11318                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
11319                         let events = nodes[1].node.get_and_clear_pending_events();
11320                         match events[0] {
11321                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11322                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
11323                                 }
11324                                 _ => panic!("Unexpected event"),
11325                         }
11326                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
11327                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11328                 }
11329
11330                 // If we try to accept a channel from another peer non-0conf it will fail.
11331                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11332                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11333                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11334                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11335                 }, true).unwrap();
11336                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11337                 let events = nodes[1].node.get_and_clear_pending_events();
11338                 match events[0] {
11339                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11340                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
11341                                         Err(APIError::APIMisuseError { err }) =>
11342                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
11343                                         _ => panic!(),
11344                                 }
11345                         }
11346                         _ => panic!("Unexpected event"),
11347                 }
11348                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11349                         open_channel_msg.temporary_channel_id);
11350
11351                 // ...however if we accept the same channel 0conf it should work just fine.
11352                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11353                 let events = nodes[1].node.get_and_clear_pending_events();
11354                 match events[0] {
11355                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11356                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
11357                         }
11358                         _ => panic!("Unexpected event"),
11359                 }
11360                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11361         }
11362
11363         #[test]
11364         fn reject_excessively_underpaying_htlcs() {
11365                 let chanmon_cfg = create_chanmon_cfgs(1);
11366                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11367                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11368                 let node = create_network(1, &node_cfg, &node_chanmgr);
11369                 let sender_intended_amt_msat = 100;
11370                 let extra_fee_msat = 10;
11371                 let hop_data = msgs::InboundOnionPayload::Receive {
11372                         amt_msat: 100,
11373                         outgoing_cltv_value: 42,
11374                         payment_metadata: None,
11375                         keysend_preimage: None,
11376                         payment_data: Some(msgs::FinalOnionHopData {
11377                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11378                         }),
11379                         custom_tlvs: Vec::new(),
11380                 };
11381                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
11382                 // intended amount, we fail the payment.
11383                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
11384                         node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11385                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat))
11386                 {
11387                         assert_eq!(err_code, 19);
11388                 } else { panic!(); }
11389
11390                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
11391                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
11392                         amt_msat: 100,
11393                         outgoing_cltv_value: 42,
11394                         payment_metadata: None,
11395                         keysend_preimage: None,
11396                         payment_data: Some(msgs::FinalOnionHopData {
11397                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11398                         }),
11399                         custom_tlvs: Vec::new(),
11400                 };
11401                 assert!(node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11402                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat)).is_ok());
11403         }
11404
11405         #[test]
11406         fn test_final_incorrect_cltv(){
11407                 let chanmon_cfg = create_chanmon_cfgs(1);
11408                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11409                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11410                 let node = create_network(1, &node_cfg, &node_chanmgr);
11411
11412                 let result = node[0].node.construct_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
11413                         amt_msat: 100,
11414                         outgoing_cltv_value: 22,
11415                         payment_metadata: None,
11416                         keysend_preimage: None,
11417                         payment_data: Some(msgs::FinalOnionHopData {
11418                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
11419                         }),
11420                         custom_tlvs: Vec::new(),
11421                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None);
11422
11423                 // Should not return an error as this condition:
11424                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
11425                 // is not satisfied.
11426                 assert!(result.is_ok());
11427         }
11428
11429         #[test]
11430         fn test_inbound_anchors_manual_acceptance() {
11431                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11432                 // flag set and (sometimes) accept channels as 0conf.
11433                 let mut anchors_cfg = test_default_channel_config();
11434                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11435
11436                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
11437                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
11438
11439                 let chanmon_cfgs = create_chanmon_cfgs(3);
11440                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11441                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
11442                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
11443                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11444
11445                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11446                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11447
11448                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11449                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11450                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
11451                 match &msg_events[0] {
11452                         MessageSendEvent::HandleError { node_id, action } => {
11453                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
11454                                 match action {
11455                                         ErrorAction::SendErrorMessage { msg } =>
11456                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
11457                                         _ => panic!("Unexpected error action"),
11458                                 }
11459                         }
11460                         _ => panic!("Unexpected event"),
11461                 }
11462
11463                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11464                 let events = nodes[2].node.get_and_clear_pending_events();
11465                 match events[0] {
11466                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
11467                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
11468                         _ => panic!("Unexpected event"),
11469                 }
11470                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11471         }
11472
11473         #[test]
11474         fn test_anchors_zero_fee_htlc_tx_fallback() {
11475                 // Tests that if both nodes support anchors, but the remote node does not want to accept
11476                 // anchor channels at the moment, an error it sent to the local node such that it can retry
11477                 // the channel without the anchors feature.
11478                 let chanmon_cfgs = create_chanmon_cfgs(2);
11479                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11480                 let mut anchors_config = test_default_channel_config();
11481                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11482                 anchors_config.manually_accept_inbound_channels = true;
11483                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
11484                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11485
11486                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
11487                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11488                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
11489
11490                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &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.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
11495                         }
11496                         _ => panic!("Unexpected event"),
11497                 }
11498
11499                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
11500                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
11501
11502                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11503                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
11504
11505                 // Since nodes[1] should not have accepted the channel, it should
11506                 // not have generated any events.
11507                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11508         }
11509
11510         #[test]
11511         fn test_update_channel_config() {
11512                 let chanmon_cfg = create_chanmon_cfgs(2);
11513                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11514                 let mut user_config = test_default_channel_config();
11515                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11516                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11517                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
11518                 let channel = &nodes[0].node.list_channels()[0];
11519
11520                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11521                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11522                 assert_eq!(events.len(), 0);
11523
11524                 user_config.channel_config.forwarding_fee_base_msat += 10;
11525                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11526                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
11527                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11528                 assert_eq!(events.len(), 1);
11529                 match &events[0] {
11530                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11531                         _ => panic!("expected BroadcastChannelUpdate event"),
11532                 }
11533
11534                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
11535                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11536                 assert_eq!(events.len(), 0);
11537
11538                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
11539                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11540                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
11541                         ..Default::default()
11542                 }).unwrap();
11543                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11544                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11545                 assert_eq!(events.len(), 1);
11546                 match &events[0] {
11547                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11548                         _ => panic!("expected BroadcastChannelUpdate event"),
11549                 }
11550
11551                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
11552                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11553                         forwarding_fee_proportional_millionths: Some(new_fee),
11554                         ..Default::default()
11555                 }).unwrap();
11556                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11557                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
11558                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11559                 assert_eq!(events.len(), 1);
11560                 match &events[0] {
11561                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11562                         _ => panic!("expected BroadcastChannelUpdate event"),
11563                 }
11564
11565                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
11566                 // should be applied to ensure update atomicity as specified in the API docs.
11567                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
11568                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
11569                 let new_fee = current_fee + 100;
11570                 assert!(
11571                         matches!(
11572                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
11573                                         forwarding_fee_proportional_millionths: Some(new_fee),
11574                                         ..Default::default()
11575                                 }),
11576                                 Err(APIError::ChannelUnavailable { err: _ }),
11577                         )
11578                 );
11579                 // Check that the fee hasn't changed for the channel that exists.
11580                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
11581                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11582                 assert_eq!(events.len(), 0);
11583         }
11584
11585         #[test]
11586         fn test_payment_display() {
11587                 let payment_id = PaymentId([42; 32]);
11588                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11589                 let payment_hash = PaymentHash([42; 32]);
11590                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11591                 let payment_preimage = PaymentPreimage([42; 32]);
11592                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11593         }
11594
11595         #[test]
11596         fn test_trigger_lnd_force_close() {
11597                 let chanmon_cfg = create_chanmon_cfgs(2);
11598                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11599                 let user_config = test_default_channel_config();
11600                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11601                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11602
11603                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
11604                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
11605                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11606                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11607                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
11608                 check_closed_broadcast(&nodes[0], 1, true);
11609                 check_added_monitors(&nodes[0], 1);
11610                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11611                 {
11612                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
11613                         assert_eq!(txn.len(), 1);
11614                         check_spends!(txn[0], funding_tx);
11615                 }
11616
11617                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
11618                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
11619                 // their side.
11620                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
11621                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
11622                 }, true).unwrap();
11623                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11624                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11625                 }, false).unwrap();
11626                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
11627                 let channel_reestablish = get_event_msg!(
11628                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
11629                 );
11630                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
11631
11632                 // Alice should respond with an error since the channel isn't known, but a bogus
11633                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
11634                 // close even if it was an lnd node.
11635                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
11636                 assert_eq!(msg_events.len(), 2);
11637                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
11638                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
11639                         assert_eq!(msg.next_local_commitment_number, 0);
11640                         assert_eq!(msg.next_remote_commitment_number, 0);
11641                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
11642                 } else { panic!() };
11643                 check_closed_broadcast(&nodes[1], 1, true);
11644                 check_added_monitors(&nodes[1], 1);
11645                 let expected_close_reason = ClosureReason::ProcessingError {
11646                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
11647                 };
11648                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
11649                 {
11650                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
11651                         assert_eq!(txn.len(), 1);
11652                         check_spends!(txn[0], funding_tx);
11653                 }
11654         }
11655 }
11656
11657 #[cfg(ldk_bench)]
11658 pub mod bench {
11659         use crate::chain::Listen;
11660         use crate::chain::chainmonitor::{ChainMonitor, Persist};
11661         use crate::sign::{KeysManager, InMemorySigner};
11662         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
11663         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
11664         use crate::ln::functional_test_utils::*;
11665         use crate::ln::msgs::{ChannelMessageHandler, Init};
11666         use crate::routing::gossip::NetworkGraph;
11667         use crate::routing::router::{PaymentParameters, RouteParameters};
11668         use crate::util::test_utils;
11669         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
11670
11671         use bitcoin::hashes::Hash;
11672         use bitcoin::hashes::sha256::Hash as Sha256;
11673         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
11674
11675         use crate::sync::{Arc, Mutex, RwLock};
11676
11677         use criterion::Criterion;
11678
11679         type Manager<'a, P> = ChannelManager<
11680                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
11681                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
11682                         &'a test_utils::TestLogger, &'a P>,
11683                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
11684                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
11685                 &'a test_utils::TestLogger>;
11686
11687         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
11688                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
11689         }
11690         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
11691                 type CM = Manager<'chan_mon_cfg, P>;
11692                 #[inline]
11693                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
11694                 #[inline]
11695                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
11696         }
11697
11698         pub fn bench_sends(bench: &mut Criterion) {
11699                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
11700         }
11701
11702         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
11703                 // Do a simple benchmark of sending a payment back and forth between two nodes.
11704                 // Note that this is unrealistic as each payment send will require at least two fsync
11705                 // calls per node.
11706                 let network = bitcoin::Network::Testnet;
11707                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
11708
11709                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
11710                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
11711                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
11712                 let scorer = RwLock::new(test_utils::TestScorer::new());
11713                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
11714
11715                 let mut config: UserConfig = Default::default();
11716                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
11717                 config.channel_handshake_config.minimum_depth = 1;
11718
11719                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
11720                 let seed_a = [1u8; 32];
11721                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
11722                 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 {
11723                         network,
11724                         best_block: BestBlock::from_network(network),
11725                 }, genesis_block.header.time);
11726                 let node_a_holder = ANodeHolder { node: &node_a };
11727
11728                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
11729                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
11730                 let seed_b = [2u8; 32];
11731                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
11732                 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 {
11733                         network,
11734                         best_block: BestBlock::from_network(network),
11735                 }, genesis_block.header.time);
11736                 let node_b_holder = ANodeHolder { node: &node_b };
11737
11738                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
11739                         features: node_b.init_features(), networks: None, remote_network_address: None
11740                 }, true).unwrap();
11741                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
11742                         features: node_a.init_features(), networks: None, remote_network_address: None
11743                 }, false).unwrap();
11744                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
11745                 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()));
11746                 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()));
11747
11748                 let tx;
11749                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
11750                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
11751                                 value: 8_000_000, script_pubkey: output_script,
11752                         }]};
11753                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
11754                 } else { panic!(); }
11755
11756                 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()));
11757                 let events_b = node_b.get_and_clear_pending_events();
11758                 assert_eq!(events_b.len(), 1);
11759                 match events_b[0] {
11760                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11761                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11762                         },
11763                         _ => panic!("Unexpected event"),
11764                 }
11765
11766                 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()));
11767                 let events_a = node_a.get_and_clear_pending_events();
11768                 assert_eq!(events_a.len(), 1);
11769                 match events_a[0] {
11770                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11771                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11772                         },
11773                         _ => panic!("Unexpected event"),
11774                 }
11775
11776                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
11777
11778                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
11779                 Listen::block_connected(&node_a, &block, 1);
11780                 Listen::block_connected(&node_b, &block, 1);
11781
11782                 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()));
11783                 let msg_events = node_a.get_and_clear_pending_msg_events();
11784                 assert_eq!(msg_events.len(), 2);
11785                 match msg_events[0] {
11786                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
11787                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
11788                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
11789                         },
11790                         _ => panic!(),
11791                 }
11792                 match msg_events[1] {
11793                         MessageSendEvent::SendChannelUpdate { .. } => {},
11794                         _ => panic!(),
11795                 }
11796
11797                 let events_a = node_a.get_and_clear_pending_events();
11798                 assert_eq!(events_a.len(), 1);
11799                 match events_a[0] {
11800                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11801                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11802                         },
11803                         _ => panic!("Unexpected event"),
11804                 }
11805
11806                 let events_b = node_b.get_and_clear_pending_events();
11807                 assert_eq!(events_b.len(), 1);
11808                 match events_b[0] {
11809                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11810                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11811                         },
11812                         _ => panic!("Unexpected event"),
11813                 }
11814
11815                 let mut payment_count: u64 = 0;
11816                 macro_rules! send_payment {
11817                         ($node_a: expr, $node_b: expr) => {
11818                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
11819                                         .with_bolt11_features($node_b.invoice_features()).unwrap();
11820                                 let mut payment_preimage = PaymentPreimage([0; 32]);
11821                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
11822                                 payment_count += 1;
11823                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
11824                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
11825
11826                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
11827                                         PaymentId(payment_hash.0),
11828                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
11829                                         Retry::Attempts(0)).unwrap();
11830                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
11831                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
11832                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
11833                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
11834                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
11835                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
11836                                 $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()));
11837
11838                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
11839                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
11840                                 $node_b.claim_funds(payment_preimage);
11841                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
11842
11843                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
11844                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
11845                                                 assert_eq!(node_id, $node_a.get_our_node_id());
11846                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
11847                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
11848                                         },
11849                                         _ => panic!("Failed to generate claim event"),
11850                                 }
11851
11852                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
11853                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
11854                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
11855                                 $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()));
11856
11857                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
11858                         }
11859                 }
11860
11861                 bench.bench_function(bench_name, |b| b.iter(|| {
11862                         send_payment!(node_a, node_b);
11863                         send_payment!(node_b, node_a);
11864                 }));
11865         }
11866 }