Merge pull request #2661 from TheBlueMatt/2023-10-dup-claim-chan-hang
[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};
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::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, WriteableEcdsaChannelSigner};
63 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
64 use crate::util::wakers::{Future, Notifier};
65 use crate::util::scid_utils::fake_scid;
66 use crate::util::string::UntrustedString;
67 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
68 use crate::util::logger::{Level, Logger};
69 use crate::util::errors::APIError;
70
71 use alloc::collections::{btree_map, BTreeMap};
72
73 use crate::io;
74 use crate::prelude::*;
75 use core::{cmp, mem};
76 use core::cell::RefCell;
77 use crate::io::Read;
78 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
79 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
80 use core::time::Duration;
81 use core::ops::Deref;
82
83 // Re-export this for use in the public API.
84 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
85 use crate::ln::script::ShutdownScript;
86
87 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
88 //
89 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
90 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
91 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
92 //
93 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
94 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
95 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
96 // before we forward it.
97 //
98 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
99 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
100 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
101 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
102 // our payment, which we can use to decode errors or inform the user that the payment was sent.
103
104 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
105 pub(super) enum PendingHTLCRouting {
106         Forward {
107                 onion_packet: msgs::OnionPacket,
108                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
109                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
110                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
111         },
112         Receive {
113                 payment_data: msgs::FinalOnionHopData,
114                 payment_metadata: Option<Vec<u8>>,
115                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
116                 phantom_shared_secret: Option<[u8; 32]>,
117                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
118                 custom_tlvs: Vec<(u64, Vec<u8>)>,
119         },
120         ReceiveKeysend {
121                 /// This was added in 0.0.116 and will break deserialization on downgrades.
122                 payment_data: Option<msgs::FinalOnionHopData>,
123                 payment_preimage: PaymentPreimage,
124                 payment_metadata: Option<Vec<u8>>,
125                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
126                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
127                 custom_tlvs: Vec<(u64, Vec<u8>)>,
128         },
129 }
130
131 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
132 pub(super) struct PendingHTLCInfo {
133         pub(super) routing: PendingHTLCRouting,
134         pub(super) incoming_shared_secret: [u8; 32],
135         payment_hash: PaymentHash,
136         /// Amount received
137         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
138         /// Sender intended amount to forward or receive (actual amount received
139         /// may overshoot this in either case)
140         pub(super) outgoing_amt_msat: u64,
141         pub(super) outgoing_cltv_value: u32,
142         /// The fee being skimmed off the top of this HTLC. If this is a forward, it'll be the fee we are
143         /// skimming. If we're receiving this HTLC, it's the fee that our counterparty skimmed.
144         pub(super) skimmed_fee_msat: Option<u64>,
145 }
146
147 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
148 pub(super) enum HTLCFailureMsg {
149         Relay(msgs::UpdateFailHTLC),
150         Malformed(msgs::UpdateFailMalformedHTLC),
151 }
152
153 /// Stores whether we can't forward an HTLC or relevant forwarding info
154 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
155 pub(super) enum PendingHTLCStatus {
156         Forward(PendingHTLCInfo),
157         Fail(HTLCFailureMsg),
158 }
159
160 pub(super) struct PendingAddHTLCInfo {
161         pub(super) forward_info: PendingHTLCInfo,
162
163         // These fields are produced in `forward_htlcs()` and consumed in
164         // `process_pending_htlc_forwards()` for constructing the
165         // `HTLCSource::PreviousHopData` for failed and forwarded
166         // HTLCs.
167         //
168         // Note that this may be an outbound SCID alias for the associated channel.
169         prev_short_channel_id: u64,
170         prev_htlc_id: u64,
171         prev_funding_outpoint: OutPoint,
172         prev_user_channel_id: u128,
173 }
174
175 pub(super) enum HTLCForwardInfo {
176         AddHTLC(PendingAddHTLCInfo),
177         FailHTLC {
178                 htlc_id: u64,
179                 err_packet: msgs::OnionErrorPacket,
180         },
181 }
182
183 /// Tracks the inbound corresponding to an outbound HTLC
184 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
185 pub(crate) struct HTLCPreviousHopData {
186         // Note that this may be an outbound SCID alias for the associated channel.
187         short_channel_id: u64,
188         user_channel_id: Option<u128>,
189         htlc_id: u64,
190         incoming_packet_shared_secret: [u8; 32],
191         phantom_shared_secret: Option<[u8; 32]>,
192
193         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
194         // channel with a preimage provided by the forward channel.
195         outpoint: OutPoint,
196 }
197
198 enum OnionPayload {
199         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
200         Invoice {
201                 /// This is only here for backwards-compatibility in serialization, in the future it can be
202                 /// removed, breaking clients running 0.0.106 and earlier.
203                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
204         },
205         /// Contains the payer-provided preimage.
206         Spontaneous(PaymentPreimage),
207 }
208
209 /// HTLCs that are to us and can be failed/claimed by the user
210 struct ClaimableHTLC {
211         prev_hop: HTLCPreviousHopData,
212         cltv_expiry: u32,
213         /// The amount (in msats) of this MPP part
214         value: u64,
215         /// The amount (in msats) that the sender intended to be sent in this MPP
216         /// part (used for validating total MPP amount)
217         sender_intended_value: u64,
218         onion_payload: OnionPayload,
219         timer_ticks: u8,
220         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
221         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
222         total_value_received: Option<u64>,
223         /// The sender intended sum total of all MPP parts specified in the onion
224         total_msat: u64,
225         /// The extra fee our counterparty skimmed off the top of this HTLC.
226         counterparty_skimmed_fee_msat: Option<u64>,
227 }
228
229 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
230         fn from(val: &ClaimableHTLC) -> Self {
231                 events::ClaimedHTLC {
232                         channel_id: val.prev_hop.outpoint.to_channel_id(),
233                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
234                         cltv_expiry: val.cltv_expiry,
235                         value_msat: val.value,
236                 }
237         }
238 }
239
240 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
241 /// a payment and ensure idempotency in LDK.
242 ///
243 /// This is not exported to bindings users as we just use [u8; 32] directly
244 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
245 pub struct PaymentId(pub [u8; Self::LENGTH]);
246
247 impl PaymentId {
248         /// Number of bytes in the id.
249         pub const LENGTH: usize = 32;
250 }
251
252 impl Writeable for PaymentId {
253         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
254                 self.0.write(w)
255         }
256 }
257
258 impl Readable for PaymentId {
259         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
260                 let buf: [u8; 32] = Readable::read(r)?;
261                 Ok(PaymentId(buf))
262         }
263 }
264
265 impl core::fmt::Display for PaymentId {
266         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
267                 crate::util::logger::DebugBytes(&self.0).fmt(f)
268         }
269 }
270
271 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
272 ///
273 /// This is not exported to bindings users as we just use [u8; 32] directly
274 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
275 pub struct InterceptId(pub [u8; 32]);
276
277 impl Writeable for InterceptId {
278         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
279                 self.0.write(w)
280         }
281 }
282
283 impl Readable for InterceptId {
284         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
285                 let buf: [u8; 32] = Readable::read(r)?;
286                 Ok(InterceptId(buf))
287         }
288 }
289
290 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
291 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
292 pub(crate) enum SentHTLCId {
293         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
294         OutboundRoute { session_priv: SecretKey },
295 }
296 impl SentHTLCId {
297         pub(crate) fn from_source(source: &HTLCSource) -> Self {
298                 match source {
299                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
300                                 short_channel_id: hop_data.short_channel_id,
301                                 htlc_id: hop_data.htlc_id,
302                         },
303                         HTLCSource::OutboundRoute { session_priv, .. } =>
304                                 Self::OutboundRoute { session_priv: *session_priv },
305                 }
306         }
307 }
308 impl_writeable_tlv_based_enum!(SentHTLCId,
309         (0, PreviousHopData) => {
310                 (0, short_channel_id, required),
311                 (2, htlc_id, required),
312         },
313         (2, OutboundRoute) => {
314                 (0, session_priv, required),
315         };
316 );
317
318
319 /// Tracks the inbound corresponding to an outbound HTLC
320 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
321 #[derive(Clone, Debug, PartialEq, Eq)]
322 pub(crate) enum HTLCSource {
323         PreviousHopData(HTLCPreviousHopData),
324         OutboundRoute {
325                 path: Path,
326                 session_priv: SecretKey,
327                 /// Technically we can recalculate this from the route, but we cache it here to avoid
328                 /// doing a double-pass on route when we get a failure back
329                 first_hop_htlc_msat: u64,
330                 payment_id: PaymentId,
331         },
332 }
333 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
334 impl core::hash::Hash for HTLCSource {
335         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
336                 match self {
337                         HTLCSource::PreviousHopData(prev_hop_data) => {
338                                 0u8.hash(hasher);
339                                 prev_hop_data.hash(hasher);
340                         },
341                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
342                                 1u8.hash(hasher);
343                                 path.hash(hasher);
344                                 session_priv[..].hash(hasher);
345                                 payment_id.hash(hasher);
346                                 first_hop_htlc_msat.hash(hasher);
347                         },
348                 }
349         }
350 }
351 impl HTLCSource {
352         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
353         #[cfg(test)]
354         pub fn dummy() -> Self {
355                 HTLCSource::OutboundRoute {
356                         path: Path { hops: Vec::new(), blinded_tail: None },
357                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
358                         first_hop_htlc_msat: 0,
359                         payment_id: PaymentId([2; 32]),
360                 }
361         }
362
363         #[cfg(debug_assertions)]
364         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
365         /// transaction. Useful to ensure different datastructures match up.
366         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
367                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
368                         *first_hop_htlc_msat == htlc.amount_msat
369                 } else {
370                         // There's nothing we can check for forwarded HTLCs
371                         true
372                 }
373         }
374 }
375
376 struct InboundOnionErr {
377         err_code: u16,
378         err_data: Vec<u8>,
379         msg: &'static str,
380 }
381
382 /// This enum is used to specify which error data to send to peers when failing back an HTLC
383 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
384 ///
385 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
386 #[derive(Clone, Copy)]
387 pub enum FailureCode {
388         /// We had a temporary error processing the payment. Useful if no other error codes fit
389         /// and you want to indicate that the payer may want to retry.
390         TemporaryNodeFailure,
391         /// We have a required feature which was not in this onion. For example, you may require
392         /// some additional metadata that was not provided with this payment.
393         RequiredNodeFeatureMissing,
394         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
395         /// the HTLC is too close to the current block height for safe handling.
396         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
397         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
398         IncorrectOrUnknownPaymentDetails,
399         /// We failed to process the payload after the onion was decrypted. You may wish to
400         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
401         ///
402         /// If available, the tuple data may include the type number and byte offset in the
403         /// decrypted byte stream where the failure occurred.
404         InvalidOnionPayload(Option<(u64, u16)>),
405 }
406
407 impl Into<u16> for FailureCode {
408     fn into(self) -> u16 {
409                 match self {
410                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
411                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
412                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
413                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
414                 }
415         }
416 }
417
418 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
419 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
420 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
421 /// peer_state lock. We then return the set of things that need to be done outside the lock in
422 /// this struct and call handle_error!() on it.
423
424 struct MsgHandleErrInternal {
425         err: msgs::LightningError,
426         chan_id: Option<(ChannelId, u128)>, // If Some a channel of ours has been closed
427         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
428         channel_capacity: Option<u64>,
429 }
430 impl MsgHandleErrInternal {
431         #[inline]
432         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
433                 Self {
434                         err: LightningError {
435                                 err: err.clone(),
436                                 action: msgs::ErrorAction::SendErrorMessage {
437                                         msg: msgs::ErrorMessage {
438                                                 channel_id,
439                                                 data: err
440                                         },
441                                 },
442                         },
443                         chan_id: None,
444                         shutdown_finish: None,
445                         channel_capacity: None,
446                 }
447         }
448         #[inline]
449         fn from_no_close(err: msgs::LightningError) -> Self {
450                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
451         }
452         #[inline]
453         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 {
454                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
455                 let action = if let (Some(_), ..) = &shutdown_res {
456                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
457                         // should disconnect our peer such that we force them to broadcast their latest
458                         // commitment upon reconnecting.
459                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
460                 } else {
461                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
462                 };
463                 Self {
464                         err: LightningError { err, action },
465                         chan_id: Some((channel_id, user_channel_id)),
466                         shutdown_finish: Some((shutdown_res, channel_update)),
467                         channel_capacity: Some(channel_capacity)
468                 }
469         }
470         #[inline]
471         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
472                 Self {
473                         err: match err {
474                                 ChannelError::Warn(msg) =>  LightningError {
475                                         err: msg.clone(),
476                                         action: msgs::ErrorAction::SendWarningMessage {
477                                                 msg: msgs::WarningMessage {
478                                                         channel_id,
479                                                         data: msg
480                                                 },
481                                                 log_level: Level::Warn,
482                                         },
483                                 },
484                                 ChannelError::Ignore(msg) => LightningError {
485                                         err: msg,
486                                         action: msgs::ErrorAction::IgnoreError,
487                                 },
488                                 ChannelError::Close(msg) => LightningError {
489                                         err: msg.clone(),
490                                         action: msgs::ErrorAction::SendErrorMessage {
491                                                 msg: msgs::ErrorMessage {
492                                                         channel_id,
493                                                         data: msg
494                                                 },
495                                         },
496                                 },
497                         },
498                         chan_id: None,
499                         shutdown_finish: None,
500                         channel_capacity: None,
501                 }
502         }
503
504         fn closes_channel(&self) -> bool {
505                 self.chan_id.is_some()
506         }
507 }
508
509 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
510 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
511 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
512 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
513 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
514
515 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
516 /// be sent in the order they appear in the return value, however sometimes the order needs to be
517 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
518 /// they were originally sent). In those cases, this enum is also returned.
519 #[derive(Clone, PartialEq)]
520 pub(super) enum RAACommitmentOrder {
521         /// Send the CommitmentUpdate messages first
522         CommitmentFirst,
523         /// Send the RevokeAndACK message first
524         RevokeAndACKFirst,
525 }
526
527 /// Information about a payment which is currently being claimed.
528 struct ClaimingPayment {
529         amount_msat: u64,
530         payment_purpose: events::PaymentPurpose,
531         receiver_node_id: PublicKey,
532         htlcs: Vec<events::ClaimedHTLC>,
533         sender_intended_value: Option<u64>,
534 }
535 impl_writeable_tlv_based!(ClaimingPayment, {
536         (0, amount_msat, required),
537         (2, payment_purpose, required),
538         (4, receiver_node_id, required),
539         (5, htlcs, optional_vec),
540         (7, sender_intended_value, option),
541 });
542
543 struct ClaimablePayment {
544         purpose: events::PaymentPurpose,
545         onion_fields: Option<RecipientOnionFields>,
546         htlcs: Vec<ClaimableHTLC>,
547 }
548
549 /// Information about claimable or being-claimed payments
550 struct ClaimablePayments {
551         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
552         /// failed/claimed by the user.
553         ///
554         /// Note that, no consistency guarantees are made about the channels given here actually
555         /// existing anymore by the time you go to read them!
556         ///
557         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
558         /// we don't get a duplicate payment.
559         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
560
561         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
562         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
563         /// as an [`events::Event::PaymentClaimed`].
564         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
565 }
566
567 /// Events which we process internally but cannot be processed immediately at the generation site
568 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
569 /// running normally, and specifically must be processed before any other non-background
570 /// [`ChannelMonitorUpdate`]s are applied.
571 #[derive(Debug)]
572 enum BackgroundEvent {
573         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
574         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
575         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
576         /// channel has been force-closed we do not need the counterparty node_id.
577         ///
578         /// Note that any such events are lost on shutdown, so in general they must be updates which
579         /// are regenerated on startup.
580         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
581         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
582         /// channel to continue normal operation.
583         ///
584         /// In general this should be used rather than
585         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
586         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
587         /// error the other variant is acceptable.
588         ///
589         /// Note that any such events are lost on shutdown, so in general they must be updates which
590         /// are regenerated on startup.
591         MonitorUpdateRegeneratedOnStartup {
592                 counterparty_node_id: PublicKey,
593                 funding_txo: OutPoint,
594                 update: ChannelMonitorUpdate
595         },
596         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
597         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
598         /// on a channel.
599         MonitorUpdatesComplete {
600                 counterparty_node_id: PublicKey,
601                 channel_id: ChannelId,
602         },
603 }
604
605 #[derive(Debug)]
606 pub(crate) enum MonitorUpdateCompletionAction {
607         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
608         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
609         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
610         /// event can be generated.
611         PaymentClaimed { payment_hash: PaymentHash },
612         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
613         /// operation of another channel.
614         ///
615         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
616         /// from completing a monitor update which removes the payment preimage until the inbound edge
617         /// completes a monitor update containing the payment preimage. In that case, after the inbound
618         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
619         /// outbound edge.
620         EmitEventAndFreeOtherChannel {
621                 event: events::Event,
622                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
623         },
624         /// Indicates we should immediately resume the operation of another channel, unless there is
625         /// some other reason why the channel is blocked. In practice this simply means immediately
626         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
627         ///
628         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
629         /// from completing a monitor update which removes the payment preimage until the inbound edge
630         /// completes a monitor update containing the payment preimage. However, we use this variant
631         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
632         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
633         ///
634         /// This variant should thus never be written to disk, as it is processed inline rather than
635         /// stored for later processing.
636         FreeOtherChannelImmediately {
637                 downstream_counterparty_node_id: PublicKey,
638                 downstream_funding_outpoint: OutPoint,
639                 blocking_action: RAAMonitorUpdateBlockingAction,
640         },
641 }
642
643 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
644         (0, PaymentClaimed) => { (0, payment_hash, required) },
645         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
646         // *immediately*. However, for simplicity we implement read/write here.
647         (1, FreeOtherChannelImmediately) => {
648                 (0, downstream_counterparty_node_id, required),
649                 (2, downstream_funding_outpoint, required),
650                 (4, blocking_action, required),
651         },
652         (2, EmitEventAndFreeOtherChannel) => {
653                 (0, event, upgradable_required),
654                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
655                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
656                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
657                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
658                 // downgrades to prior versions.
659                 (1, downstream_counterparty_and_funding_outpoint, option),
660         },
661 );
662
663 #[derive(Clone, Debug, PartialEq, Eq)]
664 pub(crate) enum EventCompletionAction {
665         ReleaseRAAChannelMonitorUpdate {
666                 counterparty_node_id: PublicKey,
667                 channel_funding_outpoint: OutPoint,
668         },
669 }
670 impl_writeable_tlv_based_enum!(EventCompletionAction,
671         (0, ReleaseRAAChannelMonitorUpdate) => {
672                 (0, channel_funding_outpoint, required),
673                 (2, counterparty_node_id, required),
674         };
675 );
676
677 #[derive(Clone, PartialEq, Eq, Debug)]
678 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
679 /// the blocked action here. See enum variants for more info.
680 pub(crate) enum RAAMonitorUpdateBlockingAction {
681         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
682         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
683         /// durably to disk.
684         ForwardedPaymentInboundClaim {
685                 /// The upstream channel ID (i.e. the inbound edge).
686                 channel_id: ChannelId,
687                 /// The HTLC ID on the inbound edge.
688                 htlc_id: u64,
689         },
690 }
691
692 impl RAAMonitorUpdateBlockingAction {
693         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
694                 Self::ForwardedPaymentInboundClaim {
695                         channel_id: prev_hop.outpoint.to_channel_id(),
696                         htlc_id: prev_hop.htlc_id,
697                 }
698         }
699 }
700
701 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
702         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
703 ;);
704
705
706 /// State we hold per-peer.
707 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
708         /// `channel_id` -> `ChannelPhase`
709         ///
710         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
711         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
712         /// `temporary_channel_id` -> `InboundChannelRequest`.
713         ///
714         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
715         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
716         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
717         /// the channel is rejected, then the entry is simply removed.
718         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
719         /// The latest `InitFeatures` we heard from the peer.
720         latest_features: InitFeatures,
721         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
722         /// for broadcast messages, where ordering isn't as strict).
723         pub(super) pending_msg_events: Vec<MessageSendEvent>,
724         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
725         /// user but which have not yet completed.
726         ///
727         /// Note that the channel may no longer exist. For example if the channel was closed but we
728         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
729         /// for a missing channel.
730         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
731         /// Map from a specific channel to some action(s) that should be taken when all pending
732         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
733         ///
734         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
735         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
736         /// channels with a peer this will just be one allocation and will amount to a linear list of
737         /// channels to walk, avoiding the whole hashing rigmarole.
738         ///
739         /// Note that the channel may no longer exist. For example, if a channel was closed but we
740         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
741         /// for a missing channel. While a malicious peer could construct a second channel with the
742         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
743         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
744         /// duplicates do not occur, so such channels should fail without a monitor update completing.
745         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
746         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
747         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
748         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
749         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
750         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
751         /// The peer is currently connected (i.e. we've seen a
752         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
753         /// [`ChannelMessageHandler::peer_disconnected`].
754         is_connected: bool,
755 }
756
757 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
758         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
759         /// If true is passed for `require_disconnected`, the function will return false if we haven't
760         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
761         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
762                 if require_disconnected && self.is_connected {
763                         return false
764                 }
765                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
766                         && self.monitor_update_blocked_actions.is_empty()
767                         && self.in_flight_monitor_updates.is_empty()
768         }
769
770         // Returns a count of all channels we have with this peer, including unfunded channels.
771         fn total_channel_count(&self) -> usize {
772                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
773         }
774
775         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
776         fn has_channel(&self, channel_id: &ChannelId) -> bool {
777                 self.channel_by_id.contains_key(channel_id) ||
778                         self.inbound_channel_request_by_id.contains_key(channel_id)
779         }
780 }
781
782 /// A not-yet-accepted inbound (from counterparty) channel. Once
783 /// accepted, the parameters will be used to construct a channel.
784 pub(super) struct InboundChannelRequest {
785         /// The original OpenChannel message.
786         pub open_channel_msg: msgs::OpenChannel,
787         /// The number of ticks remaining before the request expires.
788         pub ticks_remaining: i32,
789 }
790
791 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
792 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
793 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
794
795 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
796 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
797 ///
798 /// For users who don't want to bother doing their own payment preimage storage, we also store that
799 /// here.
800 ///
801 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
802 /// and instead encoding it in the payment secret.
803 struct PendingInboundPayment {
804         /// The payment secret that the sender must use for us to accept this payment
805         payment_secret: PaymentSecret,
806         /// Time at which this HTLC expires - blocks with a header time above this value will result in
807         /// this payment being removed.
808         expiry_time: u64,
809         /// Arbitrary identifier the user specifies (or not)
810         user_payment_id: u64,
811         // Other required attributes of the payment, optionally enforced:
812         payment_preimage: Option<PaymentPreimage>,
813         min_value_msat: Option<u64>,
814 }
815
816 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
817 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
818 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
819 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
820 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
821 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
822 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
823 /// of [`KeysManager`] and [`DefaultRouter`].
824 ///
825 /// This is not exported to bindings users as Arcs don't make sense in bindings
826 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
827         Arc<M>,
828         Arc<T>,
829         Arc<KeysManager>,
830         Arc<KeysManager>,
831         Arc<KeysManager>,
832         Arc<F>,
833         Arc<DefaultRouter<
834                 Arc<NetworkGraph<Arc<L>>>,
835                 Arc<L>,
836                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
837                 ProbabilisticScoringFeeParameters,
838                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
839         >>,
840         Arc<L>
841 >;
842
843 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
844 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
845 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
846 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
847 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
848 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
849 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
850 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
851 /// of [`KeysManager`] and [`DefaultRouter`].
852 ///
853 /// This is not exported to bindings users as Arcs don't make sense in bindings
854 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
855         ChannelManager<
856                 &'a M,
857                 &'b T,
858                 &'c KeysManager,
859                 &'c KeysManager,
860                 &'c KeysManager,
861                 &'d F,
862                 &'e DefaultRouter<
863                         &'f NetworkGraph<&'g L>,
864                         &'g L,
865                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
866                         ProbabilisticScoringFeeParameters,
867                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
868                 >,
869                 &'g L
870         >;
871
872 /// A trivial trait which describes any [`ChannelManager`].
873 ///
874 /// This is not exported to bindings users as general cover traits aren't useful in other
875 /// languages.
876 pub trait AChannelManager {
877         /// A type implementing [`chain::Watch`].
878         type Watch: chain::Watch<Self::Signer> + ?Sized;
879         /// A type that may be dereferenced to [`Self::Watch`].
880         type M: Deref<Target = Self::Watch>;
881         /// A type implementing [`BroadcasterInterface`].
882         type Broadcaster: BroadcasterInterface + ?Sized;
883         /// A type that may be dereferenced to [`Self::Broadcaster`].
884         type T: Deref<Target = Self::Broadcaster>;
885         /// A type implementing [`EntropySource`].
886         type EntropySource: EntropySource + ?Sized;
887         /// A type that may be dereferenced to [`Self::EntropySource`].
888         type ES: Deref<Target = Self::EntropySource>;
889         /// A type implementing [`NodeSigner`].
890         type NodeSigner: NodeSigner + ?Sized;
891         /// A type that may be dereferenced to [`Self::NodeSigner`].
892         type NS: Deref<Target = Self::NodeSigner>;
893         /// A type implementing [`WriteableEcdsaChannelSigner`].
894         type Signer: WriteableEcdsaChannelSigner + Sized;
895         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
896         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
897         /// A type that may be dereferenced to [`Self::SignerProvider`].
898         type SP: Deref<Target = Self::SignerProvider>;
899         /// A type implementing [`FeeEstimator`].
900         type FeeEstimator: FeeEstimator + ?Sized;
901         /// A type that may be dereferenced to [`Self::FeeEstimator`].
902         type F: Deref<Target = Self::FeeEstimator>;
903         /// A type implementing [`Router`].
904         type Router: Router + ?Sized;
905         /// A type that may be dereferenced to [`Self::Router`].
906         type R: Deref<Target = Self::Router>;
907         /// A type implementing [`Logger`].
908         type Logger: Logger + ?Sized;
909         /// A type that may be dereferenced to [`Self::Logger`].
910         type L: Deref<Target = Self::Logger>;
911         /// Returns a reference to the actual [`ChannelManager`] object.
912         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
913 }
914
915 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
916 for ChannelManager<M, T, ES, NS, SP, F, R, L>
917 where
918         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
919         T::Target: BroadcasterInterface,
920         ES::Target: EntropySource,
921         NS::Target: NodeSigner,
922         SP::Target: SignerProvider,
923         F::Target: FeeEstimator,
924         R::Target: Router,
925         L::Target: Logger,
926 {
927         type Watch = M::Target;
928         type M = M;
929         type Broadcaster = T::Target;
930         type T = T;
931         type EntropySource = ES::Target;
932         type ES = ES;
933         type NodeSigner = NS::Target;
934         type NS = NS;
935         type Signer = <SP::Target as SignerProvider>::Signer;
936         type SignerProvider = SP::Target;
937         type SP = SP;
938         type FeeEstimator = F::Target;
939         type F = F;
940         type Router = R::Target;
941         type R = R;
942         type Logger = L::Target;
943         type L = L;
944         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
945 }
946
947 /// Manager which keeps track of a number of channels and sends messages to the appropriate
948 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
949 ///
950 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
951 /// to individual Channels.
952 ///
953 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
954 /// all peers during write/read (though does not modify this instance, only the instance being
955 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
956 /// called [`funding_transaction_generated`] for outbound channels) being closed.
957 ///
958 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
959 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
960 /// [`ChannelMonitorUpdate`] before returning from
961 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
962 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
963 /// `ChannelManager` operations from occurring during the serialization process). If the
964 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
965 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
966 /// will be lost (modulo on-chain transaction fees).
967 ///
968 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
969 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
970 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
971 ///
972 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
973 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
974 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
975 /// offline for a full minute. In order to track this, you must call
976 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
977 ///
978 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
979 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
980 /// not have a channel with being unable to connect to us or open new channels with us if we have
981 /// many peers with unfunded channels.
982 ///
983 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
984 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
985 /// never limited. Please ensure you limit the count of such channels yourself.
986 ///
987 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
988 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
989 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
990 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
991 /// you're using lightning-net-tokio.
992 ///
993 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
994 /// [`funding_created`]: msgs::FundingCreated
995 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
996 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
997 /// [`update_channel`]: chain::Watch::update_channel
998 /// [`ChannelUpdate`]: msgs::ChannelUpdate
999 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1000 /// [`read`]: ReadableArgs::read
1001 //
1002 // Lock order:
1003 // The tree structure below illustrates the lock order requirements for the different locks of the
1004 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1005 // and should then be taken in the order of the lowest to the highest level in the tree.
1006 // Note that locks on different branches shall not be taken at the same time, as doing so will
1007 // create a new lock order for those specific locks in the order they were taken.
1008 //
1009 // Lock order tree:
1010 //
1011 // `total_consistency_lock`
1012 //  |
1013 //  |__`forward_htlcs`
1014 //  |   |
1015 //  |   |__`pending_intercepted_htlcs`
1016 //  |
1017 //  |__`per_peer_state`
1018 //  |   |
1019 //  |   |__`pending_inbound_payments`
1020 //  |       |
1021 //  |       |__`claimable_payments`
1022 //  |       |
1023 //  |       |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1024 //  |           |
1025 //  |           |__`peer_state`
1026 //  |               |
1027 //  |               |__`id_to_peer`
1028 //  |               |
1029 //  |               |__`short_to_chan_info`
1030 //  |               |
1031 //  |               |__`outbound_scid_aliases`
1032 //  |               |
1033 //  |               |__`best_block`
1034 //  |               |
1035 //  |               |__`pending_events`
1036 //  |                   |
1037 //  |                   |__`pending_background_events`
1038 //
1039 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1040 where
1041         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1042         T::Target: BroadcasterInterface,
1043         ES::Target: EntropySource,
1044         NS::Target: NodeSigner,
1045         SP::Target: SignerProvider,
1046         F::Target: FeeEstimator,
1047         R::Target: Router,
1048         L::Target: Logger,
1049 {
1050         default_configuration: UserConfig,
1051         chain_hash: ChainHash,
1052         fee_estimator: LowerBoundedFeeEstimator<F>,
1053         chain_monitor: M,
1054         tx_broadcaster: T,
1055         #[allow(unused)]
1056         router: R,
1057
1058         /// See `ChannelManager` struct-level documentation for lock order requirements.
1059         #[cfg(test)]
1060         pub(super) best_block: RwLock<BestBlock>,
1061         #[cfg(not(test))]
1062         best_block: RwLock<BestBlock>,
1063         secp_ctx: Secp256k1<secp256k1::All>,
1064
1065         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1066         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1067         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1068         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1069         ///
1070         /// See `ChannelManager` struct-level documentation for lock order requirements.
1071         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1072
1073         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1074         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1075         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1076         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1077         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1078         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1079         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1080         /// after reloading from disk while replaying blocks against ChannelMonitors.
1081         ///
1082         /// See `PendingOutboundPayment` documentation for more info.
1083         ///
1084         /// See `ChannelManager` struct-level documentation for lock order requirements.
1085         pending_outbound_payments: OutboundPayments,
1086
1087         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1088         ///
1089         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1090         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1091         /// and via the classic SCID.
1092         ///
1093         /// Note that no consistency guarantees are made about the existence of a channel with the
1094         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1095         ///
1096         /// See `ChannelManager` struct-level documentation for lock order requirements.
1097         #[cfg(test)]
1098         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1099         #[cfg(not(test))]
1100         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1101         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1102         /// until the user tells us what we should do with them.
1103         ///
1104         /// See `ChannelManager` struct-level documentation for lock order requirements.
1105         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1106
1107         /// The sets of payments which are claimable or currently being claimed. See
1108         /// [`ClaimablePayments`]' individual field docs for more info.
1109         ///
1110         /// See `ChannelManager` struct-level documentation for lock order requirements.
1111         claimable_payments: Mutex<ClaimablePayments>,
1112
1113         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1114         /// and some closed channels which reached a usable state prior to being closed. This is used
1115         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1116         /// active channel list on load.
1117         ///
1118         /// See `ChannelManager` struct-level documentation for lock order requirements.
1119         outbound_scid_aliases: Mutex<HashSet<u64>>,
1120
1121         /// `channel_id` -> `counterparty_node_id`.
1122         ///
1123         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1124         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1125         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1126         ///
1127         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1128         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1129         /// the handling of the events.
1130         ///
1131         /// Note that no consistency guarantees are made about the existence of a peer with the
1132         /// `counterparty_node_id` in our other maps.
1133         ///
1134         /// TODO:
1135         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1136         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1137         /// would break backwards compatability.
1138         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1139         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1140         /// required to access the channel with the `counterparty_node_id`.
1141         ///
1142         /// See `ChannelManager` struct-level documentation for lock order requirements.
1143         id_to_peer: Mutex<HashMap<ChannelId, PublicKey>>,
1144
1145         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1146         ///
1147         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1148         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1149         /// confirmation depth.
1150         ///
1151         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1152         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1153         /// channel with the `channel_id` in our other maps.
1154         ///
1155         /// See `ChannelManager` struct-level documentation for lock order requirements.
1156         #[cfg(test)]
1157         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1158         #[cfg(not(test))]
1159         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1160
1161         our_network_pubkey: PublicKey,
1162
1163         inbound_payment_key: inbound_payment::ExpandedKey,
1164
1165         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1166         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1167         /// we encrypt the namespace identifier using these bytes.
1168         ///
1169         /// [fake scids]: crate::util::scid_utils::fake_scid
1170         fake_scid_rand_bytes: [u8; 32],
1171
1172         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1173         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1174         /// keeping additional state.
1175         probing_cookie_secret: [u8; 32],
1176
1177         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1178         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1179         /// very far in the past, and can only ever be up to two hours in the future.
1180         highest_seen_timestamp: AtomicUsize,
1181
1182         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1183         /// basis, as well as the peer's latest features.
1184         ///
1185         /// If we are connected to a peer we always at least have an entry here, even if no channels
1186         /// are currently open with that peer.
1187         ///
1188         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1189         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1190         /// channels.
1191         ///
1192         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1193         ///
1194         /// See `ChannelManager` struct-level documentation for lock order requirements.
1195         #[cfg(not(any(test, feature = "_test_utils")))]
1196         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1197         #[cfg(any(test, feature = "_test_utils"))]
1198         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1199
1200         /// The set of events which we need to give to the user to handle. In some cases an event may
1201         /// require some further action after the user handles it (currently only blocking a monitor
1202         /// update from being handed to the user to ensure the included changes to the channel state
1203         /// are handled by the user before they're persisted durably to disk). In that case, the second
1204         /// element in the tuple is set to `Some` with further details of the action.
1205         ///
1206         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1207         /// could be in the middle of being processed without the direct mutex held.
1208         ///
1209         /// See `ChannelManager` struct-level documentation for lock order requirements.
1210         #[cfg(not(any(test, feature = "_test_utils")))]
1211         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1212         #[cfg(any(test, feature = "_test_utils"))]
1213         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1214
1215         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1216         pending_events_processor: AtomicBool,
1217
1218         /// If we are running during init (either directly during the deserialization method or in
1219         /// block connection methods which run after deserialization but before normal operation) we
1220         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1221         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1222         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1223         ///
1224         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1225         ///
1226         /// See `ChannelManager` struct-level documentation for lock order requirements.
1227         ///
1228         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1229         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1230         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1231         /// Essentially just when we're serializing ourselves out.
1232         /// Taken first everywhere where we are making changes before any other locks.
1233         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1234         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1235         /// Notifier the lock contains sends out a notification when the lock is released.
1236         total_consistency_lock: RwLock<()>,
1237         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1238         /// received and the monitor has been persisted.
1239         ///
1240         /// This information does not need to be persisted as funding nodes can forget
1241         /// unfunded channels upon disconnection.
1242         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1243
1244         background_events_processed_since_startup: AtomicBool,
1245
1246         event_persist_notifier: Notifier,
1247         needs_persist_flag: AtomicBool,
1248
1249         entropy_source: ES,
1250         node_signer: NS,
1251         signer_provider: SP,
1252
1253         logger: L,
1254 }
1255
1256 /// Chain-related parameters used to construct a new `ChannelManager`.
1257 ///
1258 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1259 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1260 /// are not needed when deserializing a previously constructed `ChannelManager`.
1261 #[derive(Clone, Copy, PartialEq)]
1262 pub struct ChainParameters {
1263         /// The network for determining the `chain_hash` in Lightning messages.
1264         pub network: Network,
1265
1266         /// The hash and height of the latest block successfully connected.
1267         ///
1268         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1269         pub best_block: BestBlock,
1270 }
1271
1272 #[derive(Copy, Clone, PartialEq)]
1273 #[must_use]
1274 enum NotifyOption {
1275         DoPersist,
1276         SkipPersistHandleEvents,
1277         SkipPersistNoEvents,
1278 }
1279
1280 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1281 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1282 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1283 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1284 /// sending the aforementioned notification (since the lock being released indicates that the
1285 /// updates are ready for persistence).
1286 ///
1287 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1288 /// notify or not based on whether relevant changes have been made, providing a closure to
1289 /// `optionally_notify` which returns a `NotifyOption`.
1290 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1291         event_persist_notifier: &'a Notifier,
1292         needs_persist_flag: &'a AtomicBool,
1293         should_persist: F,
1294         // We hold onto this result so the lock doesn't get released immediately.
1295         _read_guard: RwLockReadGuard<'a, ()>,
1296 }
1297
1298 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1299         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1300         /// events to handle.
1301         ///
1302         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1303         /// other cases where losing the changes on restart may result in a force-close or otherwise
1304         /// isn't ideal.
1305         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1306                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1307         }
1308
1309         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1310         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1311                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1312                 let force_notify = cm.get_cm().process_background_events();
1313
1314                 PersistenceNotifierGuard {
1315                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1316                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1317                         should_persist: move || {
1318                                 // Pick the "most" action between `persist_check` and the background events
1319                                 // processing and return that.
1320                                 let notify = persist_check();
1321                                 match (notify, force_notify) {
1322                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1323                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1324                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1325                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1326                                         _ => NotifyOption::SkipPersistNoEvents,
1327                                 }
1328                         },
1329                         _read_guard: read_guard,
1330                 }
1331         }
1332
1333         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1334         /// [`ChannelManager::process_background_events`] MUST be called first (or
1335         /// [`Self::optionally_notify`] used).
1336         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1337         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1338                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1339
1340                 PersistenceNotifierGuard {
1341                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1342                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1343                         should_persist: persist_check,
1344                         _read_guard: read_guard,
1345                 }
1346         }
1347 }
1348
1349 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1350         fn drop(&mut self) {
1351                 match (self.should_persist)() {
1352                         NotifyOption::DoPersist => {
1353                                 self.needs_persist_flag.store(true, Ordering::Release);
1354                                 self.event_persist_notifier.notify()
1355                         },
1356                         NotifyOption::SkipPersistHandleEvents =>
1357                                 self.event_persist_notifier.notify(),
1358                         NotifyOption::SkipPersistNoEvents => {},
1359                 }
1360         }
1361 }
1362
1363 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1364 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1365 ///
1366 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1367 ///
1368 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1369 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1370 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1371 /// the maximum required amount in lnd as of March 2021.
1372 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1373
1374 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1375 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1376 ///
1377 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1378 ///
1379 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1380 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1381 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1382 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1383 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1384 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1385 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1386 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1387 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1388 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1389 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1390 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1391 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1392
1393 /// Minimum CLTV difference between the current block height and received inbound payments.
1394 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1395 /// this value.
1396 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1397 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1398 // a payment was being routed, so we add an extra block to be safe.
1399 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1400
1401 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1402 // ie that if the next-hop peer fails the HTLC within
1403 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1404 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1405 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1406 // LATENCY_GRACE_PERIOD_BLOCKS.
1407 #[deny(const_err)]
1408 #[allow(dead_code)]
1409 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;
1410
1411 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1412 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1413 #[deny(const_err)]
1414 #[allow(dead_code)]
1415 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1416
1417 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1418 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1419
1420 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1421 /// until we mark the channel disabled and gossip the update.
1422 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1423
1424 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1425 /// we mark the channel enabled and gossip the update.
1426 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1427
1428 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1429 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1430 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1431 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1432
1433 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1434 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1435 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1436
1437 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1438 /// many peers we reject new (inbound) connections.
1439 const MAX_NO_CHANNEL_PEERS: usize = 250;
1440
1441 /// Information needed for constructing an invoice route hint for this channel.
1442 #[derive(Clone, Debug, PartialEq)]
1443 pub struct CounterpartyForwardingInfo {
1444         /// Base routing fee in millisatoshis.
1445         pub fee_base_msat: u32,
1446         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1447         pub fee_proportional_millionths: u32,
1448         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1449         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1450         /// `cltv_expiry_delta` for more details.
1451         pub cltv_expiry_delta: u16,
1452 }
1453
1454 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1455 /// to better separate parameters.
1456 #[derive(Clone, Debug, PartialEq)]
1457 pub struct ChannelCounterparty {
1458         /// The node_id of our counterparty
1459         pub node_id: PublicKey,
1460         /// The Features the channel counterparty provided upon last connection.
1461         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1462         /// many routing-relevant features are present in the init context.
1463         pub features: InitFeatures,
1464         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1465         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1466         /// claiming at least this value on chain.
1467         ///
1468         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1469         ///
1470         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1471         pub unspendable_punishment_reserve: u64,
1472         /// Information on the fees and requirements that the counterparty requires when forwarding
1473         /// payments to us through this channel.
1474         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1475         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1476         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1477         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1478         pub outbound_htlc_minimum_msat: Option<u64>,
1479         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1480         pub outbound_htlc_maximum_msat: Option<u64>,
1481 }
1482
1483 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1484 #[derive(Clone, Debug, PartialEq)]
1485 pub struct ChannelDetails {
1486         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1487         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1488         /// Note that this means this value is *not* persistent - it can change once during the
1489         /// lifetime of the channel.
1490         pub channel_id: ChannelId,
1491         /// Parameters which apply to our counterparty. See individual fields for more information.
1492         pub counterparty: ChannelCounterparty,
1493         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1494         /// our counterparty already.
1495         ///
1496         /// Note that, if this has been set, `channel_id` will be equivalent to
1497         /// `funding_txo.unwrap().to_channel_id()`.
1498         pub funding_txo: Option<OutPoint>,
1499         /// The features which this channel operates with. See individual features for more info.
1500         ///
1501         /// `None` until negotiation completes and the channel type is finalized.
1502         pub channel_type: Option<ChannelTypeFeatures>,
1503         /// The position of the funding transaction in the chain. None if the funding transaction has
1504         /// not yet been confirmed and the channel fully opened.
1505         ///
1506         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1507         /// payments instead of this. See [`get_inbound_payment_scid`].
1508         ///
1509         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1510         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1511         ///
1512         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1513         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1514         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1515         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1516         /// [`confirmations_required`]: Self::confirmations_required
1517         pub short_channel_id: Option<u64>,
1518         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1519         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1520         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1521         /// `Some(0)`).
1522         ///
1523         /// This will be `None` as long as the channel is not available for routing outbound payments.
1524         ///
1525         /// [`short_channel_id`]: Self::short_channel_id
1526         /// [`confirmations_required`]: Self::confirmations_required
1527         pub outbound_scid_alias: Option<u64>,
1528         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1529         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1530         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1531         /// when they see a payment to be routed to us.
1532         ///
1533         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1534         /// previous values for inbound payment forwarding.
1535         ///
1536         /// [`short_channel_id`]: Self::short_channel_id
1537         pub inbound_scid_alias: Option<u64>,
1538         /// The value, in satoshis, of this channel as appears in the funding output
1539         pub channel_value_satoshis: u64,
1540         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1541         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1542         /// this value on chain.
1543         ///
1544         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1545         ///
1546         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1547         ///
1548         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1549         pub unspendable_punishment_reserve: Option<u64>,
1550         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1551         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1552         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1553         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1554         /// serialized with LDK versions prior to 0.0.113.
1555         ///
1556         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1557         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1558         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1559         pub user_channel_id: u128,
1560         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1561         /// which is applied to commitment and HTLC transactions.
1562         ///
1563         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1564         pub feerate_sat_per_1000_weight: Option<u32>,
1565         /// Our total balance.  This is the amount we would get if we close the channel.
1566         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1567         /// amount is not likely to be recoverable on close.
1568         ///
1569         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1570         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1571         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1572         /// This does not consider any on-chain fees.
1573         ///
1574         /// See also [`ChannelDetails::outbound_capacity_msat`]
1575         pub balance_msat: u64,
1576         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1577         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1578         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1579         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1580         ///
1581         /// See also [`ChannelDetails::balance_msat`]
1582         ///
1583         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1584         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1585         /// should be able to spend nearly this amount.
1586         pub outbound_capacity_msat: u64,
1587         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1588         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1589         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1590         /// to use a limit as close as possible to the HTLC limit we can currently send.
1591         ///
1592         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1593         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1594         pub next_outbound_htlc_limit_msat: u64,
1595         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1596         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1597         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1598         /// route which is valid.
1599         pub next_outbound_htlc_minimum_msat: u64,
1600         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1601         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1602         /// available for inclusion in new inbound HTLCs).
1603         /// Note that there are some corner cases not fully handled here, so the actual available
1604         /// inbound capacity may be slightly higher than this.
1605         ///
1606         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1607         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1608         /// However, our counterparty should be able to spend nearly this amount.
1609         pub inbound_capacity_msat: u64,
1610         /// The number of required confirmations on the funding transaction before the funding will be
1611         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1612         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1613         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1614         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1615         ///
1616         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1617         ///
1618         /// [`is_outbound`]: ChannelDetails::is_outbound
1619         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1620         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1621         pub confirmations_required: Option<u32>,
1622         /// The current number of confirmations on the funding transaction.
1623         ///
1624         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1625         pub confirmations: Option<u32>,
1626         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1627         /// until we can claim our funds after we force-close the channel. During this time our
1628         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1629         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1630         /// time to claim our non-HTLC-encumbered funds.
1631         ///
1632         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1633         pub force_close_spend_delay: Option<u16>,
1634         /// True if the channel was initiated (and thus funded) by us.
1635         pub is_outbound: bool,
1636         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1637         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1638         /// required confirmation count has been reached (and we were connected to the peer at some
1639         /// point after the funding transaction received enough confirmations). The required
1640         /// confirmation count is provided in [`confirmations_required`].
1641         ///
1642         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1643         pub is_channel_ready: bool,
1644         /// The stage of the channel's shutdown.
1645         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1646         pub channel_shutdown_state: Option<ChannelShutdownState>,
1647         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1648         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1649         ///
1650         /// This is a strict superset of `is_channel_ready`.
1651         pub is_usable: bool,
1652         /// True if this channel is (or will be) publicly-announced.
1653         pub is_public: bool,
1654         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1655         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1656         pub inbound_htlc_minimum_msat: Option<u64>,
1657         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1658         pub inbound_htlc_maximum_msat: Option<u64>,
1659         /// Set of configurable parameters that affect channel operation.
1660         ///
1661         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1662         pub config: Option<ChannelConfig>,
1663 }
1664
1665 impl ChannelDetails {
1666         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1667         /// This should be used for providing invoice hints or in any other context where our
1668         /// counterparty will forward a payment to us.
1669         ///
1670         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1671         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1672         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1673                 self.inbound_scid_alias.or(self.short_channel_id)
1674         }
1675
1676         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1677         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1678         /// we're sending or forwarding a payment outbound over this channel.
1679         ///
1680         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1681         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1682         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1683                 self.short_channel_id.or(self.outbound_scid_alias)
1684         }
1685
1686         fn from_channel_context<SP: Deref, F: Deref>(
1687                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1688                 fee_estimator: &LowerBoundedFeeEstimator<F>
1689         ) -> Self
1690         where
1691                 SP::Target: SignerProvider,
1692                 F::Target: FeeEstimator
1693         {
1694                 let balance = context.get_available_balances(fee_estimator);
1695                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1696                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1697                 ChannelDetails {
1698                         channel_id: context.channel_id(),
1699                         counterparty: ChannelCounterparty {
1700                                 node_id: context.get_counterparty_node_id(),
1701                                 features: latest_features,
1702                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1703                                 forwarding_info: context.counterparty_forwarding_info(),
1704                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1705                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1706                                 // message (as they are always the first message from the counterparty).
1707                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1708                                 // default `0` value set by `Channel::new_outbound`.
1709                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1710                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1711                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1712                         },
1713                         funding_txo: context.get_funding_txo(),
1714                         // Note that accept_channel (or open_channel) is always the first message, so
1715                         // `have_received_message` indicates that type negotiation has completed.
1716                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1717                         short_channel_id: context.get_short_channel_id(),
1718                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1719                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1720                         channel_value_satoshis: context.get_value_satoshis(),
1721                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1722                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1723                         balance_msat: balance.balance_msat,
1724                         inbound_capacity_msat: balance.inbound_capacity_msat,
1725                         outbound_capacity_msat: balance.outbound_capacity_msat,
1726                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1727                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1728                         user_channel_id: context.get_user_id(),
1729                         confirmations_required: context.minimum_depth(),
1730                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1731                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1732                         is_outbound: context.is_outbound(),
1733                         is_channel_ready: context.is_usable(),
1734                         is_usable: context.is_live(),
1735                         is_public: context.should_announce(),
1736                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1737                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1738                         config: Some(context.config()),
1739                         channel_shutdown_state: Some(context.shutdown_state()),
1740                 }
1741         }
1742 }
1743
1744 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1745 /// Further information on the details of the channel shutdown.
1746 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1747 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1748 /// the channel will be removed shortly.
1749 /// Also note, that in normal operation, peers could disconnect at any of these states
1750 /// and require peer re-connection before making progress onto other states
1751 pub enum ChannelShutdownState {
1752         /// Channel has not sent or received a shutdown message.
1753         NotShuttingDown,
1754         /// Local node has sent a shutdown message for this channel.
1755         ShutdownInitiated,
1756         /// Shutdown message exchanges have concluded and the channels are in the midst of
1757         /// resolving all existing open HTLCs before closing can continue.
1758         ResolvingHTLCs,
1759         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1760         NegotiatingClosingFee,
1761         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1762         /// to drop the channel.
1763         ShutdownComplete,
1764 }
1765
1766 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1767 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1768 #[derive(Debug, PartialEq)]
1769 pub enum RecentPaymentDetails {
1770         /// When an invoice was requested and thus a payment has not yet been sent.
1771         AwaitingInvoice {
1772                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1773                 /// a payment and ensure idempotency in LDK.
1774                 payment_id: PaymentId,
1775         },
1776         /// When a payment is still being sent and awaiting successful delivery.
1777         Pending {
1778                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1779                 /// a payment and ensure idempotency in LDK.
1780                 payment_id: PaymentId,
1781                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1782                 /// abandoned.
1783                 payment_hash: PaymentHash,
1784                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1785                 /// not just the amount currently inflight.
1786                 total_msat: u64,
1787         },
1788         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1789         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1790         /// payment is removed from tracking.
1791         Fulfilled {
1792                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1793                 /// a payment and ensure idempotency in LDK.
1794                 payment_id: PaymentId,
1795                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1796                 /// made before LDK version 0.0.104.
1797                 payment_hash: Option<PaymentHash>,
1798         },
1799         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1800         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1801         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1802         Abandoned {
1803                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1804                 /// a payment and ensure idempotency in LDK.
1805                 payment_id: PaymentId,
1806                 /// Hash of the payment that we have given up trying to send.
1807                 payment_hash: PaymentHash,
1808         },
1809 }
1810
1811 /// Route hints used in constructing invoices for [phantom node payents].
1812 ///
1813 /// [phantom node payments]: crate::sign::PhantomKeysManager
1814 #[derive(Clone)]
1815 pub struct PhantomRouteHints {
1816         /// The list of channels to be included in the invoice route hints.
1817         pub channels: Vec<ChannelDetails>,
1818         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1819         /// route hints.
1820         pub phantom_scid: u64,
1821         /// The pubkey of the real backing node that would ultimately receive the payment.
1822         pub real_node_pubkey: PublicKey,
1823 }
1824
1825 macro_rules! handle_error {
1826         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1827                 // In testing, ensure there are no deadlocks where the lock is already held upon
1828                 // entering the macro.
1829                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1830                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1831
1832                 match $internal {
1833                         Ok(msg) => Ok(msg),
1834                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1835                                 let mut msg_events = Vec::with_capacity(2);
1836
1837                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1838                                         $self.finish_close_channel(shutdown_res);
1839                                         if let Some(update) = update_option {
1840                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1841                                                         msg: update
1842                                                 });
1843                                         }
1844                                         if let Some((channel_id, user_channel_id)) = chan_id {
1845                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1846                                                         channel_id, user_channel_id,
1847                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1848                                                         counterparty_node_id: Some($counterparty_node_id),
1849                                                         channel_capacity_sats: channel_capacity,
1850                                                 }, None));
1851                                         }
1852                                 }
1853
1854                                 log_error!($self.logger, "{}", err.err);
1855                                 if let msgs::ErrorAction::IgnoreError = err.action {
1856                                 } else {
1857                                         msg_events.push(events::MessageSendEvent::HandleError {
1858                                                 node_id: $counterparty_node_id,
1859                                                 action: err.action.clone()
1860                                         });
1861                                 }
1862
1863                                 if !msg_events.is_empty() {
1864                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1865                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1866                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1867                                                 peer_state.pending_msg_events.append(&mut msg_events);
1868                                         }
1869                                 }
1870
1871                                 // Return error in case higher-API need one
1872                                 Err(err)
1873                         },
1874                 }
1875         } };
1876         ($self: ident, $internal: expr) => {
1877                 match $internal {
1878                         Ok(res) => Ok(res),
1879                         Err((chan, msg_handle_err)) => {
1880                                 let counterparty_node_id = chan.get_counterparty_node_id();
1881                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1882                         },
1883                 }
1884         };
1885 }
1886
1887 macro_rules! update_maps_on_chan_removal {
1888         ($self: expr, $channel_context: expr) => {{
1889                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1890                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1891                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1892                         short_to_chan_info.remove(&short_id);
1893                 } else {
1894                         // If the channel was never confirmed on-chain prior to its closure, remove the
1895                         // outbound SCID alias we used for it from the collision-prevention set. While we
1896                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1897                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1898                         // opening a million channels with us which are closed before we ever reach the funding
1899                         // stage.
1900                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1901                         debug_assert!(alias_removed);
1902                 }
1903                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1904         }}
1905 }
1906
1907 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1908 macro_rules! convert_chan_phase_err {
1909         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
1910                 match $err {
1911                         ChannelError::Warn(msg) => {
1912                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
1913                         },
1914                         ChannelError::Ignore(msg) => {
1915                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
1916                         },
1917                         ChannelError::Close(msg) => {
1918                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
1919                                 update_maps_on_chan_removal!($self, $channel.context);
1920                                 let shutdown_res = $channel.context.force_shutdown(true);
1921                                 let user_id = $channel.context.get_user_id();
1922                                 let channel_capacity_satoshis = $channel.context.get_value_satoshis();
1923
1924                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, user_id,
1925                                         shutdown_res, $channel_update, channel_capacity_satoshis))
1926                         },
1927                 }
1928         };
1929         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
1930                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
1931         };
1932         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
1933                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
1934         };
1935         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
1936                 match $channel_phase {
1937                         ChannelPhase::Funded(channel) => {
1938                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
1939                         },
1940                         ChannelPhase::UnfundedOutboundV1(channel) => {
1941                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1942                         },
1943                         ChannelPhase::UnfundedInboundV1(channel) => {
1944                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1945                         },
1946                 }
1947         };
1948 }
1949
1950 macro_rules! break_chan_phase_entry {
1951         ($self: ident, $res: expr, $entry: expr) => {
1952                 match $res {
1953                         Ok(res) => res,
1954                         Err(e) => {
1955                                 let key = *$entry.key();
1956                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1957                                 if drop {
1958                                         $entry.remove_entry();
1959                                 }
1960                                 break Err(res);
1961                         }
1962                 }
1963         }
1964 }
1965
1966 macro_rules! try_chan_phase_entry {
1967         ($self: ident, $res: expr, $entry: expr) => {
1968                 match $res {
1969                         Ok(res) => res,
1970                         Err(e) => {
1971                                 let key = *$entry.key();
1972                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1973                                 if drop {
1974                                         $entry.remove_entry();
1975                                 }
1976                                 return Err(res);
1977                         }
1978                 }
1979         }
1980 }
1981
1982 macro_rules! remove_channel_phase {
1983         ($self: expr, $entry: expr) => {
1984                 {
1985                         let channel = $entry.remove_entry().1;
1986                         update_maps_on_chan_removal!($self, &channel.context());
1987                         channel
1988                 }
1989         }
1990 }
1991
1992 macro_rules! send_channel_ready {
1993         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1994                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1995                         node_id: $channel.context.get_counterparty_node_id(),
1996                         msg: $channel_ready_msg,
1997                 });
1998                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1999                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2000                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2001                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2002                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2003                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2004                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2005                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2006                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2007                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2008                 }
2009         }}
2010 }
2011
2012 macro_rules! emit_channel_pending_event {
2013         ($locked_events: expr, $channel: expr) => {
2014                 if $channel.context.should_emit_channel_pending_event() {
2015                         $locked_events.push_back((events::Event::ChannelPending {
2016                                 channel_id: $channel.context.channel_id(),
2017                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2018                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2019                                 user_channel_id: $channel.context.get_user_id(),
2020                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2021                         }, None));
2022                         $channel.context.set_channel_pending_event_emitted();
2023                 }
2024         }
2025 }
2026
2027 macro_rules! emit_channel_ready_event {
2028         ($locked_events: expr, $channel: expr) => {
2029                 if $channel.context.should_emit_channel_ready_event() {
2030                         debug_assert!($channel.context.channel_pending_event_emitted());
2031                         $locked_events.push_back((events::Event::ChannelReady {
2032                                 channel_id: $channel.context.channel_id(),
2033                                 user_channel_id: $channel.context.get_user_id(),
2034                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2035                                 channel_type: $channel.context.get_channel_type().clone(),
2036                         }, None));
2037                         $channel.context.set_channel_ready_event_emitted();
2038                 }
2039         }
2040 }
2041
2042 macro_rules! handle_monitor_update_completion {
2043         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2044                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
2045                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2046                         $self.best_block.read().unwrap().height());
2047                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2048                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2049                         // We only send a channel_update in the case where we are just now sending a
2050                         // channel_ready and the channel is in a usable state. We may re-send a
2051                         // channel_update later through the announcement_signatures process for public
2052                         // channels, but there's no reason not to just inform our counterparty of our fees
2053                         // now.
2054                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2055                                 Some(events::MessageSendEvent::SendChannelUpdate {
2056                                         node_id: counterparty_node_id,
2057                                         msg,
2058                                 })
2059                         } else { None }
2060                 } else { None };
2061
2062                 let update_actions = $peer_state.monitor_update_blocked_actions
2063                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2064
2065                 let htlc_forwards = $self.handle_channel_resumption(
2066                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2067                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2068                         updates.funding_broadcastable, updates.channel_ready,
2069                         updates.announcement_sigs);
2070                 if let Some(upd) = channel_update {
2071                         $peer_state.pending_msg_events.push(upd);
2072                 }
2073
2074                 let channel_id = $chan.context.channel_id();
2075                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2076                 core::mem::drop($peer_state_lock);
2077                 core::mem::drop($per_peer_state_lock);
2078
2079                 // If the channel belongs to a batch funding transaction, the progress of the batch
2080                 // should be updated as we have received funding_signed and persisted the monitor.
2081                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2082                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2083                         let mut batch_completed = false;
2084                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2085                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2086                                         *chan_id == channel_id &&
2087                                         *pubkey == counterparty_node_id
2088                                 ));
2089                                 if let Some(channel_state) = channel_state {
2090                                         channel_state.2 = true;
2091                                 } else {
2092                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2093                                 }
2094                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2095                         } else {
2096                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2097                         }
2098
2099                         // When all channels in a batched funding transaction have become ready, it is not necessary
2100                         // to track the progress of the batch anymore and the state of the channels can be updated.
2101                         if batch_completed {
2102                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2103                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2104                                 let mut batch_funding_tx = None;
2105                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2106                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2107                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2108                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2109                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2110                                                         chan.set_batch_ready();
2111                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2112                                                         emit_channel_pending_event!(pending_events, chan);
2113                                                 }
2114                                         }
2115                                 }
2116                                 if let Some(tx) = batch_funding_tx {
2117                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2118                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2119                                 }
2120                         }
2121                 }
2122
2123                 $self.handle_monitor_update_completion_actions(update_actions);
2124
2125                 if let Some(forwards) = htlc_forwards {
2126                         $self.forward_htlcs(&mut [forwards][..]);
2127                 }
2128                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2129                 for failure in updates.failed_htlcs.drain(..) {
2130                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2131                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2132                 }
2133         } }
2134 }
2135
2136 macro_rules! handle_new_monitor_update {
2137         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2138                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2139                 match $update_res {
2140                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2141                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2142                                 log_error!($self.logger, "{}", err_str);
2143                                 panic!("{}", err_str);
2144                         },
2145                         ChannelMonitorUpdateStatus::InProgress => {
2146                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2147                                         &$chan.context.channel_id());
2148                                 false
2149                         },
2150                         ChannelMonitorUpdateStatus::Completed => {
2151                                 $completed;
2152                                 true
2153                         },
2154                 }
2155         } };
2156         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2157                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2158                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2159         };
2160         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2161                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2162                         .or_insert_with(Vec::new);
2163                 // During startup, we push monitor updates as background events through to here in
2164                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2165                 // filter for uniqueness here.
2166                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2167                         .unwrap_or_else(|| {
2168                                 in_flight_updates.push($update);
2169                                 in_flight_updates.len() - 1
2170                         });
2171                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2172                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2173                         {
2174                                 let _ = in_flight_updates.remove(idx);
2175                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2176                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2177                                 }
2178                         })
2179         } };
2180 }
2181
2182 macro_rules! process_events_body {
2183         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2184                 let mut processed_all_events = false;
2185                 while !processed_all_events {
2186                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2187                                 return;
2188                         }
2189
2190                         let mut result;
2191
2192                         {
2193                                 // We'll acquire our total consistency lock so that we can be sure no other
2194                                 // persists happen while processing monitor events.
2195                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2196
2197                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2198                                 // ensure any startup-generated background events are handled first.
2199                                 result = $self.process_background_events();
2200
2201                                 // TODO: This behavior should be documented. It's unintuitive that we query
2202                                 // ChannelMonitors when clearing other events.
2203                                 if $self.process_pending_monitor_events() {
2204                                         result = NotifyOption::DoPersist;
2205                                 }
2206                         }
2207
2208                         let pending_events = $self.pending_events.lock().unwrap().clone();
2209                         let num_events = pending_events.len();
2210                         if !pending_events.is_empty() {
2211                                 result = NotifyOption::DoPersist;
2212                         }
2213
2214                         let mut post_event_actions = Vec::new();
2215
2216                         for (event, action_opt) in pending_events {
2217                                 $event_to_handle = event;
2218                                 $handle_event;
2219                                 if let Some(action) = action_opt {
2220                                         post_event_actions.push(action);
2221                                 }
2222                         }
2223
2224                         {
2225                                 let mut pending_events = $self.pending_events.lock().unwrap();
2226                                 pending_events.drain(..num_events);
2227                                 processed_all_events = pending_events.is_empty();
2228                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2229                                 // updated here with the `pending_events` lock acquired.
2230                                 $self.pending_events_processor.store(false, Ordering::Release);
2231                         }
2232
2233                         if !post_event_actions.is_empty() {
2234                                 $self.handle_post_event_actions(post_event_actions);
2235                                 // If we had some actions, go around again as we may have more events now
2236                                 processed_all_events = false;
2237                         }
2238
2239                         match result {
2240                                 NotifyOption::DoPersist => {
2241                                         $self.needs_persist_flag.store(true, Ordering::Release);
2242                                         $self.event_persist_notifier.notify();
2243                                 },
2244                                 NotifyOption::SkipPersistHandleEvents =>
2245                                         $self.event_persist_notifier.notify(),
2246                                 NotifyOption::SkipPersistNoEvents => {},
2247                         }
2248                 }
2249         }
2250 }
2251
2252 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>
2253 where
2254         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2255         T::Target: BroadcasterInterface,
2256         ES::Target: EntropySource,
2257         NS::Target: NodeSigner,
2258         SP::Target: SignerProvider,
2259         F::Target: FeeEstimator,
2260         R::Target: Router,
2261         L::Target: Logger,
2262 {
2263         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2264         ///
2265         /// The current time or latest block header time can be provided as the `current_timestamp`.
2266         ///
2267         /// This is the main "logic hub" for all channel-related actions, and implements
2268         /// [`ChannelMessageHandler`].
2269         ///
2270         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2271         ///
2272         /// Users need to notify the new `ChannelManager` when a new block is connected or
2273         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2274         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2275         /// more details.
2276         ///
2277         /// [`block_connected`]: chain::Listen::block_connected
2278         /// [`block_disconnected`]: chain::Listen::block_disconnected
2279         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2280         pub fn new(
2281                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2282                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2283                 current_timestamp: u32,
2284         ) -> Self {
2285                 let mut secp_ctx = Secp256k1::new();
2286                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2287                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2288                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2289                 ChannelManager {
2290                         default_configuration: config.clone(),
2291                         chain_hash: ChainHash::using_genesis_block(params.network),
2292                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2293                         chain_monitor,
2294                         tx_broadcaster,
2295                         router,
2296
2297                         best_block: RwLock::new(params.best_block),
2298
2299                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2300                         pending_inbound_payments: Mutex::new(HashMap::new()),
2301                         pending_outbound_payments: OutboundPayments::new(),
2302                         forward_htlcs: Mutex::new(HashMap::new()),
2303                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2304                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2305                         id_to_peer: Mutex::new(HashMap::new()),
2306                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2307
2308                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2309                         secp_ctx,
2310
2311                         inbound_payment_key: expanded_inbound_key,
2312                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2313
2314                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2315
2316                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2317
2318                         per_peer_state: FairRwLock::new(HashMap::new()),
2319
2320                         pending_events: Mutex::new(VecDeque::new()),
2321                         pending_events_processor: AtomicBool::new(false),
2322                         pending_background_events: Mutex::new(Vec::new()),
2323                         total_consistency_lock: RwLock::new(()),
2324                         background_events_processed_since_startup: AtomicBool::new(false),
2325                         event_persist_notifier: Notifier::new(),
2326                         needs_persist_flag: AtomicBool::new(false),
2327                         funding_batch_states: Mutex::new(BTreeMap::new()),
2328
2329                         entropy_source,
2330                         node_signer,
2331                         signer_provider,
2332
2333                         logger,
2334                 }
2335         }
2336
2337         /// Gets the current configuration applied to all new channels.
2338         pub fn get_current_default_configuration(&self) -> &UserConfig {
2339                 &self.default_configuration
2340         }
2341
2342         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2343                 let height = self.best_block.read().unwrap().height();
2344                 let mut outbound_scid_alias = 0;
2345                 let mut i = 0;
2346                 loop {
2347                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2348                                 outbound_scid_alias += 1;
2349                         } else {
2350                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2351                         }
2352                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2353                                 break;
2354                         }
2355                         i += 1;
2356                         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"); }
2357                 }
2358                 outbound_scid_alias
2359         }
2360
2361         /// Creates a new outbound channel to the given remote node and with the given value.
2362         ///
2363         /// `user_channel_id` will be provided back as in
2364         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2365         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2366         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2367         /// is simply copied to events and otherwise ignored.
2368         ///
2369         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2370         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2371         ///
2372         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2373         /// generate a shutdown scriptpubkey or destination script set by
2374         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2375         ///
2376         /// Note that we do not check if you are currently connected to the given peer. If no
2377         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2378         /// the channel eventually being silently forgotten (dropped on reload).
2379         ///
2380         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2381         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2382         /// [`ChannelDetails::channel_id`] until after
2383         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2384         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2385         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2386         ///
2387         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2388         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2389         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2390         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> {
2391                 if channel_value_satoshis < 1000 {
2392                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2393                 }
2394
2395                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2396                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2397                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2398
2399                 let per_peer_state = self.per_peer_state.read().unwrap();
2400
2401                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2402                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2403
2404                 let mut peer_state = peer_state_mutex.lock().unwrap();
2405                 let channel = {
2406                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2407                         let their_features = &peer_state.latest_features;
2408                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2409                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2410                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2411                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2412                         {
2413                                 Ok(res) => res,
2414                                 Err(e) => {
2415                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2416                                         return Err(e);
2417                                 },
2418                         }
2419                 };
2420                 let res = channel.get_open_channel(self.chain_hash);
2421
2422                 let temporary_channel_id = channel.context.channel_id();
2423                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2424                         hash_map::Entry::Occupied(_) => {
2425                                 if cfg!(fuzzing) {
2426                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2427                                 } else {
2428                                         panic!("RNG is bad???");
2429                                 }
2430                         },
2431                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2432                 }
2433
2434                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2435                         node_id: their_network_key,
2436                         msg: res,
2437                 });
2438                 Ok(temporary_channel_id)
2439         }
2440
2441         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2442                 // Allocate our best estimate of the number of channels we have in the `res`
2443                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2444                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2445                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2446                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2447                 // the same channel.
2448                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2449                 {
2450                         let best_block_height = self.best_block.read().unwrap().height();
2451                         let per_peer_state = self.per_peer_state.read().unwrap();
2452                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2453                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2454                                 let peer_state = &mut *peer_state_lock;
2455                                 res.extend(peer_state.channel_by_id.iter()
2456                                         .filter_map(|(chan_id, phase)| match phase {
2457                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2458                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2459                                                 _ => None,
2460                                         })
2461                                         .filter(f)
2462                                         .map(|(_channel_id, channel)| {
2463                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2464                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2465                                         })
2466                                 );
2467                         }
2468                 }
2469                 res
2470         }
2471
2472         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2473         /// more information.
2474         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2475                 // Allocate our best estimate of the number of channels we have in the `res`
2476                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2477                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2478                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2479                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2480                 // the same channel.
2481                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2482                 {
2483                         let best_block_height = self.best_block.read().unwrap().height();
2484                         let per_peer_state = self.per_peer_state.read().unwrap();
2485                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2486                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2487                                 let peer_state = &mut *peer_state_lock;
2488                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2489                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2490                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2491                                         res.push(details);
2492                                 }
2493                         }
2494                 }
2495                 res
2496         }
2497
2498         /// Gets the list of usable channels, in random order. Useful as an argument to
2499         /// [`Router::find_route`] to ensure non-announced channels are used.
2500         ///
2501         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2502         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2503         /// are.
2504         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2505                 // Note we use is_live here instead of usable which leads to somewhat confused
2506                 // internal/external nomenclature, but that's ok cause that's probably what the user
2507                 // really wanted anyway.
2508                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2509         }
2510
2511         /// Gets the list of channels we have with a given counterparty, in random order.
2512         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2513                 let best_block_height = self.best_block.read().unwrap().height();
2514                 let per_peer_state = self.per_peer_state.read().unwrap();
2515
2516                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2517                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2518                         let peer_state = &mut *peer_state_lock;
2519                         let features = &peer_state.latest_features;
2520                         let context_to_details = |context| {
2521                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2522                         };
2523                         return peer_state.channel_by_id
2524                                 .iter()
2525                                 .map(|(_, phase)| phase.context())
2526                                 .map(context_to_details)
2527                                 .collect();
2528                 }
2529                 vec![]
2530         }
2531
2532         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2533         /// successful path, or have unresolved HTLCs.
2534         ///
2535         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2536         /// result of a crash. If such a payment exists, is not listed here, and an
2537         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2538         ///
2539         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2540         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2541                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2542                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2543                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2544                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2545                                 },
2546                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2547                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2548                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2549                                 },
2550                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2551                                         Some(RecentPaymentDetails::Pending {
2552                                                 payment_id: *payment_id,
2553                                                 payment_hash: *payment_hash,
2554                                                 total_msat: *total_msat,
2555                                         })
2556                                 },
2557                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2558                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2559                                 },
2560                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2561                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2562                                 },
2563                                 PendingOutboundPayment::Legacy { .. } => None
2564                         })
2565                         .collect()
2566         }
2567
2568         /// Helper function that issues the channel close events
2569         fn issue_channel_close_events(&self, context: &ChannelContext<SP>, closure_reason: ClosureReason) {
2570                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2571                 match context.unbroadcasted_funding() {
2572                         Some(transaction) => {
2573                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2574                                         channel_id: context.channel_id(), transaction
2575                                 }, None));
2576                         },
2577                         None => {},
2578                 }
2579                 pending_events_lock.push_back((events::Event::ChannelClosed {
2580                         channel_id: context.channel_id(),
2581                         user_channel_id: context.get_user_id(),
2582                         reason: closure_reason,
2583                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2584                         channel_capacity_sats: Some(context.get_value_satoshis()),
2585                 }, None));
2586         }
2587
2588         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> {
2589                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2590
2591                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2592                 let mut shutdown_result = None;
2593                 loop {
2594                         let per_peer_state = self.per_peer_state.read().unwrap();
2595
2596                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2597                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2598
2599                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2600                         let peer_state = &mut *peer_state_lock;
2601
2602                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2603                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2604                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2605                                                 let funding_txo_opt = chan.context.get_funding_txo();
2606                                                 let their_features = &peer_state.latest_features;
2607                                                 let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
2608                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2609                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2610                                                 failed_htlcs = htlcs;
2611
2612                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2613                                                 // here as we don't need the monitor update to complete until we send a
2614                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2615                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2616                                                         node_id: *counterparty_node_id,
2617                                                         msg: shutdown_msg,
2618                                                 });
2619
2620                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2621                                                         "We can't both complete shutdown and generate a monitor update");
2622
2623                                                 // Update the monitor with the shutdown script if necessary.
2624                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2625                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2626                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2627                                                         break;
2628                                                 }
2629
2630                                                 if chan.is_shutdown() {
2631                                                         if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2632                                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2633                                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2634                                                                                 msg: channel_update
2635                                                                         });
2636                                                                 }
2637                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2638                                                                 shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
2639                                                         }
2640                                                 }
2641                                                 break;
2642                                         }
2643                                 },
2644                                 hash_map::Entry::Vacant(_) => {
2645                                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2646                                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2647                                         //
2648                                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2649                                         mem::drop(peer_state_lock);
2650                                         mem::drop(per_peer_state);
2651                                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2652                                 },
2653                         }
2654                 }
2655
2656                 for htlc_source in failed_htlcs.drain(..) {
2657                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2658                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2659                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2660                 }
2661
2662                 if let Some(shutdown_result) = shutdown_result {
2663                         self.finish_close_channel(shutdown_result);
2664                 }
2665
2666                 Ok(())
2667         }
2668
2669         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2670         /// will be accepted on the given channel, and after additional timeout/the closing of all
2671         /// pending HTLCs, the channel will be closed on chain.
2672         ///
2673         ///  * If we are the channel initiator, we will pay between our [`Background`] and
2674         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2675         ///    estimate.
2676         ///  * If our counterparty is the channel initiator, we will require a channel closing
2677         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
2678         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2679         ///    counterparty to pay as much fee as they'd like, however.
2680         ///
2681         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2682         ///
2683         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2684         /// generate a shutdown scriptpubkey or destination script set by
2685         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2686         /// channel.
2687         ///
2688         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2689         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2690         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2691         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2692         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2693                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2694         }
2695
2696         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2697         /// will be accepted on the given channel, and after additional timeout/the closing of all
2698         /// pending HTLCs, the channel will be closed on chain.
2699         ///
2700         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2701         /// the channel being closed or not:
2702         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2703         ///    transaction. The upper-bound is set by
2704         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2705         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2706         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2707         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2708         ///    will appear on a force-closure transaction, whichever is lower).
2709         ///
2710         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2711         /// Will fail if a shutdown script has already been set for this channel by
2712         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2713         /// also be compatible with our and the counterparty's features.
2714         ///
2715         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2716         ///
2717         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2718         /// generate a shutdown scriptpubkey or destination script set by
2719         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2720         /// channel.
2721         ///
2722         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2723         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2724         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2725         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2726         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> {
2727                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2728         }
2729
2730         fn finish_close_channel(&self, shutdown_res: ShutdownResult) {
2731                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2732                 #[cfg(debug_assertions)]
2733                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2734                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2735                 }
2736
2737                 let (monitor_update_option, mut failed_htlcs, unbroadcasted_batch_funding_txid) = shutdown_res;
2738                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
2739                 for htlc_source in failed_htlcs.drain(..) {
2740                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2741                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2742                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2743                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2744                 }
2745                 if let Some((_, funding_txo, monitor_update)) = monitor_update_option {
2746                         // There isn't anything we can do if we get an update failure - we're already
2747                         // force-closing. The monitor update on the required in-memory copy should broadcast
2748                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2749                         // ignore the result here.
2750                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2751                 }
2752                 let mut shutdown_results = Vec::new();
2753                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2754                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2755                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2756                         let per_peer_state = self.per_peer_state.read().unwrap();
2757                         let mut has_uncompleted_channel = None;
2758                         for (channel_id, counterparty_node_id, state) in affected_channels {
2759                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2760                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2761                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2762                                                 update_maps_on_chan_removal!(self, &chan.context());
2763                                                 self.issue_channel_close_events(&chan.context(), ClosureReason::FundingBatchClosure);
2764                                                 shutdown_results.push(chan.context_mut().force_shutdown(false));
2765                                         }
2766                                 }
2767                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2768                         }
2769                         debug_assert!(
2770                                 has_uncompleted_channel.unwrap_or(true),
2771                                 "Closing a batch where all channels have completed initial monitor update",
2772                         );
2773                 }
2774                 for shutdown_result in shutdown_results.drain(..) {
2775                         self.finish_close_channel(shutdown_result);
2776                 }
2777         }
2778
2779         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2780         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2781         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2782         -> Result<PublicKey, APIError> {
2783                 let per_peer_state = self.per_peer_state.read().unwrap();
2784                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2785                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2786                 let (update_opt, counterparty_node_id) = {
2787                         let mut peer_state = peer_state_mutex.lock().unwrap();
2788                         let closure_reason = if let Some(peer_msg) = peer_msg {
2789                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2790                         } else {
2791                                 ClosureReason::HolderForceClosed
2792                         };
2793                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2794                                 log_error!(self.logger, "Force-closing channel {}", channel_id);
2795                                 self.issue_channel_close_events(&chan_phase_entry.get().context(), closure_reason);
2796                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2797                                 mem::drop(peer_state);
2798                                 mem::drop(per_peer_state);
2799                                 match chan_phase {
2800                                         ChannelPhase::Funded(mut chan) => {
2801                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast));
2802                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2803                                         },
2804                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2805                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false));
2806                                                 // Unfunded channel has no update
2807                                                 (None, chan_phase.context().get_counterparty_node_id())
2808                                         },
2809                                 }
2810                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2811                                 log_error!(self.logger, "Force-closing channel {}", &channel_id);
2812                                 // N.B. that we don't send any channel close event here: we
2813                                 // don't have a user_channel_id, and we never sent any opening
2814                                 // events anyway.
2815                                 (None, *peer_node_id)
2816                         } else {
2817                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2818                         }
2819                 };
2820                 if let Some(update) = update_opt {
2821                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2822                         // not try to broadcast it via whatever peer we have.
2823                         let per_peer_state = self.per_peer_state.read().unwrap();
2824                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2825                                 .ok_or(per_peer_state.values().next());
2826                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2827                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2828                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2829                                         msg: update
2830                                 });
2831                         }
2832                 }
2833
2834                 Ok(counterparty_node_id)
2835         }
2836
2837         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2838                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2839                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2840                         Ok(counterparty_node_id) => {
2841                                 let per_peer_state = self.per_peer_state.read().unwrap();
2842                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2843                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2844                                         peer_state.pending_msg_events.push(
2845                                                 events::MessageSendEvent::HandleError {
2846                                                         node_id: counterparty_node_id,
2847                                                         action: msgs::ErrorAction::DisconnectPeer {
2848                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2849                                                         },
2850                                                 }
2851                                         );
2852                                 }
2853                                 Ok(())
2854                         },
2855                         Err(e) => Err(e)
2856                 }
2857         }
2858
2859         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2860         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2861         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2862         /// channel.
2863         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2864         -> Result<(), APIError> {
2865                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2866         }
2867
2868         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2869         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2870         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2871         ///
2872         /// You can always get the latest local transaction(s) to broadcast from
2873         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2874         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2875         -> Result<(), APIError> {
2876                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2877         }
2878
2879         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2880         /// for each to the chain and rejecting new HTLCs on each.
2881         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2882                 for chan in self.list_channels() {
2883                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2884                 }
2885         }
2886
2887         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2888         /// local transaction(s).
2889         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2890                 for chan in self.list_channels() {
2891                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2892                 }
2893         }
2894
2895         fn construct_fwd_pending_htlc_info(
2896                 &self, msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
2897                 new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
2898                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
2899         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2900                 debug_assert!(next_packet_pubkey_opt.is_some());
2901                 let outgoing_packet = msgs::OnionPacket {
2902                         version: 0,
2903                         public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
2904                         hop_data: new_packet_bytes,
2905                         hmac: hop_hmac,
2906                 };
2907
2908                 let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
2909                         msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
2910                                 (short_channel_id, amt_to_forward, outgoing_cltv_value),
2911                         msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
2912                                 return Err(InboundOnionErr {
2913                                         msg: "Final Node OnionHopData provided for us as an intermediary node",
2914                                         err_code: 0x4000 | 22,
2915                                         err_data: Vec::new(),
2916                                 }),
2917                 };
2918
2919                 Ok(PendingHTLCInfo {
2920                         routing: PendingHTLCRouting::Forward {
2921                                 onion_packet: outgoing_packet,
2922                                 short_channel_id,
2923                         },
2924                         payment_hash: msg.payment_hash,
2925                         incoming_shared_secret: shared_secret,
2926                         incoming_amt_msat: Some(msg.amount_msat),
2927                         outgoing_amt_msat: amt_to_forward,
2928                         outgoing_cltv_value,
2929                         skimmed_fee_msat: None,
2930                 })
2931         }
2932
2933         fn construct_recv_pending_htlc_info(
2934                 &self, hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
2935                 amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
2936                 counterparty_skimmed_fee_msat: Option<u64>,
2937         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2938                 let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
2939                         msgs::InboundOnionPayload::Receive {
2940                                 payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
2941                         } =>
2942                                 (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
2943                         msgs::InboundOnionPayload::BlindedReceive {
2944                                 amt_msat, total_msat, outgoing_cltv_value, payment_secret, ..
2945                         } => {
2946                                 let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
2947                                 (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
2948                         }
2949                         msgs::InboundOnionPayload::Forward { .. } => {
2950                                 return Err(InboundOnionErr {
2951                                         err_code: 0x4000|22,
2952                                         err_data: Vec::new(),
2953                                         msg: "Got non final data with an HMAC of 0",
2954                                 })
2955                         },
2956                 };
2957                 // final_incorrect_cltv_expiry
2958                 if outgoing_cltv_value > cltv_expiry {
2959                         return Err(InboundOnionErr {
2960                                 msg: "Upstream node set CLTV to less than the CLTV set by the sender",
2961                                 err_code: 18,
2962                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2963                         })
2964                 }
2965                 // final_expiry_too_soon
2966                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2967                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2968                 //
2969                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2970                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2971                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2972                 let current_height: u32 = self.best_block.read().unwrap().height();
2973                 if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
2974                         let mut err_data = Vec::with_capacity(12);
2975                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2976                         err_data.extend_from_slice(&current_height.to_be_bytes());
2977                         return Err(InboundOnionErr {
2978                                 err_code: 0x4000 | 15, err_data,
2979                                 msg: "The final CLTV expiry is too soon to handle",
2980                         });
2981                 }
2982                 if (!allow_underpay && onion_amt_msat > amt_msat) ||
2983                         (allow_underpay && onion_amt_msat >
2984                          amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
2985                 {
2986                         return Err(InboundOnionErr {
2987                                 err_code: 19,
2988                                 err_data: amt_msat.to_be_bytes().to_vec(),
2989                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2990                         });
2991                 }
2992
2993                 let routing = if let Some(payment_preimage) = keysend_preimage {
2994                         // We need to check that the sender knows the keysend preimage before processing this
2995                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
2996                         // could discover the final destination of X, by probing the adjacent nodes on the route
2997                         // with a keysend payment of identical payment hash to X and observing the processing
2998                         // time discrepancies due to a hash collision with X.
2999                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
3000                         if hashed_preimage != payment_hash {
3001                                 return Err(InboundOnionErr {
3002                                         err_code: 0x4000|22,
3003                                         err_data: Vec::new(),
3004                                         msg: "Payment preimage didn't match payment hash",
3005                                 });
3006                         }
3007                         if !self.default_configuration.accept_mpp_keysend && payment_data.is_some() {
3008                                 return Err(InboundOnionErr {
3009                                         err_code: 0x4000|22,
3010                                         err_data: Vec::new(),
3011                                         msg: "We don't support MPP keysend payments",
3012                                 });
3013                         }
3014                         PendingHTLCRouting::ReceiveKeysend {
3015                                 payment_data,
3016                                 payment_preimage,
3017                                 payment_metadata,
3018                                 incoming_cltv_expiry: outgoing_cltv_value,
3019                                 custom_tlvs,
3020                         }
3021                 } else if let Some(data) = payment_data {
3022                         PendingHTLCRouting::Receive {
3023                                 payment_data: data,
3024                                 payment_metadata,
3025                                 incoming_cltv_expiry: outgoing_cltv_value,
3026                                 phantom_shared_secret,
3027                                 custom_tlvs,
3028                         }
3029                 } else {
3030                         return Err(InboundOnionErr {
3031                                 err_code: 0x4000|0x2000|3,
3032                                 err_data: Vec::new(),
3033                                 msg: "We require payment_secrets",
3034                         });
3035                 };
3036                 Ok(PendingHTLCInfo {
3037                         routing,
3038                         payment_hash,
3039                         incoming_shared_secret: shared_secret,
3040                         incoming_amt_msat: Some(amt_msat),
3041                         outgoing_amt_msat: onion_amt_msat,
3042                         outgoing_cltv_value,
3043                         skimmed_fee_msat: counterparty_skimmed_fee_msat,
3044                 })
3045         }
3046
3047         fn decode_update_add_htlc_onion(
3048                 &self, msg: &msgs::UpdateAddHTLC
3049         ) -> Result<(onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg> {
3050                 macro_rules! return_malformed_err {
3051                         ($msg: expr, $err_code: expr) => {
3052                                 {
3053                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3054                                         return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3055                                                 channel_id: msg.channel_id,
3056                                                 htlc_id: msg.htlc_id,
3057                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
3058                                                 failure_code: $err_code,
3059                                         }));
3060                                 }
3061                         }
3062                 }
3063
3064                 if let Err(_) = msg.onion_routing_packet.public_key {
3065                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
3066                 }
3067
3068                 let shared_secret = self.node_signer.ecdh(
3069                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
3070                 ).unwrap().secret_bytes();
3071
3072                 if msg.onion_routing_packet.version != 0 {
3073                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
3074                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
3075                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
3076                         //receiving node would have to brute force to figure out which version was put in the
3077                         //packet by the node that send us the message, in the case of hashing the hop_data, the
3078                         //node knows the HMAC matched, so they already know what is there...
3079                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
3080                 }
3081                 macro_rules! return_err {
3082                         ($msg: expr, $err_code: expr, $data: expr) => {
3083                                 {
3084                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3085                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3086                                                 channel_id: msg.channel_id,
3087                                                 htlc_id: msg.htlc_id,
3088                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3089                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3090                                         }));
3091                                 }
3092                         }
3093                 }
3094
3095                 let next_hop = match onion_utils::decode_next_payment_hop(
3096                         shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
3097                         msg.payment_hash, &self.node_signer
3098                 ) {
3099                         Ok(res) => res,
3100                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3101                                 return_malformed_err!(err_msg, err_code);
3102                         },
3103                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3104                                 return_err!(err_msg, err_code, &[0; 0]);
3105                         },
3106                 };
3107                 let (outgoing_scid, outgoing_amt_msat, outgoing_cltv_value, next_packet_pk_opt) = match next_hop {
3108                         onion_utils::Hop::Forward {
3109                                 next_hop_data: msgs::InboundOnionPayload::Forward {
3110                                         short_channel_id, amt_to_forward, outgoing_cltv_value
3111                                 }, ..
3112                         } => {
3113                                 let next_packet_pk = onion_utils::next_hop_pubkey(&self.secp_ctx,
3114                                         msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
3115                                 (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(next_packet_pk))
3116                         },
3117                         // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
3118                         // inbound channel's state.
3119                         onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
3120                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
3121                                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
3122                         {
3123                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
3124                         }
3125                 };
3126
3127                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3128                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3129                 if let Some((err, mut code, chan_update)) = loop {
3130                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3131                         let forwarding_chan_info_opt = match id_option {
3132                                 None => { // unknown_next_peer
3133                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3134                                         // phantom or an intercept.
3135                                         if (self.default_configuration.accept_intercept_htlcs &&
3136                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3137                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3138                                         {
3139                                                 None
3140                                         } else {
3141                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3142                                         }
3143                                 },
3144                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3145                         };
3146                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3147                                 let per_peer_state = self.per_peer_state.read().unwrap();
3148                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3149                                 if peer_state_mutex_opt.is_none() {
3150                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3151                                 }
3152                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3153                                 let peer_state = &mut *peer_state_lock;
3154                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3155                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3156                                 ).flatten() {
3157                                         None => {
3158                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3159                                                 // have no consistency guarantees.
3160                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3161                                         },
3162                                         Some(chan) => chan
3163                                 };
3164                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3165                                         // Note that the behavior here should be identical to the above block - we
3166                                         // should NOT reveal the existence or non-existence of a private channel if
3167                                         // we don't allow forwards outbound over them.
3168                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3169                                 }
3170                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3171                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3172                                         // "refuse to forward unless the SCID alias was used", so we pretend
3173                                         // we don't have the channel here.
3174                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3175                                 }
3176                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3177
3178                                 // Note that we could technically not return an error yet here and just hope
3179                                 // that the connection is reestablished or monitor updated by the time we get
3180                                 // around to doing the actual forward, but better to fail early if we can and
3181                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3182                                 // on a small/per-node/per-channel scale.
3183                                 if !chan.context.is_live() { // channel_disabled
3184                                         // If the channel_update we're going to return is disabled (i.e. the
3185                                         // peer has been disabled for some time), return `channel_disabled`,
3186                                         // otherwise return `temporary_channel_failure`.
3187                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3188                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3189                                         } else {
3190                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3191                                         }
3192                                 }
3193                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3194                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3195                                 }
3196                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3197                                         break Some((err, code, chan_update_opt));
3198                                 }
3199                                 chan_update_opt
3200                         } else {
3201                                 if (msg.cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
3202                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3203                                         // forwarding over a real channel we can't generate a channel_update
3204                                         // for it. Instead we just return a generic temporary_node_failure.
3205                                         break Some((
3206                                                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
3207                                                         0x2000 | 2, None,
3208                                         ));
3209                                 }
3210                                 None
3211                         };
3212
3213                         let cur_height = self.best_block.read().unwrap().height() + 1;
3214                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
3215                         // but we want to be robust wrt to counterparty packet sanitization (see
3216                         // HTLC_FAIL_BACK_BUFFER rationale).
3217                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
3218                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
3219                         }
3220                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
3221                                 break Some(("CLTV expiry is too far in the future", 21, None));
3222                         }
3223                         // If the HTLC expires ~now, don't bother trying to forward it to our
3224                         // counterparty. They should fail it anyway, but we don't want to bother with
3225                         // the round-trips or risk them deciding they definitely want the HTLC and
3226                         // force-closing to ensure they get it if we're offline.
3227                         // We previously had a much more aggressive check here which tried to ensure
3228                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
3229                         // but there is no need to do that, and since we're a bit conservative with our
3230                         // risk threshold it just results in failing to forward payments.
3231                         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
3232                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
3233                         }
3234
3235                         break None;
3236                 }
3237                 {
3238                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3239                         if let Some(chan_update) = chan_update {
3240                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3241                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3242                                 }
3243                                 else if code == 0x1000 | 13 {
3244                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3245                                 }
3246                                 else if code == 0x1000 | 20 {
3247                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3248                                         0u16.write(&mut res).expect("Writes cannot fail");
3249                                 }
3250                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3251                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3252                                 chan_update.write(&mut res).expect("Writes cannot fail");
3253                         } else if code & 0x1000 == 0x1000 {
3254                                 // If we're trying to return an error that requires a `channel_update` but
3255                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3256                                 // generate an update), just use the generic "temporary_node_failure"
3257                                 // instead.
3258                                 code = 0x2000 | 2;
3259                         }
3260                         return_err!(err, code, &res.0[..]);
3261                 }
3262                 Ok((next_hop, shared_secret, next_packet_pk_opt))
3263         }
3264
3265         fn construct_pending_htlc_status<'a>(
3266                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3267                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3268         ) -> PendingHTLCStatus {
3269                 macro_rules! return_err {
3270                         ($msg: expr, $err_code: expr, $data: expr) => {
3271                                 {
3272                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3273                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3274                                                 channel_id: msg.channel_id,
3275                                                 htlc_id: msg.htlc_id,
3276                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3277                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3278                                         }));
3279                                 }
3280                         }
3281                 }
3282                 match decoded_hop {
3283                         onion_utils::Hop::Receive(next_hop_data) => {
3284                                 // OUR PAYMENT!
3285                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3286                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat)
3287                                 {
3288                                         Ok(info) => {
3289                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3290                                                 // message, however that would leak that we are the recipient of this payment, so
3291                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3292                                                 // delay) once they've send us a commitment_signed!
3293                                                 PendingHTLCStatus::Forward(info)
3294                                         },
3295                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3296                                 }
3297                         },
3298                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3299                                 match self.construct_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3300                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3301                                         Ok(info) => PendingHTLCStatus::Forward(info),
3302                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3303                                 }
3304                         }
3305                 }
3306         }
3307
3308         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3309         /// public, and thus should be called whenever the result is going to be passed out in a
3310         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3311         ///
3312         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3313         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3314         /// storage and the `peer_state` lock has been dropped.
3315         ///
3316         /// [`channel_update`]: msgs::ChannelUpdate
3317         /// [`internal_closing_signed`]: Self::internal_closing_signed
3318         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3319                 if !chan.context.should_announce() {
3320                         return Err(LightningError {
3321                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3322                                 action: msgs::ErrorAction::IgnoreError
3323                         });
3324                 }
3325                 if chan.context.get_short_channel_id().is_none() {
3326                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3327                 }
3328                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3329                 self.get_channel_update_for_unicast(chan)
3330         }
3331
3332         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3333         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3334         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3335         /// provided evidence that they know about the existence of the channel.
3336         ///
3337         /// Note that through [`internal_closing_signed`], this function is called without the
3338         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3339         /// removed from the storage and the `peer_state` lock has been dropped.
3340         ///
3341         /// [`channel_update`]: msgs::ChannelUpdate
3342         /// [`internal_closing_signed`]: Self::internal_closing_signed
3343         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3344                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", &chan.context.channel_id());
3345                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3346                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3347                         Some(id) => id,
3348                 };
3349
3350                 self.get_channel_update_for_onion(short_channel_id, chan)
3351         }
3352
3353         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3354                 log_trace!(self.logger, "Generating channel update for channel {}", &chan.context.channel_id());
3355                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3356
3357                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3358                         ChannelUpdateStatus::Enabled => true,
3359                         ChannelUpdateStatus::DisabledStaged(_) => true,
3360                         ChannelUpdateStatus::Disabled => false,
3361                         ChannelUpdateStatus::EnabledStaged(_) => false,
3362                 };
3363
3364                 let unsigned = msgs::UnsignedChannelUpdate {
3365                         chain_hash: self.chain_hash,
3366                         short_channel_id,
3367                         timestamp: chan.context.get_update_time_counter(),
3368                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3369                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3370                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3371                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3372                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3373                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3374                         excess_data: Vec::new(),
3375                 };
3376                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3377                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3378                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3379                 // channel.
3380                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3381
3382                 Ok(msgs::ChannelUpdate {
3383                         signature: sig,
3384                         contents: unsigned
3385                 })
3386         }
3387
3388         #[cfg(test)]
3389         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> {
3390                 let _lck = self.total_consistency_lock.read().unwrap();
3391                 self.send_payment_along_path(SendAlongPathArgs {
3392                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3393                         session_priv_bytes
3394                 })
3395         }
3396
3397         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3398                 let SendAlongPathArgs {
3399                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3400                         session_priv_bytes
3401                 } = args;
3402                 // The top-level caller should hold the total_consistency_lock read lock.
3403                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3404
3405                 log_trace!(self.logger,
3406                         "Attempting to send payment with payment hash {} along path with next hop {}",
3407                         payment_hash, path.hops.first().unwrap().short_channel_id);
3408                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3409                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3410
3411                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3412                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3413                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3414
3415                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3416                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3417
3418                 let err: Result<(), _> = loop {
3419                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3420                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3421                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3422                         };
3423
3424                         let per_peer_state = self.per_peer_state.read().unwrap();
3425                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3426                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3427                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3428                         let peer_state = &mut *peer_state_lock;
3429                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3430                                 match chan_phase_entry.get_mut() {
3431                                         ChannelPhase::Funded(chan) => {
3432                                                 if !chan.context.is_live() {
3433                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3434                                                 }
3435                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3436                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3437                                                         htlc_cltv, HTLCSource::OutboundRoute {
3438                                                                 path: path.clone(),
3439                                                                 session_priv: session_priv.clone(),
3440                                                                 first_hop_htlc_msat: htlc_msat,
3441                                                                 payment_id,
3442                                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3443                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3444                                                         Some(monitor_update) => {
3445                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3446                                                                         false => {
3447                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3448                                                                                 // docs) that we will resend the commitment update once monitor
3449                                                                                 // updating completes. Therefore, we must return an error
3450                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3451                                                                                 // which we do in the send_payment check for
3452                                                                                 // MonitorUpdateInProgress, below.
3453                                                                                 return Err(APIError::MonitorUpdateInProgress);
3454                                                                         },
3455                                                                         true => {},
3456                                                                 }
3457                                                         },
3458                                                         None => {},
3459                                                 }
3460                                         },
3461                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3462                                 };
3463                         } else {
3464                                 // The channel was likely removed after we fetched the id from the
3465                                 // `short_to_chan_info` map, but before we successfully locked the
3466                                 // `channel_by_id` map.
3467                                 // This can occur as no consistency guarantees exists between the two maps.
3468                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3469                         }
3470                         return Ok(());
3471                 };
3472
3473                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3474                         Ok(_) => unreachable!(),
3475                         Err(e) => {
3476                                 Err(APIError::ChannelUnavailable { err: e.err })
3477                         },
3478                 }
3479         }
3480
3481         /// Sends a payment along a given route.
3482         ///
3483         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3484         /// fields for more info.
3485         ///
3486         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3487         /// [`PeerManager::process_events`]).
3488         ///
3489         /// # Avoiding Duplicate Payments
3490         ///
3491         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3492         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3493         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3494         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3495         /// second payment with the same [`PaymentId`].
3496         ///
3497         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3498         /// tracking of payments, including state to indicate once a payment has completed. Because you
3499         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3500         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3501         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3502         ///
3503         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3504         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3505         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3506         /// [`ChannelManager::list_recent_payments`] for more information.
3507         ///
3508         /// # Possible Error States on [`PaymentSendFailure`]
3509         ///
3510         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3511         /// each entry matching the corresponding-index entry in the route paths, see
3512         /// [`PaymentSendFailure`] for more info.
3513         ///
3514         /// In general, a path may raise:
3515         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3516         ///    node public key) is specified.
3517         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3518         ///    closed, doesn't exist, or the peer is currently disconnected.
3519         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3520         ///    relevant updates.
3521         ///
3522         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3523         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3524         /// different route unless you intend to pay twice!
3525         ///
3526         /// [`RouteHop`]: crate::routing::router::RouteHop
3527         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3528         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3529         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3530         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3531         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3532         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3533                 let best_block_height = self.best_block.read().unwrap().height();
3534                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3535                 self.pending_outbound_payments
3536                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3537                                 &self.entropy_source, &self.node_signer, best_block_height,
3538                                 |args| self.send_payment_along_path(args))
3539         }
3540
3541         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3542         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3543         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3544                 let best_block_height = self.best_block.read().unwrap().height();
3545                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3546                 self.pending_outbound_payments
3547                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3548                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3549                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3550                                 &self.pending_events, |args| self.send_payment_along_path(args))
3551         }
3552
3553         #[cfg(test)]
3554         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> {
3555                 let best_block_height = self.best_block.read().unwrap().height();
3556                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3557                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3558                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3559                         best_block_height, |args| self.send_payment_along_path(args))
3560         }
3561
3562         #[cfg(test)]
3563         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> {
3564                 let best_block_height = self.best_block.read().unwrap().height();
3565                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3566         }
3567
3568         #[cfg(test)]
3569         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3570                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3571         }
3572
3573
3574         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3575         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3576         /// retries are exhausted.
3577         ///
3578         /// # Event Generation
3579         ///
3580         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3581         /// as there are no remaining pending HTLCs for this payment.
3582         ///
3583         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3584         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3585         /// determine the ultimate status of a payment.
3586         ///
3587         /// # Restart Behavior
3588         ///
3589         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3590         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated.
3591         pub fn abandon_payment(&self, payment_id: PaymentId) {
3592                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3593                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3594         }
3595
3596         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3597         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3598         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3599         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3600         /// never reach the recipient.
3601         ///
3602         /// See [`send_payment`] documentation for more details on the return value of this function
3603         /// and idempotency guarantees provided by the [`PaymentId`] key.
3604         ///
3605         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3606         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3607         ///
3608         /// [`send_payment`]: Self::send_payment
3609         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3610                 let best_block_height = self.best_block.read().unwrap().height();
3611                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3612                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3613                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3614                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3615         }
3616
3617         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3618         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3619         ///
3620         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3621         /// payments.
3622         ///
3623         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3624         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> {
3625                 let best_block_height = self.best_block.read().unwrap().height();
3626                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3627                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3628                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3629                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3630                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3631         }
3632
3633         /// Send a payment that is probing the given route for liquidity. We calculate the
3634         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3635         /// us to easily discern them from real payments.
3636         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3637                 let best_block_height = self.best_block.read().unwrap().height();
3638                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3639                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3640                         &self.entropy_source, &self.node_signer, best_block_height,
3641                         |args| self.send_payment_along_path(args))
3642         }
3643
3644         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3645         /// payment probe.
3646         #[cfg(test)]
3647         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3648                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3649         }
3650
3651         /// Sends payment probes over all paths of a route that would be used to pay the given
3652         /// amount to the given `node_id`.
3653         ///
3654         /// See [`ChannelManager::send_preflight_probes`] for more information.
3655         pub fn send_spontaneous_preflight_probes(
3656                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3657                 liquidity_limit_multiplier: Option<u64>,
3658         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3659                 let payment_params =
3660                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3661
3662                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3663
3664                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3665         }
3666
3667         /// Sends payment probes over all paths of a route that would be used to pay a route found
3668         /// according to the given [`RouteParameters`].
3669         ///
3670         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3671         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3672         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3673         /// confirmation in a wallet UI.
3674         ///
3675         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3676         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3677         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3678         /// payment. To mitigate this issue, channels with available liquidity less than the required
3679         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3680         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3681         pub fn send_preflight_probes(
3682                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3683         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3684                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3685
3686                 let payer = self.get_our_node_id();
3687                 let usable_channels = self.list_usable_channels();
3688                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3689                 let inflight_htlcs = self.compute_inflight_htlcs();
3690
3691                 let route = self
3692                         .router
3693                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3694                         .map_err(|e| {
3695                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3696                                 ProbeSendFailure::RouteNotFound
3697                         })?;
3698
3699                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3700
3701                 let mut res = Vec::new();
3702
3703                 for mut path in route.paths {
3704                         // If the last hop is probably an unannounced channel we refrain from probing all the
3705                         // way through to the end and instead probe up to the second-to-last channel.
3706                         while let Some(last_path_hop) = path.hops.last() {
3707                                 if last_path_hop.maybe_announced_channel {
3708                                         // We found a potentially announced last hop.
3709                                         break;
3710                                 } else {
3711                                         // Drop the last hop, as it's likely unannounced.
3712                                         log_debug!(
3713                                                 self.logger,
3714                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3715                                                 last_path_hop.short_channel_id
3716                                         );
3717                                         let final_value_msat = path.final_value_msat();
3718                                         path.hops.pop();
3719                                         if let Some(new_last) = path.hops.last_mut() {
3720                                                 new_last.fee_msat += final_value_msat;
3721                                         }
3722                                 }
3723                         }
3724
3725                         if path.hops.len() < 2 {
3726                                 log_debug!(
3727                                         self.logger,
3728                                         "Skipped sending payment probe over path with less than two hops."
3729                                 );
3730                                 continue;
3731                         }
3732
3733                         if let Some(first_path_hop) = path.hops.first() {
3734                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3735                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3736                                 }) {
3737                                         let path_value = path.final_value_msat() + path.fee_msat();
3738                                         let used_liquidity =
3739                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3740
3741                                         if first_hop.next_outbound_htlc_limit_msat
3742                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3743                                         {
3744                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3745                                                 continue;
3746                                         } else {
3747                                                 *used_liquidity += path_value;
3748                                         }
3749                                 }
3750                         }
3751
3752                         res.push(self.send_probe(path).map_err(|e| {
3753                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3754                                 ProbeSendFailure::SendingFailed(e)
3755                         })?);
3756                 }
3757
3758                 Ok(res)
3759         }
3760
3761         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3762         /// which checks the correctness of the funding transaction given the associated channel.
3763         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3764                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3765                 mut find_funding_output: FundingOutput,
3766         ) -> Result<(), APIError> {
3767                 let per_peer_state = self.per_peer_state.read().unwrap();
3768                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3769                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3770
3771                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3772                 let peer_state = &mut *peer_state_lock;
3773                 let (chan, msg) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3774                         Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
3775                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3776
3777                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &self.logger)
3778                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3779                                                 let channel_id = chan.context.channel_id();
3780                                                 let user_id = chan.context.get_user_id();
3781                                                 let shutdown_res = chan.context.force_shutdown(false);
3782                                                 let channel_capacity = chan.context.get_value_satoshis();
3783                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3784                                         } else { unreachable!(); });
3785                                 match funding_res {
3786                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3787                                         Err((chan, err)) => {
3788                                                 mem::drop(peer_state_lock);
3789                                                 mem::drop(per_peer_state);
3790
3791                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3792                                                 return Err(APIError::ChannelUnavailable {
3793                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3794                                                 });
3795                                         },
3796                                 }
3797                         },
3798                         Some(phase) => {
3799                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3800                                 return Err(APIError::APIMisuseError {
3801                                         err: format!(
3802                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3803                                                 temporary_channel_id, counterparty_node_id),
3804                                 })
3805                         },
3806                         None => return Err(APIError::ChannelUnavailable {err: format!(
3807                                 "Channel with id {} not found for the passed counterparty node_id {}",
3808                                 temporary_channel_id, counterparty_node_id),
3809                                 }),
3810                 };
3811
3812                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3813                         node_id: chan.context.get_counterparty_node_id(),
3814                         msg,
3815                 });
3816                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3817                         hash_map::Entry::Occupied(_) => {
3818                                 panic!("Generated duplicate funding txid?");
3819                         },
3820                         hash_map::Entry::Vacant(e) => {
3821                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3822                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3823                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3824                                 }
3825                                 e.insert(ChannelPhase::Funded(chan));
3826                         }
3827                 }
3828                 Ok(())
3829         }
3830
3831         #[cfg(test)]
3832         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3833                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3834                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3835                 })
3836         }
3837
3838         /// Call this upon creation of a funding transaction for the given channel.
3839         ///
3840         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3841         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3842         ///
3843         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3844         /// across the p2p network.
3845         ///
3846         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3847         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3848         ///
3849         /// May panic if the output found in the funding transaction is duplicative with some other
3850         /// channel (note that this should be trivially prevented by using unique funding transaction
3851         /// keys per-channel).
3852         ///
3853         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3854         /// counterparty's signature the funding transaction will automatically be broadcast via the
3855         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3856         ///
3857         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3858         /// not currently support replacing a funding transaction on an existing channel. Instead,
3859         /// create a new channel with a conflicting funding transaction.
3860         ///
3861         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3862         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3863         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3864         /// for more details.
3865         ///
3866         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3867         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3868         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3869                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3870         }
3871
3872         /// Call this upon creation of a batch funding transaction for the given channels.
3873         ///
3874         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3875         /// each individual channel and transaction output.
3876         ///
3877         /// Do NOT broadcast the funding transaction yourself. This batch funding transcaction
3878         /// will only be broadcast when we have safely received and persisted the counterparty's
3879         /// signature for each channel.
3880         ///
3881         /// If there is an error, all channels in the batch are to be considered closed.
3882         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3883                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3884                 let mut result = Ok(());
3885
3886                 if !funding_transaction.is_coin_base() {
3887                         for inp in funding_transaction.input.iter() {
3888                                 if inp.witness.is_empty() {
3889                                         result = result.and(Err(APIError::APIMisuseError {
3890                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3891                                         }));
3892                                 }
3893                         }
3894                 }
3895                 if funding_transaction.output.len() > u16::max_value() as usize {
3896                         result = result.and(Err(APIError::APIMisuseError {
3897                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3898                         }));
3899                 }
3900                 {
3901                         let height = self.best_block.read().unwrap().height();
3902                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3903                         // lower than the next block height. However, the modules constituting our Lightning
3904                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3905                         // module is ahead of LDK, only allow one more block of headroom.
3906                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) && LockTime::from(funding_transaction.lock_time).is_block_height() && funding_transaction.lock_time.0 > height + 1 {
3907                                 result = result.and(Err(APIError::APIMisuseError {
3908                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3909                                 }));
3910                         }
3911                 }
3912
3913                 let txid = funding_transaction.txid();
3914                 let is_batch_funding = temporary_channels.len() > 1;
3915                 let mut funding_batch_states = if is_batch_funding {
3916                         Some(self.funding_batch_states.lock().unwrap())
3917                 } else {
3918                         None
3919                 };
3920                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3921                         match states.entry(txid) {
3922                                 btree_map::Entry::Occupied(_) => {
3923                                         result = result.clone().and(Err(APIError::APIMisuseError {
3924                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3925                                         }));
3926                                         None
3927                                 },
3928                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3929                         }
3930                 });
3931                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels.iter() {
3932                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3933                                 temporary_channel_id,
3934                                 counterparty_node_id,
3935                                 funding_transaction.clone(),
3936                                 is_batch_funding,
3937                                 |chan, tx| {
3938                                         let mut output_index = None;
3939                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3940                                         for (idx, outp) in tx.output.iter().enumerate() {
3941                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3942                                                         if output_index.is_some() {
3943                                                                 return Err(APIError::APIMisuseError {
3944                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3945                                                                 });
3946                                                         }
3947                                                         output_index = Some(idx as u16);
3948                                                 }
3949                                         }
3950                                         if output_index.is_none() {
3951                                                 return Err(APIError::APIMisuseError {
3952                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3953                                                 });
3954                                         }
3955                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3956                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3957                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3958                                         }
3959                                         Ok(outpoint)
3960                                 })
3961                         );
3962                 }
3963                 if let Err(ref e) = result {
3964                         // Remaining channels need to be removed on any error.
3965                         let e = format!("Error in transaction funding: {:?}", e);
3966                         let mut channels_to_remove = Vec::new();
3967                         channels_to_remove.extend(funding_batch_states.as_mut()
3968                                 .and_then(|states| states.remove(&txid))
3969                                 .into_iter().flatten()
3970                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3971                         );
3972                         channels_to_remove.extend(temporary_channels.iter()
3973                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3974                         );
3975                         let mut shutdown_results = Vec::new();
3976                         {
3977                                 let per_peer_state = self.per_peer_state.read().unwrap();
3978                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3979                                         per_peer_state.get(&counterparty_node_id)
3980                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3981                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3982                                                 .map(|mut chan| {
3983                                                         update_maps_on_chan_removal!(self, &chan.context());
3984                                                         self.issue_channel_close_events(&chan.context(), ClosureReason::ProcessingError { err: e.clone() });
3985                                                         shutdown_results.push(chan.context_mut().force_shutdown(false));
3986                                                 });
3987                                 }
3988                         }
3989                         for shutdown_result in shutdown_results.drain(..) {
3990                                 self.finish_close_channel(shutdown_result);
3991                         }
3992                 }
3993                 result
3994         }
3995
3996         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3997         ///
3998         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3999         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4000         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4001         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4002         ///
4003         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4004         /// `counterparty_node_id` is provided.
4005         ///
4006         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4007         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4008         ///
4009         /// If an error is returned, none of the updates should be considered applied.
4010         ///
4011         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4012         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4013         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4014         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4015         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4016         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4017         /// [`APIMisuseError`]: APIError::APIMisuseError
4018         pub fn update_partial_channel_config(
4019                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
4020         ) -> Result<(), APIError> {
4021                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
4022                         return Err(APIError::APIMisuseError {
4023                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
4024                         });
4025                 }
4026
4027                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4028                 let per_peer_state = self.per_peer_state.read().unwrap();
4029                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4030                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4031                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4032                 let peer_state = &mut *peer_state_lock;
4033                 for channel_id in channel_ids {
4034                         if !peer_state.has_channel(channel_id) {
4035                                 return Err(APIError::ChannelUnavailable {
4036                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4037                                 });
4038                         };
4039                 }
4040                 for channel_id in channel_ids {
4041                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4042                                 let mut config = channel_phase.context().config();
4043                                 config.apply(config_update);
4044                                 if !channel_phase.context_mut().update_config(&config) {
4045                                         continue;
4046                                 }
4047                                 if let ChannelPhase::Funded(channel) = channel_phase {
4048                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4049                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4050                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4051                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4052                                                         node_id: channel.context.get_counterparty_node_id(),
4053                                                         msg,
4054                                                 });
4055                                         }
4056                                 }
4057                                 continue;
4058                         } else {
4059                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4060                                 debug_assert!(false);
4061                                 return Err(APIError::ChannelUnavailable {
4062                                         err: format!(
4063                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4064                                                 channel_id, counterparty_node_id),
4065                                 });
4066                         };
4067                 }
4068                 Ok(())
4069         }
4070
4071         /// Atomically updates the [`ChannelConfig`] for the given channels.
4072         ///
4073         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4074         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4075         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4076         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4077         ///
4078         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4079         /// `counterparty_node_id` is provided.
4080         ///
4081         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4082         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4083         ///
4084         /// If an error is returned, none of the updates should be considered applied.
4085         ///
4086         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4087         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4088         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4089         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4090         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4091         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4092         /// [`APIMisuseError`]: APIError::APIMisuseError
4093         pub fn update_channel_config(
4094                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4095         ) -> Result<(), APIError> {
4096                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4097         }
4098
4099         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4100         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4101         ///
4102         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4103         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4104         ///
4105         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4106         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4107         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4108         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4109         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4110         ///
4111         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4112         /// you from forwarding more than you received. See
4113         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4114         /// than expected.
4115         ///
4116         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4117         /// backwards.
4118         ///
4119         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4120         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4121         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4122         // TODO: when we move to deciding the best outbound channel at forward time, only take
4123         // `next_node_id` and not `next_hop_channel_id`
4124         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> {
4125                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4126
4127                 let next_hop_scid = {
4128                         let peer_state_lock = self.per_peer_state.read().unwrap();
4129                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4130                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4131                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4132                         let peer_state = &mut *peer_state_lock;
4133                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4134                                 Some(ChannelPhase::Funded(chan)) => {
4135                                         if !chan.context.is_usable() {
4136                                                 return Err(APIError::ChannelUnavailable {
4137                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4138                                                 })
4139                                         }
4140                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4141                                 },
4142                                 Some(_) => return Err(APIError::ChannelUnavailable {
4143                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4144                                                 next_hop_channel_id, next_node_id)
4145                                 }),
4146                                 None => return Err(APIError::ChannelUnavailable {
4147                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}",
4148                                                 next_hop_channel_id, next_node_id)
4149                                 })
4150                         }
4151                 };
4152
4153                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4154                         .ok_or_else(|| APIError::APIMisuseError {
4155                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4156                         })?;
4157
4158                 let routing = match payment.forward_info.routing {
4159                         PendingHTLCRouting::Forward { onion_packet, .. } => {
4160                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
4161                         },
4162                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4163                 };
4164                 let skimmed_fee_msat =
4165                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4166                 let pending_htlc_info = PendingHTLCInfo {
4167                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4168                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4169                 };
4170
4171                 let mut per_source_pending_forward = [(
4172                         payment.prev_short_channel_id,
4173                         payment.prev_funding_outpoint,
4174                         payment.prev_user_channel_id,
4175                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4176                 )];
4177                 self.forward_htlcs(&mut per_source_pending_forward);
4178                 Ok(())
4179         }
4180
4181         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4182         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4183         ///
4184         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4185         /// backwards.
4186         ///
4187         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4188         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4189                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4190
4191                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4192                         .ok_or_else(|| APIError::APIMisuseError {
4193                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4194                         })?;
4195
4196                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4197                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4198                                 short_channel_id: payment.prev_short_channel_id,
4199                                 user_channel_id: Some(payment.prev_user_channel_id),
4200                                 outpoint: payment.prev_funding_outpoint,
4201                                 htlc_id: payment.prev_htlc_id,
4202                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4203                                 phantom_shared_secret: None,
4204                         });
4205
4206                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4207                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4208                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4209                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4210
4211                 Ok(())
4212         }
4213
4214         /// Processes HTLCs which are pending waiting on random forward delay.
4215         ///
4216         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4217         /// Will likely generate further events.
4218         pub fn process_pending_htlc_forwards(&self) {
4219                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4220
4221                 let mut new_events = VecDeque::new();
4222                 let mut failed_forwards = Vec::new();
4223                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4224                 {
4225                         let mut forward_htlcs = HashMap::new();
4226                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4227
4228                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4229                                 if short_chan_id != 0 {
4230                                         macro_rules! forwarding_channel_not_found {
4231                                                 () => {
4232                                                         for forward_info in pending_forwards.drain(..) {
4233                                                                 match forward_info {
4234                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4235                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4236                                                                                 forward_info: PendingHTLCInfo {
4237                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4238                                                                                         outgoing_cltv_value, ..
4239                                                                                 }
4240                                                                         }) => {
4241                                                                                 macro_rules! failure_handler {
4242                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4243                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4244
4245                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4246                                                                                                         short_channel_id: prev_short_channel_id,
4247                                                                                                         user_channel_id: Some(prev_user_channel_id),
4248                                                                                                         outpoint: prev_funding_outpoint,
4249                                                                                                         htlc_id: prev_htlc_id,
4250                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4251                                                                                                         phantom_shared_secret: $phantom_ss,
4252                                                                                                 });
4253
4254                                                                                                 let reason = if $next_hop_unknown {
4255                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4256                                                                                                 } else {
4257                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4258                                                                                                 };
4259
4260                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4261                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4262                                                                                                         reason
4263                                                                                                 ));
4264                                                                                                 continue;
4265                                                                                         }
4266                                                                                 }
4267                                                                                 macro_rules! fail_forward {
4268                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4269                                                                                                 {
4270                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4271                                                                                                 }
4272                                                                                         }
4273                                                                                 }
4274                                                                                 macro_rules! failed_payment {
4275                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4276                                                                                                 {
4277                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4278                                                                                                 }
4279                                                                                         }
4280                                                                                 }
4281                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
4282                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4283                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4284                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4285                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4286                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4287                                                                                                         payment_hash, &self.node_signer
4288                                                                                                 ) {
4289                                                                                                         Ok(res) => res,
4290                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4291                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
4292                                                                                                                 // In this scenario, the phantom would have sent us an
4293                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4294                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4295                                                                                                                 // of the onion.
4296                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4297                                                                                                         },
4298                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4299                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4300                                                                                                         },
4301                                                                                                 };
4302                                                                                                 match next_hop {
4303                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4304                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data,
4305                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4306                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None)
4307                                                                                                                 {
4308                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4309                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4310                                                                                                                 }
4311                                                                                                         },
4312                                                                                                         _ => panic!(),
4313                                                                                                 }
4314                                                                                         } else {
4315                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4316                                                                                         }
4317                                                                                 } else {
4318                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4319                                                                                 }
4320                                                                         },
4321                                                                         HTLCForwardInfo::FailHTLC { .. } => {
4322                                                                                 // Channel went away before we could fail it. This implies
4323                                                                                 // the channel is now on chain and our counterparty is
4324                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4325                                                                                 // problem, not ours.
4326                                                                         }
4327                                                                 }
4328                                                         }
4329                                                 }
4330                                         }
4331                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4332                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4333                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4334                                                 None => {
4335                                                         forwarding_channel_not_found!();
4336                                                         continue;
4337                                                 }
4338                                         };
4339                                         let per_peer_state = self.per_peer_state.read().unwrap();
4340                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4341                                         if peer_state_mutex_opt.is_none() {
4342                                                 forwarding_channel_not_found!();
4343                                                 continue;
4344                                         }
4345                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4346                                         let peer_state = &mut *peer_state_lock;
4347                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4348                                                 for forward_info in pending_forwards.drain(..) {
4349                                                         match forward_info {
4350                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4351                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4352                                                                         forward_info: PendingHTLCInfo {
4353                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4354                                                                                 routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
4355                                                                         },
4356                                                                 }) => {
4357                                                                         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);
4358                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4359                                                                                 short_channel_id: prev_short_channel_id,
4360                                                                                 user_channel_id: Some(prev_user_channel_id),
4361                                                                                 outpoint: prev_funding_outpoint,
4362                                                                                 htlc_id: prev_htlc_id,
4363                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4364                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4365                                                                                 phantom_shared_secret: None,
4366                                                                         });
4367                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4368                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4369                                                                                 onion_packet, skimmed_fee_msat, &self.fee_estimator,
4370                                                                                 &self.logger)
4371                                                                         {
4372                                                                                 if let ChannelError::Ignore(msg) = e {
4373                                                                                         log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4374                                                                                 } else {
4375                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4376                                                                                 }
4377                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4378                                                                                 failed_forwards.push((htlc_source, payment_hash,
4379                                                                                         HTLCFailReason::reason(failure_code, data),
4380                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4381                                                                                 ));
4382                                                                                 continue;
4383                                                                         }
4384                                                                 },
4385                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4386                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4387                                                                 },
4388                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4389                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4390                                                                         if let Err(e) = chan.queue_fail_htlc(
4391                                                                                 htlc_id, err_packet, &self.logger
4392                                                                         ) {
4393                                                                                 if let ChannelError::Ignore(msg) = e {
4394                                                                                         log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4395                                                                                 } else {
4396                                                                                         panic!("Stated return value requirements in queue_fail_htlc() were not met");
4397                                                                                 }
4398                                                                                 // fail-backs are best-effort, we probably already have one
4399                                                                                 // pending, and if not that's OK, if not, the channel is on
4400                                                                                 // the chain and sending the HTLC-Timeout is their problem.
4401                                                                                 continue;
4402                                                                         }
4403                                                                 },
4404                                                         }
4405                                                 }
4406                                         } else {
4407                                                 forwarding_channel_not_found!();
4408                                                 continue;
4409                                         }
4410                                 } else {
4411                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4412                                                 match forward_info {
4413                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4414                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4415                                                                 forward_info: PendingHTLCInfo {
4416                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4417                                                                         skimmed_fee_msat, ..
4418                                                                 }
4419                                                         }) => {
4420                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4421                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4422                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4423                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4424                                                                                                 payment_metadata, custom_tlvs };
4425                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4426                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4427                                                                         },
4428                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4429                                                                                 let onion_fields = RecipientOnionFields {
4430                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4431                                                                                         payment_metadata,
4432                                                                                         custom_tlvs,
4433                                                                                 };
4434                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4435                                                                                         payment_data, None, onion_fields)
4436                                                                         },
4437                                                                         _ => {
4438                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4439                                                                         }
4440                                                                 };
4441                                                                 let claimable_htlc = ClaimableHTLC {
4442                                                                         prev_hop: HTLCPreviousHopData {
4443                                                                                 short_channel_id: prev_short_channel_id,
4444                                                                                 user_channel_id: Some(prev_user_channel_id),
4445                                                                                 outpoint: prev_funding_outpoint,
4446                                                                                 htlc_id: prev_htlc_id,
4447                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4448                                                                                 phantom_shared_secret,
4449                                                                         },
4450                                                                         // We differentiate the received value from the sender intended value
4451                                                                         // if possible so that we don't prematurely mark MPP payments complete
4452                                                                         // if routing nodes overpay
4453                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4454                                                                         sender_intended_value: outgoing_amt_msat,
4455                                                                         timer_ticks: 0,
4456                                                                         total_value_received: None,
4457                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4458                                                                         cltv_expiry,
4459                                                                         onion_payload,
4460                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4461                                                                 };
4462
4463                                                                 let mut committed_to_claimable = false;
4464
4465                                                                 macro_rules! fail_htlc {
4466                                                                         ($htlc: expr, $payment_hash: expr) => {
4467                                                                                 debug_assert!(!committed_to_claimable);
4468                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4469                                                                                 htlc_msat_height_data.extend_from_slice(
4470                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4471                                                                                 );
4472                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4473                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4474                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4475                                                                                                 outpoint: prev_funding_outpoint,
4476                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4477                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4478                                                                                                 phantom_shared_secret,
4479                                                                                         }), payment_hash,
4480                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4481                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4482                                                                                 ));
4483                                                                                 continue 'next_forwardable_htlc;
4484                                                                         }
4485                                                                 }
4486                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4487                                                                 let mut receiver_node_id = self.our_network_pubkey;
4488                                                                 if phantom_shared_secret.is_some() {
4489                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4490                                                                                 .expect("Failed to get node_id for phantom node recipient");
4491                                                                 }
4492
4493                                                                 macro_rules! check_total_value {
4494                                                                         ($purpose: expr) => {{
4495                                                                                 let mut payment_claimable_generated = false;
4496                                                                                 let is_keysend = match $purpose {
4497                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4498                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4499                                                                                 };
4500                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4501                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4502                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4503                                                                                 }
4504                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4505                                                                                         .entry(payment_hash)
4506                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4507                                                                                         .or_insert_with(|| {
4508                                                                                                 committed_to_claimable = true;
4509                                                                                                 ClaimablePayment {
4510                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4511                                                                                                 }
4512                                                                                         });
4513                                                                                 if $purpose != claimable_payment.purpose {
4514                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4515                                                                                         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));
4516                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4517                                                                                 }
4518                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4519                                                                                         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);
4520                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4521                                                                                 }
4522                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4523                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4524                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4525                                                                                         }
4526                                                                                 } else {
4527                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4528                                                                                 }
4529                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4530                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4531                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4532                                                                                 for htlc in htlcs.iter() {
4533                                                                                         total_value += htlc.sender_intended_value;
4534                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4535                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4536                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4537                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4538                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4539                                                                                         }
4540                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4541                                                                                 }
4542                                                                                 // The condition determining whether an MPP is complete must
4543                                                                                 // match exactly the condition used in `timer_tick_occurred`
4544                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4545                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4546                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4547                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4548                                                                                                 &payment_hash);
4549                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4550                                                                                 } else if total_value >= claimable_htlc.total_msat {
4551                                                                                         #[allow(unused_assignments)] {
4552                                                                                                 committed_to_claimable = true;
4553                                                                                         }
4554                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4555                                                                                         htlcs.push(claimable_htlc);
4556                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4557                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4558                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4559                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4560                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4561                                                                                                 counterparty_skimmed_fee_msat);
4562                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4563                                                                                                 receiver_node_id: Some(receiver_node_id),
4564                                                                                                 payment_hash,
4565                                                                                                 purpose: $purpose,
4566                                                                                                 amount_msat,
4567                                                                                                 counterparty_skimmed_fee_msat,
4568                                                                                                 via_channel_id: Some(prev_channel_id),
4569                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4570                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4571                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4572                                                                                         }, None));
4573                                                                                         payment_claimable_generated = true;
4574                                                                                 } else {
4575                                                                                         // Nothing to do - we haven't reached the total
4576                                                                                         // payment value yet, wait until we receive more
4577                                                                                         // MPP parts.
4578                                                                                         htlcs.push(claimable_htlc);
4579                                                                                         #[allow(unused_assignments)] {
4580                                                                                                 committed_to_claimable = true;
4581                                                                                         }
4582                                                                                 }
4583                                                                                 payment_claimable_generated
4584                                                                         }}
4585                                                                 }
4586
4587                                                                 // Check that the payment hash and secret are known. Note that we
4588                                                                 // MUST take care to handle the "unknown payment hash" and
4589                                                                 // "incorrect payment secret" cases here identically or we'd expose
4590                                                                 // that we are the ultimate recipient of the given payment hash.
4591                                                                 // Further, we must not expose whether we have any other HTLCs
4592                                                                 // associated with the same payment_hash pending or not.
4593                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4594                                                                 match payment_secrets.entry(payment_hash) {
4595                                                                         hash_map::Entry::Vacant(_) => {
4596                                                                                 match claimable_htlc.onion_payload {
4597                                                                                         OnionPayload::Invoice { .. } => {
4598                                                                                                 let payment_data = payment_data.unwrap();
4599                                                                                                 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) {
4600                                                                                                         Ok(result) => result,
4601                                                                                                         Err(()) => {
4602                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4603                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4604                                                                                                         }
4605                                                                                                 };
4606                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4607                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4608                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4609                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4610                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4611                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4612                                                                                                         }
4613                                                                                                 }
4614                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4615                                                                                                         payment_preimage: payment_preimage.clone(),
4616                                                                                                         payment_secret: payment_data.payment_secret,
4617                                                                                                 };
4618                                                                                                 check_total_value!(purpose);
4619                                                                                         },
4620                                                                                         OnionPayload::Spontaneous(preimage) => {
4621                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4622                                                                                                 check_total_value!(purpose);
4623                                                                                         }
4624                                                                                 }
4625                                                                         },
4626                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4627                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4628                                                                                         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);
4629                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4630                                                                                 }
4631                                                                                 let payment_data = payment_data.unwrap();
4632                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4633                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4634                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4635                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4636                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4637                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4638                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4639                                                                                 } else {
4640                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4641                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4642                                                                                                 payment_secret: payment_data.payment_secret,
4643                                                                                         };
4644                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4645                                                                                         if payment_claimable_generated {
4646                                                                                                 inbound_payment.remove_entry();
4647                                                                                         }
4648                                                                                 }
4649                                                                         },
4650                                                                 };
4651                                                         },
4652                                                         HTLCForwardInfo::FailHTLC { .. } => {
4653                                                                 panic!("Got pending fail of our own HTLC");
4654                                                         }
4655                                                 }
4656                                         }
4657                                 }
4658                         }
4659                 }
4660
4661                 let best_block_height = self.best_block.read().unwrap().height();
4662                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4663                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4664                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4665
4666                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4667                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4668                 }
4669                 self.forward_htlcs(&mut phantom_receives);
4670
4671                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4672                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4673                 // nice to do the work now if we can rather than while we're trying to get messages in the
4674                 // network stack.
4675                 self.check_free_holding_cells();
4676
4677                 if new_events.is_empty() { return }
4678                 let mut events = self.pending_events.lock().unwrap();
4679                 events.append(&mut new_events);
4680         }
4681
4682         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4683         ///
4684         /// Expects the caller to have a total_consistency_lock read lock.
4685         fn process_background_events(&self) -> NotifyOption {
4686                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4687
4688                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4689
4690                 let mut background_events = Vec::new();
4691                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4692                 if background_events.is_empty() {
4693                         return NotifyOption::SkipPersistNoEvents;
4694                 }
4695
4696                 for event in background_events.drain(..) {
4697                         match event {
4698                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4699                                         // The channel has already been closed, so no use bothering to care about the
4700                                         // monitor updating completing.
4701                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4702                                 },
4703                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4704                                         let mut updated_chan = false;
4705                                         {
4706                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4707                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4708                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4709                                                         let peer_state = &mut *peer_state_lock;
4710                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4711                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4712                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4713                                                                                 updated_chan = true;
4714                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4715                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4716                                                                         } else {
4717                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4718                                                                         }
4719                                                                 },
4720                                                                 hash_map::Entry::Vacant(_) => {},
4721                                                         }
4722                                                 }
4723                                         }
4724                                         if !updated_chan {
4725                                                 // TODO: Track this as in-flight even though the channel is closed.
4726                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4727                                         }
4728                                 },
4729                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4730                                         let per_peer_state = self.per_peer_state.read().unwrap();
4731                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4732                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4733                                                 let peer_state = &mut *peer_state_lock;
4734                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4735                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4736                                                 } else {
4737                                                         let update_actions = peer_state.monitor_update_blocked_actions
4738                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4739                                                         mem::drop(peer_state_lock);
4740                                                         mem::drop(per_peer_state);
4741                                                         self.handle_monitor_update_completion_actions(update_actions);
4742                                                 }
4743                                         }
4744                                 },
4745                         }
4746                 }
4747                 NotifyOption::DoPersist
4748         }
4749
4750         #[cfg(any(test, feature = "_test_utils"))]
4751         /// Process background events, for functional testing
4752         pub fn test_process_background_events(&self) {
4753                 let _lck = self.total_consistency_lock.read().unwrap();
4754                 let _ = self.process_background_events();
4755         }
4756
4757         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4758                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4759                 // If the feerate has decreased by less than half, don't bother
4760                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4761                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4762                                 log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4763                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4764                         }
4765                         return NotifyOption::SkipPersistNoEvents;
4766                 }
4767                 if !chan.context.is_live() {
4768                         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).",
4769                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4770                         return NotifyOption::SkipPersistNoEvents;
4771                 }
4772                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4773                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4774
4775                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4776                 NotifyOption::DoPersist
4777         }
4778
4779         #[cfg(fuzzing)]
4780         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4781         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4782         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4783         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4784         pub fn maybe_update_chan_fees(&self) {
4785                 PersistenceNotifierGuard::optionally_notify(self, || {
4786                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4787
4788                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4789                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4790
4791                         let per_peer_state = self.per_peer_state.read().unwrap();
4792                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4793                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4794                                 let peer_state = &mut *peer_state_lock;
4795                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4796                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4797                                 ) {
4798                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4799                                                 min_mempool_feerate
4800                                         } else {
4801                                                 normal_feerate
4802                                         };
4803                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4804                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4805                                 }
4806                         }
4807
4808                         should_persist
4809                 });
4810         }
4811
4812         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4813         ///
4814         /// This currently includes:
4815         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4816         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4817         ///    than a minute, informing the network that they should no longer attempt to route over
4818         ///    the channel.
4819         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4820         ///    with the current [`ChannelConfig`].
4821         ///  * Removing peers which have disconnected but and no longer have any channels.
4822         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4823         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4824         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4825         ///    The latter is determined using the system clock in `std` and the block time minus two
4826         ///    hours in `no-std`.
4827         ///
4828         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4829         /// estimate fetches.
4830         ///
4831         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4832         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4833         pub fn timer_tick_occurred(&self) {
4834                 PersistenceNotifierGuard::optionally_notify(self, || {
4835                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4836
4837                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4838                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4839
4840                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4841                         let mut timed_out_mpp_htlcs = Vec::new();
4842                         let mut pending_peers_awaiting_removal = Vec::new();
4843                         let mut shutdown_channels = Vec::new();
4844
4845                         let mut process_unfunded_channel_tick = |
4846                                 chan_id: &ChannelId,
4847                                 context: &mut ChannelContext<SP>,
4848                                 unfunded_context: &mut UnfundedChannelContext,
4849                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4850                                 counterparty_node_id: PublicKey,
4851                         | {
4852                                 context.maybe_expire_prev_config();
4853                                 if unfunded_context.should_expire_unfunded_channel() {
4854                                         log_error!(self.logger,
4855                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4856                                         update_maps_on_chan_removal!(self, &context);
4857                                         self.issue_channel_close_events(&context, ClosureReason::HolderForceClosed);
4858                                         shutdown_channels.push(context.force_shutdown(false));
4859                                         pending_msg_events.push(MessageSendEvent::HandleError {
4860                                                 node_id: counterparty_node_id,
4861                                                 action: msgs::ErrorAction::SendErrorMessage {
4862                                                         msg: msgs::ErrorMessage {
4863                                                                 channel_id: *chan_id,
4864                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4865                                                         },
4866                                                 },
4867                                         });
4868                                         false
4869                                 } else {
4870                                         true
4871                                 }
4872                         };
4873
4874                         {
4875                                 let per_peer_state = self.per_peer_state.read().unwrap();
4876                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4877                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4878                                         let peer_state = &mut *peer_state_lock;
4879                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4880                                         let counterparty_node_id = *counterparty_node_id;
4881                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4882                                                 match phase {
4883                                                         ChannelPhase::Funded(chan) => {
4884                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4885                                                                         min_mempool_feerate
4886                                                                 } else {
4887                                                                         normal_feerate
4888                                                                 };
4889                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4890                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4891
4892                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4893                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4894                                                                         handle_errors.push((Err(err), counterparty_node_id));
4895                                                                         if needs_close { return false; }
4896                                                                 }
4897
4898                                                                 match chan.channel_update_status() {
4899                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4900                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4901                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4902                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4903                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4904                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4905                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4906                                                                                 n += 1;
4907                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4908                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4909                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4910                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4911                                                                                                         msg: update
4912                                                                                                 });
4913                                                                                         }
4914                                                                                         should_persist = NotifyOption::DoPersist;
4915                                                                                 } else {
4916                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4917                                                                                 }
4918                                                                         },
4919                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4920                                                                                 n += 1;
4921                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4922                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4923                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4924                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4925                                                                                                         msg: update
4926                                                                                                 });
4927                                                                                         }
4928                                                                                         should_persist = NotifyOption::DoPersist;
4929                                                                                 } else {
4930                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4931                                                                                 }
4932                                                                         },
4933                                                                         _ => {},
4934                                                                 }
4935
4936                                                                 chan.context.maybe_expire_prev_config();
4937
4938                                                                 if chan.should_disconnect_peer_awaiting_response() {
4939                                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4940                                                                                         counterparty_node_id, chan_id);
4941                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4942                                                                                 node_id: counterparty_node_id,
4943                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4944                                                                                         msg: msgs::WarningMessage {
4945                                                                                                 channel_id: *chan_id,
4946                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4947                                                                                         },
4948                                                                                 },
4949                                                                         });
4950                                                                 }
4951
4952                                                                 true
4953                                                         },
4954                                                         ChannelPhase::UnfundedInboundV1(chan) => {
4955                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4956                                                                         pending_msg_events, counterparty_node_id)
4957                                                         },
4958                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
4959                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4960                                                                         pending_msg_events, counterparty_node_id)
4961                                                         },
4962                                                 }
4963                                         });
4964
4965                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4966                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4967                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
4968                                                         peer_state.pending_msg_events.push(
4969                                                                 events::MessageSendEvent::HandleError {
4970                                                                         node_id: counterparty_node_id,
4971                                                                         action: msgs::ErrorAction::SendErrorMessage {
4972                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4973                                                                         },
4974                                                                 }
4975                                                         );
4976                                                 }
4977                                         }
4978                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4979
4980                                         if peer_state.ok_to_remove(true) {
4981                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4982                                         }
4983                                 }
4984                         }
4985
4986                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4987                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4988                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4989                         // we therefore need to remove the peer from `peer_state` separately.
4990                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4991                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4992                         // negative effects on parallelism as much as possible.
4993                         if pending_peers_awaiting_removal.len() > 0 {
4994                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4995                                 for counterparty_node_id in pending_peers_awaiting_removal {
4996                                         match per_peer_state.entry(counterparty_node_id) {
4997                                                 hash_map::Entry::Occupied(entry) => {
4998                                                         // Remove the entry if the peer is still disconnected and we still
4999                                                         // have no channels to the peer.
5000                                                         let remove_entry = {
5001                                                                 let peer_state = entry.get().lock().unwrap();
5002                                                                 peer_state.ok_to_remove(true)
5003                                                         };
5004                                                         if remove_entry {
5005                                                                 entry.remove_entry();
5006                                                         }
5007                                                 },
5008                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
5009                                         }
5010                                 }
5011                         }
5012
5013                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
5014                                 if payment.htlcs.is_empty() {
5015                                         // This should be unreachable
5016                                         debug_assert!(false);
5017                                         return false;
5018                                 }
5019                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
5020                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
5021                                         // In this case we're not going to handle any timeouts of the parts here.
5022                                         // This condition determining whether the MPP is complete here must match
5023                                         // exactly the condition used in `process_pending_htlc_forwards`.
5024                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5025                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5026                                         {
5027                                                 return true;
5028                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5029                                                 htlc.timer_ticks += 1;
5030                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5031                                         }) {
5032                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5033                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5034                                                 return false;
5035                                         }
5036                                 }
5037                                 true
5038                         });
5039
5040                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5041                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5042                                 let reason = HTLCFailReason::from_failure_code(23);
5043                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5044                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5045                         }
5046
5047                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5048                                 let _ = handle_error!(self, err, counterparty_node_id);
5049                         }
5050
5051                         for shutdown_res in shutdown_channels {
5052                                 self.finish_close_channel(shutdown_res);
5053                         }
5054
5055                         #[cfg(feature = "std")]
5056                         let duration_since_epoch = std::time::SystemTime::now()
5057                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5058                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5059                         #[cfg(not(feature = "std"))]
5060                         let duration_since_epoch = Duration::from_secs(
5061                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5062                         );
5063
5064                         self.pending_outbound_payments.remove_stale_payments(
5065                                 duration_since_epoch, &self.pending_events
5066                         );
5067
5068                         // Technically we don't need to do this here, but if we have holding cell entries in a
5069                         // channel that need freeing, it's better to do that here and block a background task
5070                         // than block the message queueing pipeline.
5071                         if self.check_free_holding_cells() {
5072                                 should_persist = NotifyOption::DoPersist;
5073                         }
5074
5075                         should_persist
5076                 });
5077         }
5078
5079         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5080         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5081         /// along the path (including in our own channel on which we received it).
5082         ///
5083         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5084         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5085         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5086         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5087         ///
5088         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5089         /// [`ChannelManager::claim_funds`]), you should still monitor for
5090         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5091         /// startup during which time claims that were in-progress at shutdown may be replayed.
5092         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5093                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5094         }
5095
5096         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5097         /// reason for the failure.
5098         ///
5099         /// See [`FailureCode`] for valid failure codes.
5100         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5101                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5102
5103                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5104                 if let Some(payment) = removed_source {
5105                         for htlc in payment.htlcs {
5106                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5107                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5108                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5109                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5110                         }
5111                 }
5112         }
5113
5114         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5115         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5116                 match failure_code {
5117                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5118                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5119                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5120                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5121                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5122                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5123                         },
5124                         FailureCode::InvalidOnionPayload(data) => {
5125                                 let fail_data = match data {
5126                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5127                                         None => Vec::new(),
5128                                 };
5129                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5130                         }
5131                 }
5132         }
5133
5134         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5135         /// that we want to return and a channel.
5136         ///
5137         /// This is for failures on the channel on which the HTLC was *received*, not failures
5138         /// forwarding
5139         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5140                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5141                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5142                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5143                 // an inbound SCID alias before the real SCID.
5144                 let scid_pref = if chan.context.should_announce() {
5145                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5146                 } else {
5147                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5148                 };
5149                 if let Some(scid) = scid_pref {
5150                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5151                 } else {
5152                         (0x4000|10, Vec::new())
5153                 }
5154         }
5155
5156
5157         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5158         /// that we want to return and a channel.
5159         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5160                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5161                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5162                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5163                         if desired_err_code == 0x1000 | 20 {
5164                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5165                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5166                                 0u16.write(&mut enc).expect("Writes cannot fail");
5167                         }
5168                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5169                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5170                         upd.write(&mut enc).expect("Writes cannot fail");
5171                         (desired_err_code, enc.0)
5172                 } else {
5173                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5174                         // which means we really shouldn't have gotten a payment to be forwarded over this
5175                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5176                         // PERM|no_such_channel should be fine.
5177                         (0x4000|10, Vec::new())
5178                 }
5179         }
5180
5181         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5182         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5183         // be surfaced to the user.
5184         fn fail_holding_cell_htlcs(
5185                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5186                 counterparty_node_id: &PublicKey
5187         ) {
5188                 let (failure_code, onion_failure_data) = {
5189                         let per_peer_state = self.per_peer_state.read().unwrap();
5190                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5191                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5192                                 let peer_state = &mut *peer_state_lock;
5193                                 match peer_state.channel_by_id.entry(channel_id) {
5194                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5195                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5196                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5197                                                 } else {
5198                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5199                                                         debug_assert!(false);
5200                                                         (0x4000|10, Vec::new())
5201                                                 }
5202                                         },
5203                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5204                                 }
5205                         } else { (0x4000|10, Vec::new()) }
5206                 };
5207
5208                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5209                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5210                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5211                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5212                 }
5213         }
5214
5215         /// Fails an HTLC backwards to the sender of it to us.
5216         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5217         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5218                 // Ensure that no peer state channel storage lock is held when calling this function.
5219                 // This ensures that future code doesn't introduce a lock-order requirement for
5220                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5221                 // this function with any `per_peer_state` peer lock acquired would.
5222                 #[cfg(debug_assertions)]
5223                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5224                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5225                 }
5226
5227                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5228                 //identify whether we sent it or not based on the (I presume) very different runtime
5229                 //between the branches here. We should make this async and move it into the forward HTLCs
5230                 //timer handling.
5231
5232                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5233                 // from block_connected which may run during initialization prior to the chain_monitor
5234                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5235                 match source {
5236                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5237                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5238                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5239                                         &self.pending_events, &self.logger)
5240                                 { self.push_pending_forwards_ev(); }
5241                         },
5242                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint, .. }) => {
5243                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", &payment_hash, onion_error);
5244                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
5245
5246                                 let mut push_forward_ev = false;
5247                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5248                                 if forward_htlcs.is_empty() {
5249                                         push_forward_ev = true;
5250                                 }
5251                                 match forward_htlcs.entry(*short_channel_id) {
5252                                         hash_map::Entry::Occupied(mut entry) => {
5253                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
5254                                         },
5255                                         hash_map::Entry::Vacant(entry) => {
5256                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
5257                                         }
5258                                 }
5259                                 mem::drop(forward_htlcs);
5260                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5261                                 let mut pending_events = self.pending_events.lock().unwrap();
5262                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5263                                         prev_channel_id: outpoint.to_channel_id(),
5264                                         failed_next_destination: destination,
5265                                 }, None));
5266                         },
5267                 }
5268         }
5269
5270         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5271         /// [`MessageSendEvent`]s needed to claim the payment.
5272         ///
5273         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5274         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5275         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5276         /// successful. It will generally be available in the next [`process_pending_events`] call.
5277         ///
5278         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5279         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5280         /// event matches your expectation. If you fail to do so and call this method, you may provide
5281         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5282         ///
5283         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5284         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5285         /// [`claim_funds_with_known_custom_tlvs`].
5286         ///
5287         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5288         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5289         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5290         /// [`process_pending_events`]: EventsProvider::process_pending_events
5291         /// [`create_inbound_payment`]: Self::create_inbound_payment
5292         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5293         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5294         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5295                 self.claim_payment_internal(payment_preimage, false);
5296         }
5297
5298         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5299         /// even type numbers.
5300         ///
5301         /// # Note
5302         ///
5303         /// You MUST check you've understood all even TLVs before using this to
5304         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5305         ///
5306         /// [`claim_funds`]: Self::claim_funds
5307         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5308                 self.claim_payment_internal(payment_preimage, true);
5309         }
5310
5311         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5312                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5313
5314                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5315
5316                 let mut sources = {
5317                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5318                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5319                                 let mut receiver_node_id = self.our_network_pubkey;
5320                                 for htlc in payment.htlcs.iter() {
5321                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5322                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5323                                                         .expect("Failed to get node_id for phantom node recipient");
5324                                                 receiver_node_id = phantom_pubkey;
5325                                                 break;
5326                                         }
5327                                 }
5328
5329                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5330                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5331                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5332                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5333                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5334                                 });
5335                                 if dup_purpose.is_some() {
5336                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5337                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5338                                                 &payment_hash);
5339                                 }
5340
5341                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5342                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5343                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5344                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5345                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5346                                                 mem::drop(claimable_payments);
5347                                                 for htlc in payment.htlcs {
5348                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5349                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5350                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5351                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5352                                                 }
5353                                                 return;
5354                                         }
5355                                 }
5356
5357                                 payment.htlcs
5358                         } else { return; }
5359                 };
5360                 debug_assert!(!sources.is_empty());
5361
5362                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5363                 // and when we got here we need to check that the amount we're about to claim matches the
5364                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5365                 // the MPP parts all have the same `total_msat`.
5366                 let mut claimable_amt_msat = 0;
5367                 let mut prev_total_msat = None;
5368                 let mut expected_amt_msat = None;
5369                 let mut valid_mpp = true;
5370                 let mut errs = Vec::new();
5371                 let per_peer_state = self.per_peer_state.read().unwrap();
5372                 for htlc in sources.iter() {
5373                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5374                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5375                                 debug_assert!(false);
5376                                 valid_mpp = false;
5377                                 break;
5378                         }
5379                         prev_total_msat = Some(htlc.total_msat);
5380
5381                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5382                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5383                                 debug_assert!(false);
5384                                 valid_mpp = false;
5385                                 break;
5386                         }
5387                         expected_amt_msat = htlc.total_value_received;
5388                         claimable_amt_msat += htlc.value;
5389                 }
5390                 mem::drop(per_peer_state);
5391                 if sources.is_empty() || expected_amt_msat.is_none() {
5392                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5393                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5394                         return;
5395                 }
5396                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5397                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5398                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5399                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5400                         return;
5401                 }
5402                 if valid_mpp {
5403                         for htlc in sources.drain(..) {
5404                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5405                                         htlc.prev_hop, payment_preimage,
5406                                         |_, definitely_duplicate| {
5407                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5408                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5409                                         }
5410                                 ) {
5411                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5412                                                 // We got a temporary failure updating monitor, but will claim the
5413                                                 // HTLC when the monitor updating is restored (or on chain).
5414                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5415                                         } else { errs.push((pk, err)); }
5416                                 }
5417                         }
5418                 }
5419                 if !valid_mpp {
5420                         for htlc in sources.drain(..) {
5421                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5422                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5423                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5424                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5425                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5426                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5427                         }
5428                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5429                 }
5430
5431                 // Now we can handle any errors which were generated.
5432                 for (counterparty_node_id, err) in errs.drain(..) {
5433                         let res: Result<(), _> = Err(err);
5434                         let _ = handle_error!(self, res, counterparty_node_id);
5435                 }
5436         }
5437
5438         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5439                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5440         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5441                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5442
5443                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5444                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5445                 // `BackgroundEvent`s.
5446                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5447
5448                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5449                 // the required mutexes are not held before we start.
5450                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5451                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5452
5453                 {
5454                         let per_peer_state = self.per_peer_state.read().unwrap();
5455                         let chan_id = prev_hop.outpoint.to_channel_id();
5456                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5457                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5458                                 None => None
5459                         };
5460
5461                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5462                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5463                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5464                         ).unwrap_or(None);
5465
5466                         if peer_state_opt.is_some() {
5467                                 let mut peer_state_lock = peer_state_opt.unwrap();
5468                                 let peer_state = &mut *peer_state_lock;
5469                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5470                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5471                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5472                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5473
5474                                                 match fulfill_res {
5475                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5476                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5477                                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5478                                                                                 chan_id, action);
5479                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5480                                                                 }
5481                                                                 if !during_init {
5482                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5483                                                                                 peer_state, per_peer_state, chan);
5484                                                                 } else {
5485                                                                         // If we're running during init we cannot update a monitor directly -
5486                                                                         // they probably haven't actually been loaded yet. Instead, push the
5487                                                                         // monitor update as a background event.
5488                                                                         self.pending_background_events.lock().unwrap().push(
5489                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5490                                                                                         counterparty_node_id,
5491                                                                                         funding_txo: prev_hop.outpoint,
5492                                                                                         update: monitor_update.clone(),
5493                                                                                 });
5494                                                                 }
5495                                                         }
5496                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5497                                                                 let action = if let Some(action) = completion_action(None, true) {
5498                                                                         action
5499                                                                 } else {
5500                                                                         return Ok(());
5501                                                                 };
5502                                                                 mem::drop(peer_state_lock);
5503
5504                                                                 log_trace!(self.logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5505                                                                         chan_id, action);
5506                                                                 let (node_id, funding_outpoint, blocker) =
5507                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5508                                                                         downstream_counterparty_node_id: node_id,
5509                                                                         downstream_funding_outpoint: funding_outpoint,
5510                                                                         blocking_action: blocker,
5511                                                                 } = action {
5512                                                                         (node_id, funding_outpoint, blocker)
5513                                                                 } else {
5514                                                                         debug_assert!(false,
5515                                                                                 "Duplicate claims should always free another channel immediately");
5516                                                                         return Ok(());
5517                                                                 };
5518                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5519                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5520                                                                         if let Some(blockers) = peer_state
5521                                                                                 .actions_blocking_raa_monitor_updates
5522                                                                                 .get_mut(&funding_outpoint.to_channel_id())
5523                                                                         {
5524                                                                                 let mut found_blocker = false;
5525                                                                                 blockers.retain(|iter| {
5526                                                                                         // Note that we could actually be blocked, in
5527                                                                                         // which case we need to only remove the one
5528                                                                                         // blocker which was added duplicatively.
5529                                                                                         let first_blocker = !found_blocker;
5530                                                                                         if *iter == blocker { found_blocker = true; }
5531                                                                                         *iter != blocker || !first_blocker
5532                                                                                 });
5533                                                                                 debug_assert!(found_blocker);
5534                                                                         }
5535                                                                 } else {
5536                                                                         debug_assert!(false);
5537                                                                 }
5538                                                         }
5539                                                 }
5540                                         }
5541                                         return Ok(());
5542                                 }
5543                         }
5544                 }
5545                 let preimage_update = ChannelMonitorUpdate {
5546                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5547                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5548                                 payment_preimage,
5549                         }],
5550                 };
5551
5552                 if !during_init {
5553                         // We update the ChannelMonitor on the backward link, after
5554                         // receiving an `update_fulfill_htlc` from the forward link.
5555                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5556                         if update_res != ChannelMonitorUpdateStatus::Completed {
5557                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5558                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5559                                 // channel, or we must have an ability to receive the same event and try
5560                                 // again on restart.
5561                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5562                                         payment_preimage, update_res);
5563                         }
5564                 } else {
5565                         // If we're running during init we cannot update a monitor directly - they probably
5566                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5567                         // event.
5568                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5569                         // channel is already closed) we need to ultimately handle the monitor update
5570                         // completion action only after we've completed the monitor update. This is the only
5571                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5572                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5573                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5574                         // complete the monitor update completion action from `completion_action`.
5575                         self.pending_background_events.lock().unwrap().push(
5576                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5577                                         prev_hop.outpoint, preimage_update,
5578                                 )));
5579                 }
5580                 // Note that we do process the completion action here. This totally could be a
5581                 // duplicate claim, but we have no way of knowing without interrogating the
5582                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5583                 // generally always allowed to be duplicative (and it's specifically noted in
5584                 // `PaymentForwarded`).
5585                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5586                 Ok(())
5587         }
5588
5589         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5590                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5591         }
5592
5593         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5594                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5595                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5596         ) {
5597                 match source {
5598                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5599                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5600                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5601                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5602                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5603                                 }
5604                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5605                                         channel_funding_outpoint: next_channel_outpoint,
5606                                         counterparty_node_id: path.hops[0].pubkey,
5607                                 };
5608                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5609                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5610                                         &self.logger);
5611                         },
5612                         HTLCSource::PreviousHopData(hop_data) => {
5613                                 let prev_outpoint = hop_data.outpoint;
5614                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5615                                 #[cfg(debug_assertions)]
5616                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5617                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5618                                         |htlc_claim_value_msat, definitely_duplicate| {
5619                                                 let chan_to_release =
5620                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5621                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5622                                                         } else {
5623                                                                 // We can only get `None` here if we are processing a
5624                                                                 // `ChannelMonitor`-originated event, in which case we
5625                                                                 // don't care about ensuring we wake the downstream
5626                                                                 // channel's monitor updating - the channel is already
5627                                                                 // closed.
5628                                                                 None
5629                                                         };
5630
5631                                                 if definitely_duplicate && startup_replay {
5632                                                         // On startup we may get redundant claims which are related to
5633                                                         // monitor updates still in flight. In that case, we shouldn't
5634                                                         // immediately free, but instead let that monitor update complete
5635                                                         // in the background.
5636                                                         #[cfg(debug_assertions)] {
5637                                                                 let background_events = self.pending_background_events.lock().unwrap();
5638                                                                 // There should be a `BackgroundEvent` pending...
5639                                                                 assert!(background_events.iter().any(|ev| {
5640                                                                         match ev {
5641                                                                                 // to apply a monitor update that blocked the claiming channel,
5642                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5643                                                                                         funding_txo, update, ..
5644                                                                                 } => {
5645                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5646                                                                                                 assert!(update.updates.iter().any(|upd|
5647                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5648                                                                                                                 payment_preimage: update_preimage
5649                                                                                                         } = upd {
5650                                                                                                                 payment_preimage == *update_preimage
5651                                                                                                         } else { false }
5652                                                                                                 ), "{:?}", update);
5653                                                                                                 true
5654                                                                                         } else { false }
5655                                                                                 },
5656                                                                                 // or the channel we'd unblock is already closed,
5657                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5658                                                                                         (funding_txo, monitor_update)
5659                                                                                 ) => {
5660                                                                                         if *funding_txo == next_channel_outpoint {
5661                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5662                                                                                                 assert!(matches!(
5663                                                                                                         monitor_update.updates[0],
5664                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5665                                                                                                 ));
5666                                                                                                 true
5667                                                                                         } else { false }
5668                                                                                 },
5669                                                                                 // or the monitor update has completed and will unblock
5670                                                                                 // immediately once we get going.
5671                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5672                                                                                         channel_id, ..
5673                                                                                 } =>
5674                                                                                         *channel_id == claiming_chan_funding_outpoint.to_channel_id(),
5675                                                                         }
5676                                                                 }), "{:?}", *background_events);
5677                                                         }
5678                                                         None
5679                                                 } else if definitely_duplicate {
5680                                                         if let Some(other_chan) = chan_to_release {
5681                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5682                                                                         downstream_counterparty_node_id: other_chan.0,
5683                                                                         downstream_funding_outpoint: other_chan.1,
5684                                                                         blocking_action: other_chan.2,
5685                                                                 })
5686                                                         } else { None }
5687                                                 } else {
5688                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5689                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5690                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5691                                                                 } else { None }
5692                                                         } else { None };
5693                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5694                                                                 event: events::Event::PaymentForwarded {
5695                                                                         fee_earned_msat,
5696                                                                         claim_from_onchain_tx: from_onchain,
5697                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5698                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5699                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5700                                                                 },
5701                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5702                                                         })
5703                                                 }
5704                                         });
5705                                 if let Err((pk, err)) = res {
5706                                         let result: Result<(), _> = Err(err);
5707                                         let _ = handle_error!(self, result, pk);
5708                                 }
5709                         },
5710                 }
5711         }
5712
5713         /// Gets the node_id held by this ChannelManager
5714         pub fn get_our_node_id(&self) -> PublicKey {
5715                 self.our_network_pubkey.clone()
5716         }
5717
5718         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5719                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5720                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5721                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5722
5723                 for action in actions.into_iter() {
5724                         match action {
5725                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5726                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5727                                         if let Some(ClaimingPayment {
5728                                                 amount_msat,
5729                                                 payment_purpose: purpose,
5730                                                 receiver_node_id,
5731                                                 htlcs,
5732                                                 sender_intended_value: sender_intended_total_msat,
5733                                         }) = payment {
5734                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5735                                                         payment_hash,
5736                                                         purpose,
5737                                                         amount_msat,
5738                                                         receiver_node_id: Some(receiver_node_id),
5739                                                         htlcs,
5740                                                         sender_intended_total_msat,
5741                                                 }, None));
5742                                         }
5743                                 },
5744                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5745                                         event, downstream_counterparty_and_funding_outpoint
5746                                 } => {
5747                                         self.pending_events.lock().unwrap().push_back((event, None));
5748                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5749                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5750                                         }
5751                                 },
5752                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5753                                         downstream_counterparty_node_id, downstream_funding_outpoint, blocking_action,
5754                                 } => {
5755                                         self.handle_monitor_update_release(
5756                                                 downstream_counterparty_node_id,
5757                                                 downstream_funding_outpoint,
5758                                                 Some(blocking_action),
5759                                         );
5760                                 },
5761                         }
5762                 }
5763         }
5764
5765         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5766         /// update completion.
5767         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5768                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5769                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5770                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5771                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5772         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5773                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5774                         &channel.context.channel_id(),
5775                         if raa.is_some() { "an" } else { "no" },
5776                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5777                         if funding_broadcastable.is_some() { "" } else { "not " },
5778                         if channel_ready.is_some() { "sending" } else { "without" },
5779                         if announcement_sigs.is_some() { "sending" } else { "without" });
5780
5781                 let mut htlc_forwards = None;
5782
5783                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5784                 if !pending_forwards.is_empty() {
5785                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5786                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5787                 }
5788
5789                 if let Some(msg) = channel_ready {
5790                         send_channel_ready!(self, pending_msg_events, channel, msg);
5791                 }
5792                 if let Some(msg) = announcement_sigs {
5793                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5794                                 node_id: counterparty_node_id,
5795                                 msg,
5796                         });
5797                 }
5798
5799                 macro_rules! handle_cs { () => {
5800                         if let Some(update) = commitment_update {
5801                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5802                                         node_id: counterparty_node_id,
5803                                         updates: update,
5804                                 });
5805                         }
5806                 } }
5807                 macro_rules! handle_raa { () => {
5808                         if let Some(revoke_and_ack) = raa {
5809                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5810                                         node_id: counterparty_node_id,
5811                                         msg: revoke_and_ack,
5812                                 });
5813                         }
5814                 } }
5815                 match order {
5816                         RAACommitmentOrder::CommitmentFirst => {
5817                                 handle_cs!();
5818                                 handle_raa!();
5819                         },
5820                         RAACommitmentOrder::RevokeAndACKFirst => {
5821                                 handle_raa!();
5822                                 handle_cs!();
5823                         },
5824                 }
5825
5826                 if let Some(tx) = funding_broadcastable {
5827                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5828                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5829                 }
5830
5831                 {
5832                         let mut pending_events = self.pending_events.lock().unwrap();
5833                         emit_channel_pending_event!(pending_events, channel);
5834                         emit_channel_ready_event!(pending_events, channel);
5835                 }
5836
5837                 htlc_forwards
5838         }
5839
5840         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5841                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5842
5843                 let counterparty_node_id = match counterparty_node_id {
5844                         Some(cp_id) => cp_id.clone(),
5845                         None => {
5846                                 // TODO: Once we can rely on the counterparty_node_id from the
5847                                 // monitor event, this and the id_to_peer map should be removed.
5848                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5849                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5850                                         Some(cp_id) => cp_id.clone(),
5851                                         None => return,
5852                                 }
5853                         }
5854                 };
5855                 let per_peer_state = self.per_peer_state.read().unwrap();
5856                 let mut peer_state_lock;
5857                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5858                 if peer_state_mutex_opt.is_none() { return }
5859                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5860                 let peer_state = &mut *peer_state_lock;
5861                 let channel =
5862                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5863                                 chan
5864                         } else {
5865                                 let update_actions = peer_state.monitor_update_blocked_actions
5866                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5867                                 mem::drop(peer_state_lock);
5868                                 mem::drop(per_peer_state);
5869                                 self.handle_monitor_update_completion_actions(update_actions);
5870                                 return;
5871                         };
5872                 let remaining_in_flight =
5873                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5874                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5875                                 pending.len()
5876                         } else { 0 };
5877                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5878                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5879                         remaining_in_flight);
5880                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5881                         return;
5882                 }
5883                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5884         }
5885
5886         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5887         ///
5888         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5889         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5890         /// the channel.
5891         ///
5892         /// The `user_channel_id` parameter will be provided back in
5893         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5894         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5895         ///
5896         /// Note that this method will return an error and reject the channel, if it requires support
5897         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5898         /// used to accept such channels.
5899         ///
5900         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5901         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5902         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5903                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5904         }
5905
5906         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5907         /// it as confirmed immediately.
5908         ///
5909         /// The `user_channel_id` parameter will be provided back in
5910         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5911         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5912         ///
5913         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5914         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5915         ///
5916         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5917         /// transaction and blindly assumes that it will eventually confirm.
5918         ///
5919         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5920         /// does not pay to the correct script the correct amount, *you will lose funds*.
5921         ///
5922         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5923         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5924         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5925                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5926         }
5927
5928         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5929                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5930
5931                 let peers_without_funded_channels =
5932                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5933                 let per_peer_state = self.per_peer_state.read().unwrap();
5934                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5935                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5936                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5937                 let peer_state = &mut *peer_state_lock;
5938                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5939
5940                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5941                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5942                 // that we can delay allocating the SCID until after we're sure that the checks below will
5943                 // succeed.
5944                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5945                         Some(unaccepted_channel) => {
5946                                 let best_block_height = self.best_block.read().unwrap().height();
5947                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5948                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5949                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5950                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5951                         }
5952                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5953                 }?;
5954
5955                 if accept_0conf {
5956                         // This should have been correctly configured by the call to InboundV1Channel::new.
5957                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5958                 } else if channel.context.get_channel_type().requires_zero_conf() {
5959                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5960                                 node_id: channel.context.get_counterparty_node_id(),
5961                                 action: msgs::ErrorAction::SendErrorMessage{
5962                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5963                                 }
5964                         };
5965                         peer_state.pending_msg_events.push(send_msg_err_event);
5966                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5967                 } else {
5968                         // If this peer already has some channels, a new channel won't increase our number of peers
5969                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5970                         // channels per-peer we can accept channels from a peer with existing ones.
5971                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5972                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5973                                         node_id: channel.context.get_counterparty_node_id(),
5974                                         action: msgs::ErrorAction::SendErrorMessage{
5975                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5976                                         }
5977                                 };
5978                                 peer_state.pending_msg_events.push(send_msg_err_event);
5979                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5980                         }
5981                 }
5982
5983                 // Now that we know we have a channel, assign an outbound SCID alias.
5984                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5985                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5986
5987                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5988                         node_id: channel.context.get_counterparty_node_id(),
5989                         msg: channel.accept_inbound_channel(),
5990                 });
5991
5992                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
5993
5994                 Ok(())
5995         }
5996
5997         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5998         /// or 0-conf channels.
5999         ///
6000         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6001         /// non-0-conf channels we have with the peer.
6002         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6003         where Filter: Fn(&PeerState<SP>) -> bool {
6004                 let mut peers_without_funded_channels = 0;
6005                 let best_block_height = self.best_block.read().unwrap().height();
6006                 {
6007                         let peer_state_lock = self.per_peer_state.read().unwrap();
6008                         for (_, peer_mtx) in peer_state_lock.iter() {
6009                                 let peer = peer_mtx.lock().unwrap();
6010                                 if !maybe_count_peer(&*peer) { continue; }
6011                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6012                                 if num_unfunded_channels == peer.total_channel_count() {
6013                                         peers_without_funded_channels += 1;
6014                                 }
6015                         }
6016                 }
6017                 return peers_without_funded_channels;
6018         }
6019
6020         fn unfunded_channel_count(
6021                 peer: &PeerState<SP>, best_block_height: u32
6022         ) -> usize {
6023                 let mut num_unfunded_channels = 0;
6024                 for (_, phase) in peer.channel_by_id.iter() {
6025                         match phase {
6026                                 ChannelPhase::Funded(chan) => {
6027                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6028                                         // which have not yet had any confirmations on-chain.
6029                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6030                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6031                                         {
6032                                                 num_unfunded_channels += 1;
6033                                         }
6034                                 },
6035                                 ChannelPhase::UnfundedInboundV1(chan) => {
6036                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6037                                                 num_unfunded_channels += 1;
6038                                         }
6039                                 },
6040                                 ChannelPhase::UnfundedOutboundV1(_) => {
6041                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6042                                         continue;
6043                                 }
6044                         }
6045                 }
6046                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6047         }
6048
6049         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6050                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6051                 // likely to be lost on restart!
6052                 if msg.chain_hash != self.chain_hash {
6053                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
6054                 }
6055
6056                 if !self.default_configuration.accept_inbound_channels {
6057                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6058                 }
6059
6060                 // Get the number of peers with channels, but without funded ones. We don't care too much
6061                 // about peers that never open a channel, so we filter by peers that have at least one
6062                 // channel, and then limit the number of those with unfunded channels.
6063                 let channeled_peers_without_funding =
6064                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6065
6066                 let per_peer_state = self.per_peer_state.read().unwrap();
6067                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6068                     .ok_or_else(|| {
6069                                 debug_assert!(false);
6070                                 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())
6071                         })?;
6072                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6073                 let peer_state = &mut *peer_state_lock;
6074
6075                 // If this peer already has some channels, a new channel won't increase our number of peers
6076                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6077                 // channels per-peer we can accept channels from a peer with existing ones.
6078                 if peer_state.total_channel_count() == 0 &&
6079                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6080                         !self.default_configuration.manually_accept_inbound_channels
6081                 {
6082                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6083                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6084                                 msg.temporary_channel_id.clone()));
6085                 }
6086
6087                 let best_block_height = self.best_block.read().unwrap().height();
6088                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6089                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6090                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6091                                 msg.temporary_channel_id.clone()));
6092                 }
6093
6094                 let channel_id = msg.temporary_channel_id;
6095                 let channel_exists = peer_state.has_channel(&channel_id);
6096                 if channel_exists {
6097                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
6098                 }
6099
6100                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6101                 if self.default_configuration.manually_accept_inbound_channels {
6102                         let mut pending_events = self.pending_events.lock().unwrap();
6103                         pending_events.push_back((events::Event::OpenChannelRequest {
6104                                 temporary_channel_id: msg.temporary_channel_id.clone(),
6105                                 counterparty_node_id: counterparty_node_id.clone(),
6106                                 funding_satoshis: msg.funding_satoshis,
6107                                 push_msat: msg.push_msat,
6108                                 channel_type: msg.channel_type.clone().unwrap(),
6109                         }, None));
6110                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6111                                 open_channel_msg: msg.clone(),
6112                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6113                         });
6114                         return Ok(());
6115                 }
6116
6117                 // Otherwise create the channel right now.
6118                 let mut random_bytes = [0u8; 16];
6119                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6120                 let user_channel_id = u128::from_be_bytes(random_bytes);
6121                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6122                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6123                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6124                 {
6125                         Err(e) => {
6126                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
6127                         },
6128                         Ok(res) => res
6129                 };
6130
6131                 let channel_type = channel.context.get_channel_type();
6132                 if channel_type.requires_zero_conf() {
6133                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6134                 }
6135                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6136                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
6137                 }
6138
6139                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6140                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6141
6142                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6143                         node_id: counterparty_node_id.clone(),
6144                         msg: channel.accept_inbound_channel(),
6145                 });
6146                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6147                 Ok(())
6148         }
6149
6150         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6151                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6152                 // likely to be lost on restart!
6153                 let (value, output_script, user_id) = {
6154                         let per_peer_state = self.per_peer_state.read().unwrap();
6155                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6156                                 .ok_or_else(|| {
6157                                         debug_assert!(false);
6158                                         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)
6159                                 })?;
6160                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6161                         let peer_state = &mut *peer_state_lock;
6162                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6163                                 hash_map::Entry::Occupied(mut phase) => {
6164                                         match phase.get_mut() {
6165                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6166                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6167                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6168                                                 },
6169                                                 _ => {
6170                                                         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));
6171                                                 }
6172                                         }
6173                                 },
6174                                 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))
6175                         }
6176                 };
6177                 let mut pending_events = self.pending_events.lock().unwrap();
6178                 pending_events.push_back((events::Event::FundingGenerationReady {
6179                         temporary_channel_id: msg.temporary_channel_id,
6180                         counterparty_node_id: *counterparty_node_id,
6181                         channel_value_satoshis: value,
6182                         output_script,
6183                         user_channel_id: user_id,
6184                 }, None));
6185                 Ok(())
6186         }
6187
6188         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6189                 let best_block = *self.best_block.read().unwrap();
6190
6191                 let per_peer_state = self.per_peer_state.read().unwrap();
6192                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6193                         .ok_or_else(|| {
6194                                 debug_assert!(false);
6195                                 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)
6196                         })?;
6197
6198                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6199                 let peer_state = &mut *peer_state_lock;
6200                 let (chan, funding_msg, monitor) =
6201                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6202                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6203                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
6204                                                 Ok(res) => res,
6205                                                 Err((mut inbound_chan, err)) => {
6206                                                         // We've already removed this inbound channel from the map in `PeerState`
6207                                                         // above so at this point we just need to clean up any lingering entries
6208                                                         // concerning this channel as it is safe to do so.
6209                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
6210                                                         let user_id = inbound_chan.context.get_user_id();
6211                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
6212                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
6213                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
6214                                                 },
6215                                         }
6216                                 },
6217                                 Some(ChannelPhase::Funded(_)) | Some(ChannelPhase::UnfundedOutboundV1(_)) => {
6218                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id));
6219                                 },
6220                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id))
6221                         };
6222
6223                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
6224                         hash_map::Entry::Occupied(_) => {
6225                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
6226                         },
6227                         hash_map::Entry::Vacant(e) => {
6228                                 let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
6229                                 match id_to_peer_lock.entry(chan.context.channel_id()) {
6230                                         hash_map::Entry::Occupied(_) => {
6231                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
6232                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6233                                                         funding_msg.channel_id))
6234                                         },
6235                                         hash_map::Entry::Vacant(i_e) => {
6236                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6237                                                 if let Ok(persist_state) = monitor_res {
6238                                                         i_e.insert(chan.context.get_counterparty_node_id());
6239                                                         mem::drop(id_to_peer_lock);
6240
6241                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6242                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6243                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6244                                                         // until we have persisted our monitor.
6245                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6246                                                                 node_id: counterparty_node_id.clone(),
6247                                                                 msg: funding_msg,
6248                                                         });
6249
6250                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6251                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6252                                                                         per_peer_state, chan, INITIAL_MONITOR);
6253                                                         } else {
6254                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6255                                                         }
6256                                                         Ok(())
6257                                                 } else {
6258                                                         log_error!(self.logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6259                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6260                                                                 "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6261                                                                 funding_msg.channel_id));
6262                                                 }
6263                                         }
6264                                 }
6265                         }
6266                 }
6267         }
6268
6269         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6270                 let best_block = *self.best_block.read().unwrap();
6271                 let per_peer_state = self.per_peer_state.read().unwrap();
6272                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6273                         .ok_or_else(|| {
6274                                 debug_assert!(false);
6275                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6276                         })?;
6277
6278                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6279                 let peer_state = &mut *peer_state_lock;
6280                 match peer_state.channel_by_id.entry(msg.channel_id) {
6281                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6282                                 match chan_phase_entry.get_mut() {
6283                                         ChannelPhase::Funded(ref mut chan) => {
6284                                                 let monitor = try_chan_phase_entry!(self,
6285                                                         chan.funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan_phase_entry);
6286                                                 if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6287                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6288                                                         Ok(())
6289                                                 } else {
6290                                                         try_chan_phase_entry!(self, Err(ChannelError::Close("Channel funding outpoint was a duplicate".to_owned())), chan_phase_entry)
6291                                                 }
6292                                         },
6293                                         _ => {
6294                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6295                                         },
6296                                 }
6297                         },
6298                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6299                 }
6300         }
6301
6302         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6303                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6304                 // closing a channel), so any changes are likely to be lost on restart!
6305                 let per_peer_state = self.per_peer_state.read().unwrap();
6306                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6307                         .ok_or_else(|| {
6308                                 debug_assert!(false);
6309                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6310                         })?;
6311                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6312                 let peer_state = &mut *peer_state_lock;
6313                 match peer_state.channel_by_id.entry(msg.channel_id) {
6314                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6315                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6316                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6317                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
6318                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6319                                                 log_trace!(self.logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6320                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6321                                                         node_id: counterparty_node_id.clone(),
6322                                                         msg: announcement_sigs,
6323                                                 });
6324                                         } else if chan.context.is_usable() {
6325                                                 // If we're sending an announcement_signatures, we'll send the (public)
6326                                                 // channel_update after sending a channel_announcement when we receive our
6327                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6328                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6329                                                 // announcement_signatures.
6330                                                 log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6331                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6332                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6333                                                                 node_id: counterparty_node_id.clone(),
6334                                                                 msg,
6335                                                         });
6336                                                 }
6337                                         }
6338
6339                                         {
6340                                                 let mut pending_events = self.pending_events.lock().unwrap();
6341                                                 emit_channel_ready_event!(pending_events, chan);
6342                                         }
6343
6344                                         Ok(())
6345                                 } else {
6346                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6347                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6348                                 }
6349                         },
6350                         hash_map::Entry::Vacant(_) => {
6351                                 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))
6352                         }
6353                 }
6354         }
6355
6356         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6357                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6358                 let mut finish_shutdown = None;
6359                 {
6360                         let per_peer_state = self.per_peer_state.read().unwrap();
6361                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6362                                 .ok_or_else(|| {
6363                                         debug_assert!(false);
6364                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6365                                 })?;
6366                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6367                         let peer_state = &mut *peer_state_lock;
6368                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6369                                 let phase = chan_phase_entry.get_mut();
6370                                 match phase {
6371                                         ChannelPhase::Funded(chan) => {
6372                                                 if !chan.received_shutdown() {
6373                                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
6374                                                                 msg.channel_id,
6375                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6376                                                 }
6377
6378                                                 let funding_txo_opt = chan.context.get_funding_txo();
6379                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6380                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6381                                                 dropped_htlcs = htlcs;
6382
6383                                                 if let Some(msg) = shutdown {
6384                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6385                                                         // here as we don't need the monitor update to complete until we send a
6386                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6387                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6388                                                                 node_id: *counterparty_node_id,
6389                                                                 msg,
6390                                                         });
6391                                                 }
6392                                                 // Update the monitor with the shutdown script if necessary.
6393                                                 if let Some(monitor_update) = monitor_update_opt {
6394                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6395                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6396                                                 }
6397                                         },
6398                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6399                                                 let context = phase.context_mut();
6400                                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6401                                                 self.issue_channel_close_events(&context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
6402                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6403                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false));
6404                                         },
6405                                 }
6406                         } else {
6407                                 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))
6408                         }
6409                 }
6410                 for htlc_source in dropped_htlcs.drain(..) {
6411                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6412                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6413                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6414                 }
6415                 if let Some(shutdown_res) = finish_shutdown {
6416                         self.finish_close_channel(shutdown_res);
6417                 }
6418
6419                 Ok(())
6420         }
6421
6422         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6423                 let mut shutdown_result = None;
6424                 let unbroadcasted_batch_funding_txid;
6425                 let per_peer_state = self.per_peer_state.read().unwrap();
6426                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6427                         .ok_or_else(|| {
6428                                 debug_assert!(false);
6429                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6430                         })?;
6431                 let (tx, chan_option) = {
6432                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6433                         let peer_state = &mut *peer_state_lock;
6434                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6435                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6436                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6437                                                 unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
6438                                                 let (closing_signed, tx) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6439                                                 if let Some(msg) = closing_signed {
6440                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6441                                                                 node_id: counterparty_node_id.clone(),
6442                                                                 msg,
6443                                                         });
6444                                                 }
6445                                                 if tx.is_some() {
6446                                                         // We're done with this channel, we've got a signed closing transaction and
6447                                                         // will send the closing_signed back to the remote peer upon return. This
6448                                                         // also implies there are no pending HTLCs left on the channel, so we can
6449                                                         // fully delete it from tracking (the channel monitor is still around to
6450                                                         // watch for old state broadcasts)!
6451                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)))
6452                                                 } else { (tx, None) }
6453                                         } else {
6454                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6455                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6456                                         }
6457                                 },
6458                                 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))
6459                         }
6460                 };
6461                 if let Some(broadcast_tx) = tx {
6462                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
6463                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6464                 }
6465                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6466                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6467                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6468                                 let peer_state = &mut *peer_state_lock;
6469                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6470                                         msg: update
6471                                 });
6472                         }
6473                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6474                         shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
6475                 }
6476                 mem::drop(per_peer_state);
6477                 if let Some(shutdown_result) = shutdown_result {
6478                         self.finish_close_channel(shutdown_result);
6479                 }
6480                 Ok(())
6481         }
6482
6483         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6484                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6485                 //determine the state of the payment based on our response/if we forward anything/the time
6486                 //we take to respond. We should take care to avoid allowing such an attack.
6487                 //
6488                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6489                 //us repeatedly garbled in different ways, and compare our error messages, which are
6490                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6491                 //but we should prevent it anyway.
6492
6493                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6494                 // closing a channel), so any changes are likely to be lost on restart!
6495
6496                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
6497                 let per_peer_state = self.per_peer_state.read().unwrap();
6498                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6499                         .ok_or_else(|| {
6500                                 debug_assert!(false);
6501                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6502                         })?;
6503                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6504                 let peer_state = &mut *peer_state_lock;
6505                 match peer_state.channel_by_id.entry(msg.channel_id) {
6506                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6507                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6508                                         let pending_forward_info = match decoded_hop_res {
6509                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6510                                                         self.construct_pending_htlc_status(msg, shared_secret, next_hop,
6511                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt),
6512                                                 Err(e) => PendingHTLCStatus::Fail(e)
6513                                         };
6514                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6515                                                 // If the update_add is completely bogus, the call will Err and we will close,
6516                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6517                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6518                                                 match pending_forward_info {
6519                                                         PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
6520                                                                 let reason = if (error_code & 0x1000) != 0 {
6521                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6522                                                                         HTLCFailReason::reason(real_code, error_data)
6523                                                                 } else {
6524                                                                         HTLCFailReason::from_failure_code(error_code)
6525                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6526                                                                 let msg = msgs::UpdateFailHTLC {
6527                                                                         channel_id: msg.channel_id,
6528                                                                         htlc_id: msg.htlc_id,
6529                                                                         reason
6530                                                                 };
6531                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6532                                                         },
6533                                                         _ => pending_forward_info
6534                                                 }
6535                                         };
6536                                         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);
6537                                 } else {
6538                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6539                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6540                                 }
6541                         },
6542                         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))
6543                 }
6544                 Ok(())
6545         }
6546
6547         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6548                 let funding_txo;
6549                 let (htlc_source, forwarded_htlc_value) = {
6550                         let per_peer_state = self.per_peer_state.read().unwrap();
6551                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6552                                 .ok_or_else(|| {
6553                                         debug_assert!(false);
6554                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6555                                 })?;
6556                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6557                         let peer_state = &mut *peer_state_lock;
6558                         match peer_state.channel_by_id.entry(msg.channel_id) {
6559                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6560                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6561                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6562                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6563                                                         log_trace!(self.logger,
6564                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6565                                                                 msg.channel_id);
6566                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6567                                                                 .or_insert_with(Vec::new)
6568                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6569                                                 }
6570                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6571                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6572                                                 // We do this instead in the `claim_funds_internal` by attaching a
6573                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6574                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6575                                                 // process the RAA as messages are processed from single peers serially.
6576                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6577                                                 res
6578                                         } else {
6579                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6580                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6581                                         }
6582                                 },
6583                                 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))
6584                         }
6585                 };
6586                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, false, Some(*counterparty_node_id), funding_txo);
6587                 Ok(())
6588         }
6589
6590         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6591                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6592                 // closing a channel), so any changes are likely to be lost on restart!
6593                 let per_peer_state = self.per_peer_state.read().unwrap();
6594                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6595                         .ok_or_else(|| {
6596                                 debug_assert!(false);
6597                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6598                         })?;
6599                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6600                 let peer_state = &mut *peer_state_lock;
6601                 match peer_state.channel_by_id.entry(msg.channel_id) {
6602                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6603                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6604                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6605                                 } else {
6606                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6607                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6608                                 }
6609                         },
6610                         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))
6611                 }
6612                 Ok(())
6613         }
6614
6615         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6616                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6617                 // closing a channel), so any changes are likely to be lost on restart!
6618                 let per_peer_state = self.per_peer_state.read().unwrap();
6619                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6620                         .ok_or_else(|| {
6621                                 debug_assert!(false);
6622                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6623                         })?;
6624                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6625                 let peer_state = &mut *peer_state_lock;
6626                 match peer_state.channel_by_id.entry(msg.channel_id) {
6627                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6628                                 if (msg.failure_code & 0x8000) == 0 {
6629                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6630                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6631                                 }
6632                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6633                                         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);
6634                                 } else {
6635                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6636                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6637                                 }
6638                                 Ok(())
6639                         },
6640                         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))
6641                 }
6642         }
6643
6644         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6645                 let per_peer_state = self.per_peer_state.read().unwrap();
6646                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6647                         .ok_or_else(|| {
6648                                 debug_assert!(false);
6649                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6650                         })?;
6651                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6652                 let peer_state = &mut *peer_state_lock;
6653                 match peer_state.channel_by_id.entry(msg.channel_id) {
6654                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6655                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6656                                         let funding_txo = chan.context.get_funding_txo();
6657                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &self.logger), chan_phase_entry);
6658                                         if let Some(monitor_update) = monitor_update_opt {
6659                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6660                                                         peer_state, per_peer_state, chan);
6661                                         }
6662                                         Ok(())
6663                                 } else {
6664                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6665                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6666                                 }
6667                         },
6668                         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))
6669                 }
6670         }
6671
6672         #[inline]
6673         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6674                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6675                         let mut push_forward_event = false;
6676                         let mut new_intercept_events = VecDeque::new();
6677                         let mut failed_intercept_forwards = Vec::new();
6678                         if !pending_forwards.is_empty() {
6679                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6680                                         let scid = match forward_info.routing {
6681                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6682                                                 PendingHTLCRouting::Receive { .. } => 0,
6683                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6684                                         };
6685                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6686                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6687
6688                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6689                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6690                                         match forward_htlcs.entry(scid) {
6691                                                 hash_map::Entry::Occupied(mut entry) => {
6692                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6693                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6694                                                 },
6695                                                 hash_map::Entry::Vacant(entry) => {
6696                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6697                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6698                                                         {
6699                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6700                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6701                                                                 match pending_intercepts.entry(intercept_id) {
6702                                                                         hash_map::Entry::Vacant(entry) => {
6703                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6704                                                                                         requested_next_hop_scid: scid,
6705                                                                                         payment_hash: forward_info.payment_hash,
6706                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6707                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6708                                                                                         intercept_id
6709                                                                                 }, None));
6710                                                                                 entry.insert(PendingAddHTLCInfo {
6711                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6712                                                                         },
6713                                                                         hash_map::Entry::Occupied(_) => {
6714                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6715                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6716                                                                                         short_channel_id: prev_short_channel_id,
6717                                                                                         user_channel_id: Some(prev_user_channel_id),
6718                                                                                         outpoint: prev_funding_outpoint,
6719                                                                                         htlc_id: prev_htlc_id,
6720                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6721                                                                                         phantom_shared_secret: None,
6722                                                                                 });
6723
6724                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6725                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6726                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6727                                                                                 ));
6728                                                                         }
6729                                                                 }
6730                                                         } else {
6731                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6732                                                                 // payments are being processed.
6733                                                                 if forward_htlcs_empty {
6734                                                                         push_forward_event = true;
6735                                                                 }
6736                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6737                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6738                                                         }
6739                                                 }
6740                                         }
6741                                 }
6742                         }
6743
6744                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6745                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6746                         }
6747
6748                         if !new_intercept_events.is_empty() {
6749                                 let mut events = self.pending_events.lock().unwrap();
6750                                 events.append(&mut new_intercept_events);
6751                         }
6752                         if push_forward_event { self.push_pending_forwards_ev() }
6753                 }
6754         }
6755
6756         fn push_pending_forwards_ev(&self) {
6757                 let mut pending_events = self.pending_events.lock().unwrap();
6758                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6759                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6760                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6761                 ).count();
6762                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6763                 // events is done in batches and they are not removed until we're done processing each
6764                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6765                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6766                 // payments will need an additional forwarding event before being claimed to make them look
6767                 // real by taking more time.
6768                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6769                         pending_events.push_back((Event::PendingHTLCsForwardable {
6770                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6771                         }, None));
6772                 }
6773         }
6774
6775         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6776         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6777         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6778         /// the [`ChannelMonitorUpdate`] in question.
6779         fn raa_monitor_updates_held(&self,
6780                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6781                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6782         ) -> bool {
6783                 actions_blocking_raa_monitor_updates
6784                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6785                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6786                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6787                                 channel_funding_outpoint,
6788                                 counterparty_node_id,
6789                         })
6790                 })
6791         }
6792
6793         #[cfg(any(test, feature = "_test_utils"))]
6794         pub(crate) fn test_raa_monitor_updates_held(&self,
6795                 counterparty_node_id: PublicKey, channel_id: ChannelId
6796         ) -> bool {
6797                 let per_peer_state = self.per_peer_state.read().unwrap();
6798                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6799                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6800                         let peer_state = &mut *peer_state_lck;
6801
6802                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6803                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6804                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6805                         }
6806                 }
6807                 false
6808         }
6809
6810         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6811                 let htlcs_to_fail = {
6812                         let per_peer_state = self.per_peer_state.read().unwrap();
6813                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6814                                 .ok_or_else(|| {
6815                                         debug_assert!(false);
6816                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6817                                 }).map(|mtx| mtx.lock().unwrap())?;
6818                         let peer_state = &mut *peer_state_lock;
6819                         match peer_state.channel_by_id.entry(msg.channel_id) {
6820                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6821                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6822                                                 let funding_txo_opt = chan.context.get_funding_txo();
6823                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6824                                                         self.raa_monitor_updates_held(
6825                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6826                                                                 *counterparty_node_id)
6827                                                 } else { false };
6828                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
6829                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &self.logger, mon_update_blocked), chan_phase_entry);
6830                                                 if let Some(monitor_update) = monitor_update_opt {
6831                                                         let funding_txo = funding_txo_opt
6832                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
6833                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
6834                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6835                                                 }
6836                                                 htlcs_to_fail
6837                                         } else {
6838                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6839                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
6840                                         }
6841                                 },
6842                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6843                         }
6844                 };
6845                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6846                 Ok(())
6847         }
6848
6849         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6850                 let per_peer_state = self.per_peer_state.read().unwrap();
6851                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6852                         .ok_or_else(|| {
6853                                 debug_assert!(false);
6854                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6855                         })?;
6856                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6857                 let peer_state = &mut *peer_state_lock;
6858                 match peer_state.channel_by_id.entry(msg.channel_id) {
6859                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6860                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6861                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &self.logger), chan_phase_entry);
6862                                 } else {
6863                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6864                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
6865                                 }
6866                         },
6867                         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))
6868                 }
6869                 Ok(())
6870         }
6871
6872         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6873                 let per_peer_state = self.per_peer_state.read().unwrap();
6874                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6875                         .ok_or_else(|| {
6876                                 debug_assert!(false);
6877                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6878                         })?;
6879                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6880                 let peer_state = &mut *peer_state_lock;
6881                 match peer_state.channel_by_id.entry(msg.channel_id) {
6882                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6883                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6884                                         if !chan.context.is_usable() {
6885                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6886                                         }
6887
6888                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6889                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6890                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
6891                                                         msg, &self.default_configuration
6892                                                 ), chan_phase_entry),
6893                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6894                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6895                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
6896                                         });
6897                                 } else {
6898                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6899                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
6900                                 }
6901                         },
6902                         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))
6903                 }
6904                 Ok(())
6905         }
6906
6907         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
6908         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6909                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6910                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6911                         None => {
6912                                 // It's not a local channel
6913                                 return Ok(NotifyOption::SkipPersistNoEvents)
6914                         }
6915                 };
6916                 let per_peer_state = self.per_peer_state.read().unwrap();
6917                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6918                 if peer_state_mutex_opt.is_none() {
6919                         return Ok(NotifyOption::SkipPersistNoEvents)
6920                 }
6921                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6922                 let peer_state = &mut *peer_state_lock;
6923                 match peer_state.channel_by_id.entry(chan_id) {
6924                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6925                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6926                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
6927                                                 if chan.context.should_announce() {
6928                                                         // If the announcement is about a channel of ours which is public, some
6929                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
6930                                                         // a scary-looking error message and return Ok instead.
6931                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6932                                                 }
6933                                                 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));
6934                                         }
6935                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
6936                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
6937                                         if were_node_one == msg_from_node_one {
6938                                                 return Ok(NotifyOption::SkipPersistNoEvents);
6939                                         } else {
6940                                                 log_debug!(self.logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
6941                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
6942                                                 // If nothing changed after applying their update, we don't need to bother
6943                                                 // persisting.
6944                                                 if !did_change {
6945                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6946                                                 }
6947                                         }
6948                                 } else {
6949                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6950                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
6951                                 }
6952                         },
6953                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
6954                 }
6955                 Ok(NotifyOption::DoPersist)
6956         }
6957
6958         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
6959                 let htlc_forwards;
6960                 let need_lnd_workaround = {
6961                         let per_peer_state = self.per_peer_state.read().unwrap();
6962
6963                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6964                                 .ok_or_else(|| {
6965                                         debug_assert!(false);
6966                                         MsgHandleErrInternal::send_err_msg_no_close(
6967                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6968                                                 msg.channel_id
6969                                         )
6970                                 })?;
6971                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6972                         let peer_state = &mut *peer_state_lock;
6973                         match peer_state.channel_by_id.entry(msg.channel_id) {
6974                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6975                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6976                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
6977                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
6978                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
6979                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6980                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
6981                                                         msg, &self.logger, &self.node_signer, self.chain_hash,
6982                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
6983                                                 let mut channel_update = None;
6984                                                 if let Some(msg) = responses.shutdown_msg {
6985                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6986                                                                 node_id: counterparty_node_id.clone(),
6987                                                                 msg,
6988                                                         });
6989                                                 } else if chan.context.is_usable() {
6990                                                         // If the channel is in a usable state (ie the channel is not being shut
6991                                                         // down), send a unicast channel_update to our counterparty to make sure
6992                                                         // they have the latest channel parameters.
6993                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6994                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
6995                                                                         node_id: chan.context.get_counterparty_node_id(),
6996                                                                         msg,
6997                                                                 });
6998                                                         }
6999                                                 }
7000                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7001                                                 htlc_forwards = self.handle_channel_resumption(
7002                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7003                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7004                                                 if let Some(upd) = channel_update {
7005                                                         peer_state.pending_msg_events.push(upd);
7006                                                 }
7007                                                 need_lnd_workaround
7008                                         } else {
7009                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7010                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7011                                         }
7012                                 },
7013                                 hash_map::Entry::Vacant(_) => {
7014                                         log_debug!(self.logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7015                                                 log_bytes!(msg.channel_id.0));
7016                                         // Unfortunately, lnd doesn't force close on errors
7017                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7018                                         // One of the few ways to get an lnd counterparty to force close is by
7019                                         // replicating what they do when restoring static channel backups (SCBs). They
7020                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7021                                         // invalid `your_last_per_commitment_secret`.
7022                                         //
7023                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7024                                         // can assume it's likely the channel closed from our point of view, but it
7025                                         // remains open on the counterparty's side. By sending this bogus
7026                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7027                                         // force close broadcasting their latest state. If the closing transaction from
7028                                         // our point of view remains unconfirmed, it'll enter a race with the
7029                                         // counterparty's to-be-broadcast latest commitment transaction.
7030                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7031                                                 node_id: *counterparty_node_id,
7032                                                 msg: msgs::ChannelReestablish {
7033                                                         channel_id: msg.channel_id,
7034                                                         next_local_commitment_number: 0,
7035                                                         next_remote_commitment_number: 0,
7036                                                         your_last_per_commitment_secret: [1u8; 32],
7037                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7038                                                         next_funding_txid: None,
7039                                                 },
7040                                         });
7041                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7042                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7043                                                         counterparty_node_id), msg.channel_id)
7044                                         )
7045                                 }
7046                         }
7047                 };
7048
7049                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7050                 if let Some(forwards) = htlc_forwards {
7051                         self.forward_htlcs(&mut [forwards][..]);
7052                         persist = NotifyOption::DoPersist;
7053                 }
7054
7055                 if let Some(channel_ready_msg) = need_lnd_workaround {
7056                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7057                 }
7058                 Ok(persist)
7059         }
7060
7061         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7062         fn process_pending_monitor_events(&self) -> bool {
7063                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7064
7065                 let mut failed_channels = Vec::new();
7066                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7067                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7068                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7069                         for monitor_event in monitor_events.drain(..) {
7070                                 match monitor_event {
7071                                         MonitorEvent::HTLCEvent(htlc_update) => {
7072                                                 if let Some(preimage) = htlc_update.payment_preimage {
7073                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7074                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint);
7075                                                 } else {
7076                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7077                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
7078                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7079                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7080                                                 }
7081                                         },
7082                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
7083                                                 let counterparty_node_id_opt = match counterparty_node_id {
7084                                                         Some(cp_id) => Some(cp_id),
7085                                                         None => {
7086                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7087                                                                 // monitor event, this and the id_to_peer map should be removed.
7088                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
7089                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
7090                                                         }
7091                                                 };
7092                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7093                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7094                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7095                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7096                                                                 let peer_state = &mut *peer_state_lock;
7097                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7098                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
7099                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7100                                                                                 failed_channels.push(chan.context.force_shutdown(false));
7101                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7102                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7103                                                                                                 msg: update
7104                                                                                         });
7105                                                                                 }
7106                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
7107                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7108                                                                                         node_id: chan.context.get_counterparty_node_id(),
7109                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7110                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7111                                                                                         },
7112                                                                                 });
7113                                                                         }
7114                                                                 }
7115                                                         }
7116                                                 }
7117                                         },
7118                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
7119                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
7120                                         },
7121                                 }
7122                         }
7123                 }
7124
7125                 for failure in failed_channels.drain(..) {
7126                         self.finish_close_channel(failure);
7127                 }
7128
7129                 has_pending_monitor_events
7130         }
7131
7132         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7133         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7134         /// update events as a separate process method here.
7135         #[cfg(fuzzing)]
7136         pub fn process_monitor_events(&self) {
7137                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7138                 self.process_pending_monitor_events();
7139         }
7140
7141         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7142         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7143         /// update was applied.
7144         fn check_free_holding_cells(&self) -> bool {
7145                 let mut has_monitor_update = false;
7146                 let mut failed_htlcs = Vec::new();
7147
7148                 // Walk our list of channels and find any that need to update. Note that when we do find an
7149                 // update, if it includes actions that must be taken afterwards, we have to drop the
7150                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7151                 // manage to go through all our peers without finding a single channel to update.
7152                 'peer_loop: loop {
7153                         let per_peer_state = self.per_peer_state.read().unwrap();
7154                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7155                                 'chan_loop: loop {
7156                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7157                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7158                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7159                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7160                                         ) {
7161                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7162                                                 let funding_txo = chan.context.get_funding_txo();
7163                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7164                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
7165                                                 if !holding_cell_failed_htlcs.is_empty() {
7166                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7167                                                 }
7168                                                 if let Some(monitor_update) = monitor_opt {
7169                                                         has_monitor_update = true;
7170
7171                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7172                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7173                                                         continue 'peer_loop;
7174                                                 }
7175                                         }
7176                                         break 'chan_loop;
7177                                 }
7178                         }
7179                         break 'peer_loop;
7180                 }
7181
7182                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7183                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7184                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7185                 }
7186
7187                 has_update
7188         }
7189
7190         /// Check whether any channels have finished removing all pending updates after a shutdown
7191         /// exchange and can now send a closing_signed.
7192         /// Returns whether any closing_signed messages were generated.
7193         fn maybe_generate_initial_closing_signed(&self) -> bool {
7194                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7195                 let mut has_update = false;
7196                 let mut shutdown_results = Vec::new();
7197                 {
7198                         let per_peer_state = self.per_peer_state.read().unwrap();
7199
7200                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7201                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7202                                 let peer_state = &mut *peer_state_lock;
7203                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7204                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7205                                         match phase {
7206                                                 ChannelPhase::Funded(chan) => {
7207                                                         let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
7208                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
7209                                                                 Ok((msg_opt, tx_opt)) => {
7210                                                                         if let Some(msg) = msg_opt {
7211                                                                                 has_update = true;
7212                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7213                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7214                                                                                 });
7215                                                                         }
7216                                                                         if let Some(tx) = tx_opt {
7217                                                                                 // We're done with this channel. We got a closing_signed and sent back
7218                                                                                 // a closing_signed with a closing transaction to broadcast.
7219                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7220                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7221                                                                                                 msg: update
7222                                                                                         });
7223                                                                                 }
7224
7225                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
7226
7227                                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
7228                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7229                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7230                                                                                 shutdown_results.push((None, Vec::new(), unbroadcasted_batch_funding_txid));
7231                                                                                 false
7232                                                                         } else { true }
7233                                                                 },
7234                                                                 Err(e) => {
7235                                                                         has_update = true;
7236                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7237                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7238                                                                         !close_channel
7239                                                                 }
7240                                                         }
7241                                                 },
7242                                                 _ => true, // Retain unfunded channels if present.
7243                                         }
7244                                 });
7245                         }
7246                 }
7247
7248                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7249                         let _ = handle_error!(self, err, counterparty_node_id);
7250                 }
7251
7252                 for shutdown_result in shutdown_results.drain(..) {
7253                         self.finish_close_channel(shutdown_result);
7254                 }
7255
7256                 has_update
7257         }
7258
7259         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7260         /// pushing the channel monitor update (if any) to the background events queue and removing the
7261         /// Channel object.
7262         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7263                 for mut failure in failed_channels.drain(..) {
7264                         // Either a commitment transactions has been confirmed on-chain or
7265                         // Channel::block_disconnected detected that the funding transaction has been
7266                         // reorganized out of the main chain.
7267                         // We cannot broadcast our latest local state via monitor update (as
7268                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7269                         // so we track the update internally and handle it when the user next calls
7270                         // timer_tick_occurred, guaranteeing we're running normally.
7271                         if let Some((counterparty_node_id, funding_txo, update)) = failure.0.take() {
7272                                 assert_eq!(update.updates.len(), 1);
7273                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7274                                         assert!(should_broadcast);
7275                                 } else { unreachable!(); }
7276                                 self.pending_background_events.lock().unwrap().push(
7277                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7278                                                 counterparty_node_id, funding_txo, update
7279                                         });
7280                         }
7281                         self.finish_close_channel(failure);
7282                 }
7283         }
7284
7285         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7286         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7287         /// not have an expiration unless otherwise set on the builder.
7288         ///
7289         /// Uses a one-hop [`BlindedPath`] for the offer with [`ChannelManager::get_our_node_id`] as the
7290         /// introduction node and a derived signing pubkey for recipient privacy. As such, currently,
7291         /// the node must be announced. Otherwise, there is no way to find a path to the introduction
7292         /// node in order to send the [`InvoiceRequest`].
7293         ///
7294         /// [`Offer`]: crate::offers::offer::Offer
7295         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7296         pub fn create_offer_builder(
7297                 &self, description: String
7298         ) -> OfferBuilder<DerivedMetadata, secp256k1::All> {
7299                 let node_id = self.get_our_node_id();
7300                 let expanded_key = &self.inbound_payment_key;
7301                 let entropy = &*self.entropy_source;
7302                 let secp_ctx = &self.secp_ctx;
7303                 let path = self.create_one_hop_blinded_path();
7304
7305                 OfferBuilder::deriving_signing_pubkey(description, node_id, expanded_key, entropy, secp_ctx)
7306                         .chain_hash(self.chain_hash)
7307                         .path(path)
7308         }
7309
7310         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7311         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund. The builder will
7312         /// have the provided expiration set. Any changes to the expiration on the returned builder will
7313         /// not be honored by [`ChannelManager`].
7314         ///
7315         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7316         ///
7317         /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
7318         /// the introduction node and a derived payer id for sender privacy. As such, currently, the
7319         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7320         /// in order to send the [`Bolt12Invoice`].
7321         ///
7322         /// [`Refund`]: crate::offers::refund::Refund
7323         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7324         pub fn create_refund_builder(
7325                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7326                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7327         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7328                 let node_id = self.get_our_node_id();
7329                 let expanded_key = &self.inbound_payment_key;
7330                 let entropy = &*self.entropy_source;
7331                 let secp_ctx = &self.secp_ctx;
7332                 let path = self.create_one_hop_blinded_path();
7333
7334                 let builder = RefundBuilder::deriving_payer_id(
7335                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7336                 )?
7337                         .chain_hash(self.chain_hash)
7338                         .absolute_expiry(absolute_expiry)
7339                         .path(path);
7340
7341                 self.pending_outbound_payments
7342                         .add_new_awaiting_invoice(
7343                                 payment_id, absolute_expiry, retry_strategy, max_total_routing_fee_msat,
7344                         )
7345                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7346
7347                 Ok(builder)
7348         }
7349
7350         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7351         /// to pay us.
7352         ///
7353         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7354         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7355         ///
7356         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7357         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7358         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7359         /// passed directly to [`claim_funds`].
7360         ///
7361         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7362         ///
7363         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7364         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7365         ///
7366         /// # Note
7367         ///
7368         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7369         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7370         ///
7371         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7372         ///
7373         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7374         /// on versions of LDK prior to 0.0.114.
7375         ///
7376         /// [`claim_funds`]: Self::claim_funds
7377         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7378         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7379         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7380         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7381         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7382         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7383                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7384                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7385                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7386                         min_final_cltv_expiry_delta)
7387         }
7388
7389         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7390         /// stored external to LDK.
7391         ///
7392         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7393         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7394         /// the `min_value_msat` provided here, if one is provided.
7395         ///
7396         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7397         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7398         /// payments.
7399         ///
7400         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7401         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7402         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7403         /// sender "proof-of-payment" unless they have paid the required amount.
7404         ///
7405         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7406         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7407         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7408         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7409         /// invoices when no timeout is set.
7410         ///
7411         /// Note that we use block header time to time-out pending inbound payments (with some margin
7412         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7413         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7414         /// If you need exact expiry semantics, you should enforce them upon receipt of
7415         /// [`PaymentClaimable`].
7416         ///
7417         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7418         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7419         ///
7420         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7421         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7422         ///
7423         /// # Note
7424         ///
7425         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7426         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7427         ///
7428         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7429         ///
7430         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7431         /// on versions of LDK prior to 0.0.114.
7432         ///
7433         /// [`create_inbound_payment`]: Self::create_inbound_payment
7434         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7435         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7436                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7437                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7438                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7439                         min_final_cltv_expiry)
7440         }
7441
7442         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7443         /// previously returned from [`create_inbound_payment`].
7444         ///
7445         /// [`create_inbound_payment`]: Self::create_inbound_payment
7446         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7447                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7448         }
7449
7450         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7451         /// node.
7452         fn create_one_hop_blinded_path(&self) -> BlindedPath {
7453                 let entropy_source = self.entropy_source.deref();
7454                 let secp_ctx = &self.secp_ctx;
7455                 BlindedPath::one_hop_for_message(self.get_our_node_id(), entropy_source, secp_ctx).unwrap()
7456         }
7457
7458         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
7459         /// are used when constructing the phantom invoice's route hints.
7460         ///
7461         /// [phantom node payments]: crate::sign::PhantomKeysManager
7462         pub fn get_phantom_scid(&self) -> u64 {
7463                 let best_block_height = self.best_block.read().unwrap().height();
7464                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7465                 loop {
7466                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7467                         // Ensure the generated scid doesn't conflict with a real channel.
7468                         match short_to_chan_info.get(&scid_candidate) {
7469                                 Some(_) => continue,
7470                                 None => return scid_candidate
7471                         }
7472                 }
7473         }
7474
7475         /// Gets route hints for use in receiving [phantom node payments].
7476         ///
7477         /// [phantom node payments]: crate::sign::PhantomKeysManager
7478         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
7479                 PhantomRouteHints {
7480                         channels: self.list_usable_channels(),
7481                         phantom_scid: self.get_phantom_scid(),
7482                         real_node_pubkey: self.get_our_node_id(),
7483                 }
7484         }
7485
7486         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
7487         /// used when constructing the route hints for HTLCs intended to be intercepted. See
7488         /// [`ChannelManager::forward_intercepted_htlc`].
7489         ///
7490         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
7491         /// times to get a unique scid.
7492         pub fn get_intercept_scid(&self) -> u64 {
7493                 let best_block_height = self.best_block.read().unwrap().height();
7494                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7495                 loop {
7496                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7497                         // Ensure the generated scid doesn't conflict with a real channel.
7498                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
7499                         return scid_candidate
7500                 }
7501         }
7502
7503         /// Gets inflight HTLC information by processing pending outbound payments that are in
7504         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
7505         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
7506                 let mut inflight_htlcs = InFlightHtlcs::new();
7507
7508                 let per_peer_state = self.per_peer_state.read().unwrap();
7509                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7510                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7511                         let peer_state = &mut *peer_state_lock;
7512                         for chan in peer_state.channel_by_id.values().filter_map(
7513                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7514                         ) {
7515                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
7516                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
7517                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
7518                                         }
7519                                 }
7520                         }
7521                 }
7522
7523                 inflight_htlcs
7524         }
7525
7526         #[cfg(any(test, feature = "_test_utils"))]
7527         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
7528                 let events = core::cell::RefCell::new(Vec::new());
7529                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
7530                 self.process_pending_events(&event_handler);
7531                 events.into_inner()
7532         }
7533
7534         #[cfg(feature = "_test_utils")]
7535         pub fn push_pending_event(&self, event: events::Event) {
7536                 let mut events = self.pending_events.lock().unwrap();
7537                 events.push_back((event, None));
7538         }
7539
7540         #[cfg(test)]
7541         pub fn pop_pending_event(&self) -> Option<events::Event> {
7542                 let mut events = self.pending_events.lock().unwrap();
7543                 events.pop_front().map(|(e, _)| e)
7544         }
7545
7546         #[cfg(test)]
7547         pub fn has_pending_payments(&self) -> bool {
7548                 self.pending_outbound_payments.has_pending_payments()
7549         }
7550
7551         #[cfg(test)]
7552         pub fn clear_pending_payments(&self) {
7553                 self.pending_outbound_payments.clear_pending_payments()
7554         }
7555
7556         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
7557         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
7558         /// operation. It will double-check that nothing *else* is also blocking the same channel from
7559         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
7560         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
7561                 loop {
7562                         let per_peer_state = self.per_peer_state.read().unwrap();
7563                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7564                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7565                                 let peer_state = &mut *peer_state_lck;
7566
7567                                 if let Some(blocker) = completed_blocker.take() {
7568                                         // Only do this on the first iteration of the loop.
7569                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
7570                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
7571                                         {
7572                                                 blockers.retain(|iter| iter != &blocker);
7573                                         }
7574                                 }
7575
7576                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7577                                         channel_funding_outpoint, counterparty_node_id) {
7578                                         // Check that, while holding the peer lock, we don't have anything else
7579                                         // blocking monitor updates for this channel. If we do, release the monitor
7580                                         // update(s) when those blockers complete.
7581                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
7582                                                 &channel_funding_outpoint.to_channel_id());
7583                                         break;
7584                                 }
7585
7586                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
7587                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7588                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
7589                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
7590                                                         log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
7591                                                                 channel_funding_outpoint.to_channel_id());
7592                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
7593                                                                 peer_state_lck, peer_state, per_peer_state, chan);
7594                                                         if further_update_exists {
7595                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
7596                                                                 // top of the loop.
7597                                                                 continue;
7598                                                         }
7599                                                 } else {
7600                                                         log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
7601                                                                 channel_funding_outpoint.to_channel_id());
7602                                                 }
7603                                         }
7604                                 }
7605                         } else {
7606                                 log_debug!(self.logger,
7607                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
7608                                         log_pubkey!(counterparty_node_id));
7609                         }
7610                         break;
7611                 }
7612         }
7613
7614         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
7615                 for action in actions {
7616                         match action {
7617                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7618                                         channel_funding_outpoint, counterparty_node_id
7619                                 } => {
7620                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
7621                                 }
7622                         }
7623                 }
7624         }
7625
7626         /// Processes any events asynchronously in the order they were generated since the last call
7627         /// using the given event handler.
7628         ///
7629         /// See the trait-level documentation of [`EventsProvider`] for requirements.
7630         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
7631                 &self, handler: H
7632         ) {
7633                 let mut ev;
7634                 process_events_body!(self, ev, { handler(ev).await });
7635         }
7636 }
7637
7638 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>
7639 where
7640         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7641         T::Target: BroadcasterInterface,
7642         ES::Target: EntropySource,
7643         NS::Target: NodeSigner,
7644         SP::Target: SignerProvider,
7645         F::Target: FeeEstimator,
7646         R::Target: Router,
7647         L::Target: Logger,
7648 {
7649         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
7650         /// The returned array will contain `MessageSendEvent`s for different peers if
7651         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
7652         /// is always placed next to each other.
7653         ///
7654         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
7655         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
7656         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
7657         /// will randomly be placed first or last in the returned array.
7658         ///
7659         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
7660         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
7661         /// the `MessageSendEvent`s to the specific peer they were generated under.
7662         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
7663                 let events = RefCell::new(Vec::new());
7664                 PersistenceNotifierGuard::optionally_notify(self, || {
7665                         let mut result = NotifyOption::SkipPersistNoEvents;
7666
7667                         // TODO: This behavior should be documented. It's unintuitive that we query
7668                         // ChannelMonitors when clearing other events.
7669                         if self.process_pending_monitor_events() {
7670                                 result = NotifyOption::DoPersist;
7671                         }
7672
7673                         if self.check_free_holding_cells() {
7674                                 result = NotifyOption::DoPersist;
7675                         }
7676                         if self.maybe_generate_initial_closing_signed() {
7677                                 result = NotifyOption::DoPersist;
7678                         }
7679
7680                         let mut pending_events = Vec::new();
7681                         let per_peer_state = self.per_peer_state.read().unwrap();
7682                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7683                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7684                                 let peer_state = &mut *peer_state_lock;
7685                                 if peer_state.pending_msg_events.len() > 0 {
7686                                         pending_events.append(&mut peer_state.pending_msg_events);
7687                                 }
7688                         }
7689
7690                         if !pending_events.is_empty() {
7691                                 events.replace(pending_events);
7692                         }
7693
7694                         result
7695                 });
7696                 events.into_inner()
7697         }
7698 }
7699
7700 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>
7701 where
7702         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7703         T::Target: BroadcasterInterface,
7704         ES::Target: EntropySource,
7705         NS::Target: NodeSigner,
7706         SP::Target: SignerProvider,
7707         F::Target: FeeEstimator,
7708         R::Target: Router,
7709         L::Target: Logger,
7710 {
7711         /// Processes events that must be periodically handled.
7712         ///
7713         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
7714         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
7715         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
7716                 let mut ev;
7717                 process_events_body!(self, ev, handler.handle_event(ev));
7718         }
7719 }
7720
7721 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>
7722 where
7723         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7724         T::Target: BroadcasterInterface,
7725         ES::Target: EntropySource,
7726         NS::Target: NodeSigner,
7727         SP::Target: SignerProvider,
7728         F::Target: FeeEstimator,
7729         R::Target: Router,
7730         L::Target: Logger,
7731 {
7732         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7733                 {
7734                         let best_block = self.best_block.read().unwrap();
7735                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
7736                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
7737                         assert_eq!(best_block.height(), height - 1,
7738                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
7739                 }
7740
7741                 self.transactions_confirmed(header, txdata, height);
7742                 self.best_block_updated(header, height);
7743         }
7744
7745         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
7746                 let _persistence_guard =
7747                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7748                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7749                 let new_height = height - 1;
7750                 {
7751                         let mut best_block = self.best_block.write().unwrap();
7752                         assert_eq!(best_block.block_hash(), header.block_hash(),
7753                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
7754                         assert_eq!(best_block.height(), height,
7755                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
7756                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
7757                 }
7758
7759                 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));
7760         }
7761 }
7762
7763 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>
7764 where
7765         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7766         T::Target: BroadcasterInterface,
7767         ES::Target: EntropySource,
7768         NS::Target: NodeSigner,
7769         SP::Target: SignerProvider,
7770         F::Target: FeeEstimator,
7771         R::Target: Router,
7772         L::Target: Logger,
7773 {
7774         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7775                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7776                 // during initialization prior to the chain_monitor being fully configured in some cases.
7777                 // See the docs for `ChannelManagerReadArgs` for more.
7778
7779                 let block_hash = header.block_hash();
7780                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
7781
7782                 let _persistence_guard =
7783                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7784                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7785                 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)
7786                         .map(|(a, b)| (a, Vec::new(), b)));
7787
7788                 let last_best_block_height = self.best_block.read().unwrap().height();
7789                 if height < last_best_block_height {
7790                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
7791                         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));
7792                 }
7793         }
7794
7795         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
7796                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7797                 // during initialization prior to the chain_monitor being fully configured in some cases.
7798                 // See the docs for `ChannelManagerReadArgs` for more.
7799
7800                 let block_hash = header.block_hash();
7801                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
7802
7803                 let _persistence_guard =
7804                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7805                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7806                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
7807
7808                 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));
7809
7810                 macro_rules! max_time {
7811                         ($timestamp: expr) => {
7812                                 loop {
7813                                         // Update $timestamp to be the max of its current value and the block
7814                                         // timestamp. This should keep us close to the current time without relying on
7815                                         // having an explicit local time source.
7816                                         // Just in case we end up in a race, we loop until we either successfully
7817                                         // update $timestamp or decide we don't need to.
7818                                         let old_serial = $timestamp.load(Ordering::Acquire);
7819                                         if old_serial >= header.time as usize { break; }
7820                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
7821                                                 break;
7822                                         }
7823                                 }
7824                         }
7825                 }
7826                 max_time!(self.highest_seen_timestamp);
7827                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
7828                 payment_secrets.retain(|_, inbound_payment| {
7829                         inbound_payment.expiry_time > header.time as u64
7830                 });
7831         }
7832
7833         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
7834                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
7835                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
7836                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7837                         let peer_state = &mut *peer_state_lock;
7838                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
7839                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
7840                                         res.push((funding_txo.txid, Some(block_hash)));
7841                                 }
7842                         }
7843                 }
7844                 res
7845         }
7846
7847         fn transaction_unconfirmed(&self, txid: &Txid) {
7848                 let _persistence_guard =
7849                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7850                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7851                 self.do_chain_event(None, |channel| {
7852                         if let Some(funding_txo) = channel.context.get_funding_txo() {
7853                                 if funding_txo.txid == *txid {
7854                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
7855                                 } else { Ok((None, Vec::new(), None)) }
7856                         } else { Ok((None, Vec::new(), None)) }
7857                 });
7858         }
7859 }
7860
7861 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>
7862 where
7863         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7864         T::Target: BroadcasterInterface,
7865         ES::Target: EntropySource,
7866         NS::Target: NodeSigner,
7867         SP::Target: SignerProvider,
7868         F::Target: FeeEstimator,
7869         R::Target: Router,
7870         L::Target: Logger,
7871 {
7872         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
7873         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
7874         /// the function.
7875         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
7876                         (&self, height_opt: Option<u32>, f: FN) {
7877                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7878                 // during initialization prior to the chain_monitor being fully configured in some cases.
7879                 // See the docs for `ChannelManagerReadArgs` for more.
7880
7881                 let mut failed_channels = Vec::new();
7882                 let mut timed_out_htlcs = Vec::new();
7883                 {
7884                         let per_peer_state = self.per_peer_state.read().unwrap();
7885                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7886                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7887                                 let peer_state = &mut *peer_state_lock;
7888                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7889                                 peer_state.channel_by_id.retain(|_, phase| {
7890                                         match phase {
7891                                                 // Retain unfunded channels.
7892                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
7893                                                 ChannelPhase::Funded(channel) => {
7894                                                         let res = f(channel);
7895                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
7896                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
7897                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
7898                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
7899                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
7900                                                                 }
7901                                                                 if let Some(channel_ready) = channel_ready_opt {
7902                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
7903                                                                         if channel.context.is_usable() {
7904                                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
7905                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
7906                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
7907                                                                                                 node_id: channel.context.get_counterparty_node_id(),
7908                                                                                                 msg,
7909                                                                                         });
7910                                                                                 }
7911                                                                         } else {
7912                                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
7913                                                                         }
7914                                                                 }
7915
7916                                                                 {
7917                                                                         let mut pending_events = self.pending_events.lock().unwrap();
7918                                                                         emit_channel_ready_event!(pending_events, channel);
7919                                                                 }
7920
7921                                                                 if let Some(announcement_sigs) = announcement_sigs {
7922                                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
7923                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
7924                                                                                 node_id: channel.context.get_counterparty_node_id(),
7925                                                                                 msg: announcement_sigs,
7926                                                                         });
7927                                                                         if let Some(height) = height_opt {
7928                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
7929                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7930                                                                                                 msg: announcement,
7931                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7932                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7933                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
7934                                                                                         });
7935                                                                                 }
7936                                                                         }
7937                                                                 }
7938                                                                 if channel.is_our_channel_ready() {
7939                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
7940                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
7941                                                                                 // to the short_to_chan_info map here. Note that we check whether we
7942                                                                                 // can relay using the real SCID at relay-time (i.e.
7943                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
7944                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
7945                                                                                 // is always consistent.
7946                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
7947                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
7948                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
7949                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
7950                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
7951                                                                         }
7952                                                                 }
7953                                                         } else if let Err(reason) = res {
7954                                                                 update_maps_on_chan_removal!(self, &channel.context);
7955                                                                 // It looks like our counterparty went on-chain or funding transaction was
7956                                                                 // reorged out of the main chain. Close the channel.
7957                                                                 failed_channels.push(channel.context.force_shutdown(true));
7958                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
7959                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7960                                                                                 msg: update
7961                                                                         });
7962                                                                 }
7963                                                                 let reason_message = format!("{}", reason);
7964                                                                 self.issue_channel_close_events(&channel.context, reason);
7965                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7966                                                                         node_id: channel.context.get_counterparty_node_id(),
7967                                                                         action: msgs::ErrorAction::DisconnectPeer {
7968                                                                                 msg: Some(msgs::ErrorMessage {
7969                                                                                         channel_id: channel.context.channel_id(),
7970                                                                                         data: reason_message,
7971                                                                                 })
7972                                                                         },
7973                                                                 });
7974                                                                 return false;
7975                                                         }
7976                                                         true
7977                                                 }
7978                                         }
7979                                 });
7980                         }
7981                 }
7982
7983                 if let Some(height) = height_opt {
7984                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
7985                                 payment.htlcs.retain(|htlc| {
7986                                         // If height is approaching the number of blocks we think it takes us to get
7987                                         // our commitment transaction confirmed before the HTLC expires, plus the
7988                                         // number of blocks we generally consider it to take to do a commitment update,
7989                                         // just give up on it and fail the HTLC.
7990                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
7991                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
7992                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
7993
7994                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
7995                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
7996                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
7997                                                 false
7998                                         } else { true }
7999                                 });
8000                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8001                         });
8002
8003                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8004                         intercepted_htlcs.retain(|_, htlc| {
8005                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8006                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8007                                                 short_channel_id: htlc.prev_short_channel_id,
8008                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8009                                                 htlc_id: htlc.prev_htlc_id,
8010                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8011                                                 phantom_shared_secret: None,
8012                                                 outpoint: htlc.prev_funding_outpoint,
8013                                         });
8014
8015                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8016                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8017                                                 _ => unreachable!(),
8018                                         };
8019                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8020                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8021                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8022                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8023                                         false
8024                                 } else { true }
8025                         });
8026                 }
8027
8028                 self.handle_init_event_channel_failures(failed_channels);
8029
8030                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8031                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8032                 }
8033         }
8034
8035         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8036         /// may have events that need processing.
8037         ///
8038         /// In order to check if this [`ChannelManager`] needs persisting, call
8039         /// [`Self::get_and_clear_needs_persistence`].
8040         ///
8041         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8042         /// [`ChannelManager`] and should instead register actions to be taken later.
8043         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8044                 self.event_persist_notifier.get_future()
8045         }
8046
8047         /// Returns true if this [`ChannelManager`] needs to be persisted.
8048         pub fn get_and_clear_needs_persistence(&self) -> bool {
8049                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8050         }
8051
8052         #[cfg(any(test, feature = "_test_utils"))]
8053         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8054                 self.event_persist_notifier.notify_pending()
8055         }
8056
8057         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8058         /// [`chain::Confirm`] interfaces.
8059         pub fn current_best_block(&self) -> BestBlock {
8060                 self.best_block.read().unwrap().clone()
8061         }
8062
8063         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
8064         /// [`ChannelManager`].
8065         pub fn node_features(&self) -> NodeFeatures {
8066                 provided_node_features(&self.default_configuration)
8067         }
8068
8069         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
8070         /// [`ChannelManager`].
8071         ///
8072         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8073         /// or not. Thus, this method is not public.
8074         #[cfg(any(feature = "_test_utils", test))]
8075         pub fn invoice_features(&self) -> Bolt11InvoiceFeatures {
8076                 provided_invoice_features(&self.default_configuration)
8077         }
8078
8079         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
8080         /// [`ChannelManager`].
8081         pub fn channel_features(&self) -> ChannelFeatures {
8082                 provided_channel_features(&self.default_configuration)
8083         }
8084
8085         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
8086         /// [`ChannelManager`].
8087         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8088                 provided_channel_type_features(&self.default_configuration)
8089         }
8090
8091         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
8092         /// [`ChannelManager`].
8093         pub fn init_features(&self) -> InitFeatures {
8094                 provided_init_features(&self.default_configuration)
8095         }
8096 }
8097
8098 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8099         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8100 where
8101         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8102         T::Target: BroadcasterInterface,
8103         ES::Target: EntropySource,
8104         NS::Target: NodeSigner,
8105         SP::Target: SignerProvider,
8106         F::Target: FeeEstimator,
8107         R::Target: Router,
8108         L::Target: Logger,
8109 {
8110         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8111                 // Note that we never need to persist the updated ChannelManager for an inbound
8112                 // open_channel message - pre-funded channels are never written so there should be no
8113                 // change to the contents.
8114                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8115                         let res = self.internal_open_channel(counterparty_node_id, msg);
8116                         let persist = match &res {
8117                                 Err(e) if e.closes_channel() => {
8118                                         debug_assert!(false, "We shouldn't close a new channel");
8119                                         NotifyOption::DoPersist
8120                                 },
8121                                 _ => NotifyOption::SkipPersistHandleEvents,
8122                         };
8123                         let _ = handle_error!(self, res, *counterparty_node_id);
8124                         persist
8125                 });
8126         }
8127
8128         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8129                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8130                         "Dual-funded channels not supported".to_owned(),
8131                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8132         }
8133
8134         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8135                 // Note that we never need to persist the updated ChannelManager for an inbound
8136                 // accept_channel message - pre-funded channels are never written so there should be no
8137                 // change to the contents.
8138                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8139                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8140                         NotifyOption::SkipPersistHandleEvents
8141                 });
8142         }
8143
8144         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8145                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8146                         "Dual-funded channels not supported".to_owned(),
8147                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8148         }
8149
8150         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8151                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8152                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8153         }
8154
8155         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8156                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8157                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8158         }
8159
8160         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8161                 // Note that we never need to persist the updated ChannelManager for an inbound
8162                 // channel_ready message - while the channel's state will change, any channel_ready message
8163                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8164                 // will not force-close the channel on startup.
8165                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8166                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8167                         let persist = match &res {
8168                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8169                                 _ => NotifyOption::SkipPersistHandleEvents,
8170                         };
8171                         let _ = handle_error!(self, res, *counterparty_node_id);
8172                         persist
8173                 });
8174         }
8175
8176         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8177                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8178                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8179         }
8180
8181         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8182                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8183                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8184         }
8185
8186         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8187                 // Note that we never need to persist the updated ChannelManager for an inbound
8188                 // update_add_htlc message - the message itself doesn't change our channel state only the
8189                 // `commitment_signed` message afterwards will.
8190                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8191                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8192                         let persist = match &res {
8193                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8194                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8195                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8196                         };
8197                         let _ = handle_error!(self, res, *counterparty_node_id);
8198                         persist
8199                 });
8200         }
8201
8202         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8203                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8204                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8205         }
8206
8207         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8208                 // Note that we never need to persist the updated ChannelManager for an inbound
8209                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8210                 // `commitment_signed` message afterwards will.
8211                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8212                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8213                         let persist = match &res {
8214                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8215                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8216                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8217                         };
8218                         let _ = handle_error!(self, res, *counterparty_node_id);
8219                         persist
8220                 });
8221         }
8222
8223         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8224                 // Note that we never need to persist the updated ChannelManager for an inbound
8225                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8226                 // only the `commitment_signed` message afterwards will.
8227                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8228                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8229                         let persist = match &res {
8230                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8231                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8232                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8233                         };
8234                         let _ = handle_error!(self, res, *counterparty_node_id);
8235                         persist
8236                 });
8237         }
8238
8239         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8240                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8241                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8242         }
8243
8244         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8245                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8246                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8247         }
8248
8249         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8250                 // Note that we never need to persist the updated ChannelManager for an inbound
8251                 // update_fee message - the message itself doesn't change our channel state only the
8252                 // `commitment_signed` message afterwards will.
8253                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8254                         let res = self.internal_update_fee(counterparty_node_id, msg);
8255                         let persist = match &res {
8256                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8257                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8258                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8259                         };
8260                         let _ = handle_error!(self, res, *counterparty_node_id);
8261                         persist
8262                 });
8263         }
8264
8265         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8266                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8267                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8268         }
8269
8270         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8271                 PersistenceNotifierGuard::optionally_notify(self, || {
8272                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8273                                 persist
8274                         } else {
8275                                 NotifyOption::DoPersist
8276                         }
8277                 });
8278         }
8279
8280         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8281                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8282                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8283                         let persist = match &res {
8284                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8285                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8286                                 Ok(persist) => *persist,
8287                         };
8288                         let _ = handle_error!(self, res, *counterparty_node_id);
8289                         persist
8290                 });
8291         }
8292
8293         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8294                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8295                         self, || NotifyOption::SkipPersistHandleEvents);
8296                 let mut failed_channels = Vec::new();
8297                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8298                 let remove_peer = {
8299                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
8300                                 log_pubkey!(counterparty_node_id));
8301                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8302                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8303                                 let peer_state = &mut *peer_state_lock;
8304                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8305                                 peer_state.channel_by_id.retain(|_, phase| {
8306                                         let context = match phase {
8307                                                 ChannelPhase::Funded(chan) => {
8308                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger).is_ok() {
8309                                                                 // We only retain funded channels that are not shutdown.
8310                                                                 return true;
8311                                                         }
8312                                                         &mut chan.context
8313                                                 },
8314                                                 // Unfunded channels will always be removed.
8315                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8316                                                         &mut chan.context
8317                                                 },
8318                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8319                                                         &mut chan.context
8320                                                 },
8321                                         };
8322                                         // Clean up for removal.
8323                                         update_maps_on_chan_removal!(self, &context);
8324                                         self.issue_channel_close_events(&context, ClosureReason::DisconnectedPeer);
8325                                         failed_channels.push(context.force_shutdown(false));
8326                                         false
8327                                 });
8328                                 // Note that we don't bother generating any events for pre-accept channels -
8329                                 // they're not considered "channels" yet from the PoV of our events interface.
8330                                 peer_state.inbound_channel_request_by_id.clear();
8331                                 pending_msg_events.retain(|msg| {
8332                                         match msg {
8333                                                 // V1 Channel Establishment
8334                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8335                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8336                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8337                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8338                                                 // V2 Channel Establishment
8339                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8340                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8341                                                 // Common Channel Establishment
8342                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8343                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8344                                                 // Interactive Transaction Construction
8345                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8346                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8347                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8348                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8349                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8350                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8351                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8352                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8353                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8354                                                 // Channel Operations
8355                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8356                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8357                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8358                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8359                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8360                                                 &events::MessageSendEvent::HandleError { .. } => false,
8361                                                 // Gossip
8362                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8363                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8364                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8365                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8366                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8367                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8368                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8369                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8370                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8371                                         }
8372                                 });
8373                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8374                                 peer_state.is_connected = false;
8375                                 peer_state.ok_to_remove(true)
8376                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8377                 };
8378                 if remove_peer {
8379                         per_peer_state.remove(counterparty_node_id);
8380                 }
8381                 mem::drop(per_peer_state);
8382
8383                 for failure in failed_channels.drain(..) {
8384                         self.finish_close_channel(failure);
8385                 }
8386         }
8387
8388         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8389                 if !init_msg.features.supports_static_remote_key() {
8390                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8391                         return Err(());
8392                 }
8393
8394                 let mut res = Ok(());
8395
8396                 PersistenceNotifierGuard::optionally_notify(self, || {
8397                         // If we have too many peers connected which don't have funded channels, disconnect the
8398                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8399                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8400                         // peers connect, but we'll reject new channels from them.
8401                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8402                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8403
8404                         {
8405                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8406                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8407                                         hash_map::Entry::Vacant(e) => {
8408                                                 if inbound_peer_limited {
8409                                                         res = Err(());
8410                                                         return NotifyOption::SkipPersistNoEvents;
8411                                                 }
8412                                                 e.insert(Mutex::new(PeerState {
8413                                                         channel_by_id: HashMap::new(),
8414                                                         inbound_channel_request_by_id: HashMap::new(),
8415                                                         latest_features: init_msg.features.clone(),
8416                                                         pending_msg_events: Vec::new(),
8417                                                         in_flight_monitor_updates: BTreeMap::new(),
8418                                                         monitor_update_blocked_actions: BTreeMap::new(),
8419                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
8420                                                         is_connected: true,
8421                                                 }));
8422                                         },
8423                                         hash_map::Entry::Occupied(e) => {
8424                                                 let mut peer_state = e.get().lock().unwrap();
8425                                                 peer_state.latest_features = init_msg.features.clone();
8426
8427                                                 let best_block_height = self.best_block.read().unwrap().height();
8428                                                 if inbound_peer_limited &&
8429                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
8430                                                         peer_state.channel_by_id.len()
8431                                                 {
8432                                                         res = Err(());
8433                                                         return NotifyOption::SkipPersistNoEvents;
8434                                                 }
8435
8436                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
8437                                                 peer_state.is_connected = true;
8438                                         },
8439                                 }
8440                         }
8441
8442                         log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
8443
8444                         let per_peer_state = self.per_peer_state.read().unwrap();
8445                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8446                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8447                                 let peer_state = &mut *peer_state_lock;
8448                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8449
8450                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
8451                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else {
8452                                                 // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
8453                                                 // (so won't be recovered after a crash), they shouldn't exist here and we would never need to
8454                                                 // worry about closing and removing them.
8455                                                 debug_assert!(false);
8456                                                 None
8457                                         }
8458                                 ).for_each(|chan| {
8459                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
8460                                                 node_id: chan.context.get_counterparty_node_id(),
8461                                                 msg: chan.get_channel_reestablish(&self.logger),
8462                                         });
8463                                 });
8464                         }
8465
8466                         return NotifyOption::SkipPersistHandleEvents;
8467                         //TODO: Also re-broadcast announcement_signatures
8468                 });
8469                 res
8470         }
8471
8472         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
8473                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8474
8475                 match &msg.data as &str {
8476                         "cannot co-op close channel w/ active htlcs"|
8477                         "link failed to shutdown" =>
8478                         {
8479                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
8480                                 // send one while HTLCs are still present. The issue is tracked at
8481                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
8482                                 // to fix it but none so far have managed to land upstream. The issue appears to be
8483                                 // very low priority for the LND team despite being marked "P1".
8484                                 // We're not going to bother handling this in a sensible way, instead simply
8485                                 // repeating the Shutdown message on repeat until morale improves.
8486                                 if !msg.channel_id.is_zero() {
8487                                         let per_peer_state = self.per_peer_state.read().unwrap();
8488                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8489                                         if peer_state_mutex_opt.is_none() { return; }
8490                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
8491                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
8492                                                 if let Some(msg) = chan.get_outbound_shutdown() {
8493                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
8494                                                                 node_id: *counterparty_node_id,
8495                                                                 msg,
8496                                                         });
8497                                                 }
8498                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
8499                                                         node_id: *counterparty_node_id,
8500                                                         action: msgs::ErrorAction::SendWarningMessage {
8501                                                                 msg: msgs::WarningMessage {
8502                                                                         channel_id: msg.channel_id,
8503                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
8504                                                                 },
8505                                                                 log_level: Level::Trace,
8506                                                         }
8507                                                 });
8508                                         }
8509                                 }
8510                                 return;
8511                         }
8512                         _ => {}
8513                 }
8514
8515                 if msg.channel_id.is_zero() {
8516                         let channel_ids: Vec<ChannelId> = {
8517                                 let per_peer_state = self.per_peer_state.read().unwrap();
8518                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8519                                 if peer_state_mutex_opt.is_none() { return; }
8520                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8521                                 let peer_state = &mut *peer_state_lock;
8522                                 // Note that we don't bother generating any events for pre-accept channels -
8523                                 // they're not considered "channels" yet from the PoV of our events interface.
8524                                 peer_state.inbound_channel_request_by_id.clear();
8525                                 peer_state.channel_by_id.keys().cloned().collect()
8526                         };
8527                         for channel_id in channel_ids {
8528                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8529                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
8530                         }
8531                 } else {
8532                         {
8533                                 // First check if we can advance the channel type and try again.
8534                                 let per_peer_state = self.per_peer_state.read().unwrap();
8535                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8536                                 if peer_state_mutex_opt.is_none() { return; }
8537                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8538                                 let peer_state = &mut *peer_state_lock;
8539                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8540                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
8541                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
8542                                                         node_id: *counterparty_node_id,
8543                                                         msg,
8544                                                 });
8545                                                 return;
8546                                         }
8547                                 }
8548                         }
8549
8550                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8551                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
8552                 }
8553         }
8554
8555         fn provided_node_features(&self) -> NodeFeatures {
8556                 provided_node_features(&self.default_configuration)
8557         }
8558
8559         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
8560                 provided_init_features(&self.default_configuration)
8561         }
8562
8563         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8564                 Some(vec![self.chain_hash])
8565         }
8566
8567         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
8568                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8569                         "Dual-funded channels not supported".to_owned(),
8570                          msg.channel_id.clone())), *counterparty_node_id);
8571         }
8572
8573         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
8574                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8575                         "Dual-funded channels not supported".to_owned(),
8576                          msg.channel_id.clone())), *counterparty_node_id);
8577         }
8578
8579         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
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_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
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_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
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_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
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_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
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_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
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_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
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
8622 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
8623 /// [`ChannelManager`].
8624 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
8625         let mut node_features = provided_init_features(config).to_context();
8626         node_features.set_keysend_optional();
8627         node_features
8628 }
8629
8630 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
8631 /// [`ChannelManager`].
8632 ///
8633 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8634 /// or not. Thus, this method is not public.
8635 #[cfg(any(feature = "_test_utils", test))]
8636 pub(crate) fn provided_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
8637         provided_init_features(config).to_context()
8638 }
8639
8640 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
8641 /// [`ChannelManager`].
8642 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
8643         provided_init_features(config).to_context()
8644 }
8645
8646 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
8647 /// [`ChannelManager`].
8648 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
8649         ChannelTypeFeatures::from_init(&provided_init_features(config))
8650 }
8651
8652 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
8653 /// [`ChannelManager`].
8654 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
8655         // Note that if new features are added here which other peers may (eventually) require, we
8656         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
8657         // [`ErroringMessageHandler`].
8658         let mut features = InitFeatures::empty();
8659         features.set_data_loss_protect_required();
8660         features.set_upfront_shutdown_script_optional();
8661         features.set_variable_length_onion_required();
8662         features.set_static_remote_key_required();
8663         features.set_payment_secret_required();
8664         features.set_basic_mpp_optional();
8665         features.set_wumbo_optional();
8666         features.set_shutdown_any_segwit_optional();
8667         features.set_channel_type_optional();
8668         features.set_scid_privacy_optional();
8669         features.set_zero_conf_optional();
8670         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
8671                 features.set_anchors_zero_fee_htlc_tx_optional();
8672         }
8673         features
8674 }
8675
8676 const SERIALIZATION_VERSION: u8 = 1;
8677 const MIN_SERIALIZATION_VERSION: u8 = 1;
8678
8679 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
8680         (2, fee_base_msat, required),
8681         (4, fee_proportional_millionths, required),
8682         (6, cltv_expiry_delta, required),
8683 });
8684
8685 impl_writeable_tlv_based!(ChannelCounterparty, {
8686         (2, node_id, required),
8687         (4, features, required),
8688         (6, unspendable_punishment_reserve, required),
8689         (8, forwarding_info, option),
8690         (9, outbound_htlc_minimum_msat, option),
8691         (11, outbound_htlc_maximum_msat, option),
8692 });
8693
8694 impl Writeable for ChannelDetails {
8695         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8696                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8697                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8698                 let user_channel_id_low = self.user_channel_id as u64;
8699                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
8700                 write_tlv_fields!(writer, {
8701                         (1, self.inbound_scid_alias, option),
8702                         (2, self.channel_id, required),
8703                         (3, self.channel_type, option),
8704                         (4, self.counterparty, required),
8705                         (5, self.outbound_scid_alias, option),
8706                         (6, self.funding_txo, option),
8707                         (7, self.config, option),
8708                         (8, self.short_channel_id, option),
8709                         (9, self.confirmations, option),
8710                         (10, self.channel_value_satoshis, required),
8711                         (12, self.unspendable_punishment_reserve, option),
8712                         (14, user_channel_id_low, required),
8713                         (16, self.balance_msat, required),
8714                         (18, self.outbound_capacity_msat, required),
8715                         (19, self.next_outbound_htlc_limit_msat, required),
8716                         (20, self.inbound_capacity_msat, required),
8717                         (21, self.next_outbound_htlc_minimum_msat, required),
8718                         (22, self.confirmations_required, option),
8719                         (24, self.force_close_spend_delay, option),
8720                         (26, self.is_outbound, required),
8721                         (28, self.is_channel_ready, required),
8722                         (30, self.is_usable, required),
8723                         (32, self.is_public, required),
8724                         (33, self.inbound_htlc_minimum_msat, option),
8725                         (35, self.inbound_htlc_maximum_msat, option),
8726                         (37, user_channel_id_high_opt, option),
8727                         (39, self.feerate_sat_per_1000_weight, option),
8728                         (41, self.channel_shutdown_state, option),
8729                 });
8730                 Ok(())
8731         }
8732 }
8733
8734 impl Readable for ChannelDetails {
8735         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8736                 _init_and_read_len_prefixed_tlv_fields!(reader, {
8737                         (1, inbound_scid_alias, option),
8738                         (2, channel_id, required),
8739                         (3, channel_type, option),
8740                         (4, counterparty, required),
8741                         (5, outbound_scid_alias, option),
8742                         (6, funding_txo, option),
8743                         (7, config, option),
8744                         (8, short_channel_id, option),
8745                         (9, confirmations, option),
8746                         (10, channel_value_satoshis, required),
8747                         (12, unspendable_punishment_reserve, option),
8748                         (14, user_channel_id_low, required),
8749                         (16, balance_msat, required),
8750                         (18, outbound_capacity_msat, required),
8751                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
8752                         // filled in, so we can safely unwrap it here.
8753                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
8754                         (20, inbound_capacity_msat, required),
8755                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
8756                         (22, confirmations_required, option),
8757                         (24, force_close_spend_delay, option),
8758                         (26, is_outbound, required),
8759                         (28, is_channel_ready, required),
8760                         (30, is_usable, required),
8761                         (32, is_public, required),
8762                         (33, inbound_htlc_minimum_msat, option),
8763                         (35, inbound_htlc_maximum_msat, option),
8764                         (37, user_channel_id_high_opt, option),
8765                         (39, feerate_sat_per_1000_weight, option),
8766                         (41, channel_shutdown_state, option),
8767                 });
8768
8769                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8770                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8771                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
8772                 let user_channel_id = user_channel_id_low as u128 +
8773                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
8774
8775                 Ok(Self {
8776                         inbound_scid_alias,
8777                         channel_id: channel_id.0.unwrap(),
8778                         channel_type,
8779                         counterparty: counterparty.0.unwrap(),
8780                         outbound_scid_alias,
8781                         funding_txo,
8782                         config,
8783                         short_channel_id,
8784                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
8785                         unspendable_punishment_reserve,
8786                         user_channel_id,
8787                         balance_msat: balance_msat.0.unwrap(),
8788                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
8789                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
8790                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
8791                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
8792                         confirmations_required,
8793                         confirmations,
8794                         force_close_spend_delay,
8795                         is_outbound: is_outbound.0.unwrap(),
8796                         is_channel_ready: is_channel_ready.0.unwrap(),
8797                         is_usable: is_usable.0.unwrap(),
8798                         is_public: is_public.0.unwrap(),
8799                         inbound_htlc_minimum_msat,
8800                         inbound_htlc_maximum_msat,
8801                         feerate_sat_per_1000_weight,
8802                         channel_shutdown_state,
8803                 })
8804         }
8805 }
8806
8807 impl_writeable_tlv_based!(PhantomRouteHints, {
8808         (2, channels, required_vec),
8809         (4, phantom_scid, required),
8810         (6, real_node_pubkey, required),
8811 });
8812
8813 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
8814         (0, Forward) => {
8815                 (0, onion_packet, required),
8816                 (2, short_channel_id, required),
8817         },
8818         (1, Receive) => {
8819                 (0, payment_data, required),
8820                 (1, phantom_shared_secret, option),
8821                 (2, incoming_cltv_expiry, required),
8822                 (3, payment_metadata, option),
8823                 (5, custom_tlvs, optional_vec),
8824         },
8825         (2, ReceiveKeysend) => {
8826                 (0, payment_preimage, required),
8827                 (2, incoming_cltv_expiry, required),
8828                 (3, payment_metadata, option),
8829                 (4, payment_data, option), // Added in 0.0.116
8830                 (5, custom_tlvs, optional_vec),
8831         },
8832 ;);
8833
8834 impl_writeable_tlv_based!(PendingHTLCInfo, {
8835         (0, routing, required),
8836         (2, incoming_shared_secret, required),
8837         (4, payment_hash, required),
8838         (6, outgoing_amt_msat, required),
8839         (8, outgoing_cltv_value, required),
8840         (9, incoming_amt_msat, option),
8841         (10, skimmed_fee_msat, option),
8842 });
8843
8844
8845 impl Writeable for HTLCFailureMsg {
8846         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8847                 match self {
8848                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
8849                                 0u8.write(writer)?;
8850                                 channel_id.write(writer)?;
8851                                 htlc_id.write(writer)?;
8852                                 reason.write(writer)?;
8853                         },
8854                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
8855                                 channel_id, htlc_id, sha256_of_onion, failure_code
8856                         }) => {
8857                                 1u8.write(writer)?;
8858                                 channel_id.write(writer)?;
8859                                 htlc_id.write(writer)?;
8860                                 sha256_of_onion.write(writer)?;
8861                                 failure_code.write(writer)?;
8862                         },
8863                 }
8864                 Ok(())
8865         }
8866 }
8867
8868 impl Readable for HTLCFailureMsg {
8869         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8870                 let id: u8 = Readable::read(reader)?;
8871                 match id {
8872                         0 => {
8873                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
8874                                         channel_id: Readable::read(reader)?,
8875                                         htlc_id: Readable::read(reader)?,
8876                                         reason: Readable::read(reader)?,
8877                                 }))
8878                         },
8879                         1 => {
8880                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
8881                                         channel_id: Readable::read(reader)?,
8882                                         htlc_id: Readable::read(reader)?,
8883                                         sha256_of_onion: Readable::read(reader)?,
8884                                         failure_code: Readable::read(reader)?,
8885                                 }))
8886                         },
8887                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
8888                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
8889                         // messages contained in the variants.
8890                         // In version 0.0.101, support for reading the variants with these types was added, and
8891                         // we should migrate to writing these variants when UpdateFailHTLC or
8892                         // UpdateFailMalformedHTLC get TLV fields.
8893                         2 => {
8894                                 let length: BigSize = Readable::read(reader)?;
8895                                 let mut s = FixedLengthReader::new(reader, length.0);
8896                                 let res = Readable::read(&mut s)?;
8897                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
8898                                 Ok(HTLCFailureMsg::Relay(res))
8899                         },
8900                         3 => {
8901                                 let length: BigSize = Readable::read(reader)?;
8902                                 let mut s = FixedLengthReader::new(reader, length.0);
8903                                 let res = Readable::read(&mut s)?;
8904                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
8905                                 Ok(HTLCFailureMsg::Malformed(res))
8906                         },
8907                         _ => Err(DecodeError::UnknownRequiredFeature),
8908                 }
8909         }
8910 }
8911
8912 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
8913         (0, Forward),
8914         (1, Fail),
8915 );
8916
8917 impl_writeable_tlv_based!(HTLCPreviousHopData, {
8918         (0, short_channel_id, required),
8919         (1, phantom_shared_secret, option),
8920         (2, outpoint, required),
8921         (4, htlc_id, required),
8922         (6, incoming_packet_shared_secret, required),
8923         (7, user_channel_id, option),
8924 });
8925
8926 impl Writeable for ClaimableHTLC {
8927         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8928                 let (payment_data, keysend_preimage) = match &self.onion_payload {
8929                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
8930                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
8931                 };
8932                 write_tlv_fields!(writer, {
8933                         (0, self.prev_hop, required),
8934                         (1, self.total_msat, required),
8935                         (2, self.value, required),
8936                         (3, self.sender_intended_value, required),
8937                         (4, payment_data, option),
8938                         (5, self.total_value_received, option),
8939                         (6, self.cltv_expiry, required),
8940                         (8, keysend_preimage, option),
8941                         (10, self.counterparty_skimmed_fee_msat, option),
8942                 });
8943                 Ok(())
8944         }
8945 }
8946
8947 impl Readable for ClaimableHTLC {
8948         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8949                 _init_and_read_len_prefixed_tlv_fields!(reader, {
8950                         (0, prev_hop, required),
8951                         (1, total_msat, option),
8952                         (2, value_ser, required),
8953                         (3, sender_intended_value, option),
8954                         (4, payment_data_opt, option),
8955                         (5, total_value_received, option),
8956                         (6, cltv_expiry, required),
8957                         (8, keysend_preimage, option),
8958                         (10, counterparty_skimmed_fee_msat, option),
8959                 });
8960                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
8961                 let value = value_ser.0.unwrap();
8962                 let onion_payload = match keysend_preimage {
8963                         Some(p) => {
8964                                 if payment_data.is_some() {
8965                                         return Err(DecodeError::InvalidValue)
8966                                 }
8967                                 if total_msat.is_none() {
8968                                         total_msat = Some(value);
8969                                 }
8970                                 OnionPayload::Spontaneous(p)
8971                         },
8972                         None => {
8973                                 if total_msat.is_none() {
8974                                         if payment_data.is_none() {
8975                                                 return Err(DecodeError::InvalidValue)
8976                                         }
8977                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
8978                                 }
8979                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
8980                         },
8981                 };
8982                 Ok(Self {
8983                         prev_hop: prev_hop.0.unwrap(),
8984                         timer_ticks: 0,
8985                         value,
8986                         sender_intended_value: sender_intended_value.unwrap_or(value),
8987                         total_value_received,
8988                         total_msat: total_msat.unwrap(),
8989                         onion_payload,
8990                         cltv_expiry: cltv_expiry.0.unwrap(),
8991                         counterparty_skimmed_fee_msat,
8992                 })
8993         }
8994 }
8995
8996 impl Readable for HTLCSource {
8997         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8998                 let id: u8 = Readable::read(reader)?;
8999                 match id {
9000                         0 => {
9001                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9002                                 let mut first_hop_htlc_msat: u64 = 0;
9003                                 let mut path_hops = Vec::new();
9004                                 let mut payment_id = None;
9005                                 let mut payment_params: Option<PaymentParameters> = None;
9006                                 let mut blinded_tail: Option<BlindedTail> = None;
9007                                 read_tlv_fields!(reader, {
9008                                         (0, session_priv, required),
9009                                         (1, payment_id, option),
9010                                         (2, first_hop_htlc_msat, required),
9011                                         (4, path_hops, required_vec),
9012                                         (5, payment_params, (option: ReadableArgs, 0)),
9013                                         (6, blinded_tail, option),
9014                                 });
9015                                 if payment_id.is_none() {
9016                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9017                                         // instead.
9018                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9019                                 }
9020                                 let path = Path { hops: path_hops, blinded_tail };
9021                                 if path.hops.len() == 0 {
9022                                         return Err(DecodeError::InvalidValue);
9023                                 }
9024                                 if let Some(params) = payment_params.as_mut() {
9025                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9026                                                 if final_cltv_expiry_delta == &0 {
9027                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9028                                                 }
9029                                         }
9030                                 }
9031                                 Ok(HTLCSource::OutboundRoute {
9032                                         session_priv: session_priv.0.unwrap(),
9033                                         first_hop_htlc_msat,
9034                                         path,
9035                                         payment_id: payment_id.unwrap(),
9036                                 })
9037                         }
9038                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9039                         _ => Err(DecodeError::UnknownRequiredFeature),
9040                 }
9041         }
9042 }
9043
9044 impl Writeable for HTLCSource {
9045         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9046                 match self {
9047                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9048                                 0u8.write(writer)?;
9049                                 let payment_id_opt = Some(payment_id);
9050                                 write_tlv_fields!(writer, {
9051                                         (0, session_priv, required),
9052                                         (1, payment_id_opt, option),
9053                                         (2, first_hop_htlc_msat, required),
9054                                         // 3 was previously used to write a PaymentSecret for the payment.
9055                                         (4, path.hops, required_vec),
9056                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9057                                         (6, path.blinded_tail, option),
9058                                  });
9059                         }
9060                         HTLCSource::PreviousHopData(ref field) => {
9061                                 1u8.write(writer)?;
9062                                 field.write(writer)?;
9063                         }
9064                 }
9065                 Ok(())
9066         }
9067 }
9068
9069 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9070         (0, forward_info, required),
9071         (1, prev_user_channel_id, (default_value, 0)),
9072         (2, prev_short_channel_id, required),
9073         (4, prev_htlc_id, required),
9074         (6, prev_funding_outpoint, required),
9075 });
9076
9077 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
9078         (1, FailHTLC) => {
9079                 (0, htlc_id, required),
9080                 (2, err_packet, required),
9081         };
9082         (0, AddHTLC)
9083 );
9084
9085 impl_writeable_tlv_based!(PendingInboundPayment, {
9086         (0, payment_secret, required),
9087         (2, expiry_time, required),
9088         (4, user_payment_id, required),
9089         (6, payment_preimage, required),
9090         (8, min_value_msat, required),
9091 });
9092
9093 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>
9094 where
9095         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9096         T::Target: BroadcasterInterface,
9097         ES::Target: EntropySource,
9098         NS::Target: NodeSigner,
9099         SP::Target: SignerProvider,
9100         F::Target: FeeEstimator,
9101         R::Target: Router,
9102         L::Target: Logger,
9103 {
9104         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9105                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9106
9107                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9108
9109                 self.chain_hash.write(writer)?;
9110                 {
9111                         let best_block = self.best_block.read().unwrap();
9112                         best_block.height().write(writer)?;
9113                         best_block.block_hash().write(writer)?;
9114                 }
9115
9116                 let mut serializable_peer_count: u64 = 0;
9117                 {
9118                         let per_peer_state = self.per_peer_state.read().unwrap();
9119                         let mut number_of_funded_channels = 0;
9120                         for (_, peer_state_mutex) in per_peer_state.iter() {
9121                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9122                                 let peer_state = &mut *peer_state_lock;
9123                                 if !peer_state.ok_to_remove(false) {
9124                                         serializable_peer_count += 1;
9125                                 }
9126
9127                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9128                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9129                                 ).count();
9130                         }
9131
9132                         (number_of_funded_channels as u64).write(writer)?;
9133
9134                         for (_, peer_state_mutex) in per_peer_state.iter() {
9135                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9136                                 let peer_state = &mut *peer_state_lock;
9137                                 for channel in peer_state.channel_by_id.iter().filter_map(
9138                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9139                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9140                                         } else { None }
9141                                 ) {
9142                                         channel.write(writer)?;
9143                                 }
9144                         }
9145                 }
9146
9147                 {
9148                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9149                         (forward_htlcs.len() as u64).write(writer)?;
9150                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9151                                 short_channel_id.write(writer)?;
9152                                 (pending_forwards.len() as u64).write(writer)?;
9153                                 for forward in pending_forwards {
9154                                         forward.write(writer)?;
9155                                 }
9156                         }
9157                 }
9158
9159                 let per_peer_state = self.per_peer_state.write().unwrap();
9160
9161                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9162                 let claimable_payments = self.claimable_payments.lock().unwrap();
9163                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9164
9165                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9166                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9167                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9168                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9169                         payment_hash.write(writer)?;
9170                         (payment.htlcs.len() as u64).write(writer)?;
9171                         for htlc in payment.htlcs.iter() {
9172                                 htlc.write(writer)?;
9173                         }
9174                         htlc_purposes.push(&payment.purpose);
9175                         htlc_onion_fields.push(&payment.onion_fields);
9176                 }
9177
9178                 let mut monitor_update_blocked_actions_per_peer = None;
9179                 let mut peer_states = Vec::new();
9180                 for (_, peer_state_mutex) in per_peer_state.iter() {
9181                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9182                         // of a lockorder violation deadlock - no other thread can be holding any
9183                         // per_peer_state lock at all.
9184                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9185                 }
9186
9187                 (serializable_peer_count).write(writer)?;
9188                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9189                         // Peers which we have no channels to should be dropped once disconnected. As we
9190                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9191                         // consider all peers as disconnected here. There's therefore no need write peers with
9192                         // no channels.
9193                         if !peer_state.ok_to_remove(false) {
9194                                 peer_pubkey.write(writer)?;
9195                                 peer_state.latest_features.write(writer)?;
9196                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9197                                         monitor_update_blocked_actions_per_peer
9198                                                 .get_or_insert_with(Vec::new)
9199                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9200                                 }
9201                         }
9202                 }
9203
9204                 let events = self.pending_events.lock().unwrap();
9205                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9206                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9207                 // refuse to read the new ChannelManager.
9208                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9209                 if events_not_backwards_compatible {
9210                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9211                         // well save the space and not write any events here.
9212                         0u64.write(writer)?;
9213                 } else {
9214                         (events.len() as u64).write(writer)?;
9215                         for (event, _) in events.iter() {
9216                                 event.write(writer)?;
9217                         }
9218                 }
9219
9220                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
9221                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
9222                 // the closing monitor updates were always effectively replayed on startup (either directly
9223                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
9224                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
9225                 0u64.write(writer)?;
9226
9227                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
9228                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
9229                 // likely to be identical.
9230                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9231                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9232
9233                 (pending_inbound_payments.len() as u64).write(writer)?;
9234                 for (hash, pending_payment) in pending_inbound_payments.iter() {
9235                         hash.write(writer)?;
9236                         pending_payment.write(writer)?;
9237                 }
9238
9239                 // For backwards compat, write the session privs and their total length.
9240                 let mut num_pending_outbounds_compat: u64 = 0;
9241                 for (_, outbound) in pending_outbound_payments.iter() {
9242                         if !outbound.is_fulfilled() && !outbound.abandoned() {
9243                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
9244                         }
9245                 }
9246                 num_pending_outbounds_compat.write(writer)?;
9247                 for (_, outbound) in pending_outbound_payments.iter() {
9248                         match outbound {
9249                                 PendingOutboundPayment::Legacy { session_privs } |
9250                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9251                                         for session_priv in session_privs.iter() {
9252                                                 session_priv.write(writer)?;
9253                                         }
9254                                 }
9255                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
9256                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
9257                                 PendingOutboundPayment::Fulfilled { .. } => {},
9258                                 PendingOutboundPayment::Abandoned { .. } => {},
9259                         }
9260                 }
9261
9262                 // Encode without retry info for 0.0.101 compatibility.
9263                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
9264                 for (id, outbound) in pending_outbound_payments.iter() {
9265                         match outbound {
9266                                 PendingOutboundPayment::Legacy { session_privs } |
9267                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9268                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
9269                                 },
9270                                 _ => {},
9271                         }
9272                 }
9273
9274                 let mut pending_intercepted_htlcs = None;
9275                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
9276                 if our_pending_intercepts.len() != 0 {
9277                         pending_intercepted_htlcs = Some(our_pending_intercepts);
9278                 }
9279
9280                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
9281                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
9282                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
9283                         // map. Thus, if there are no entries we skip writing a TLV for it.
9284                         pending_claiming_payments = None;
9285                 }
9286
9287                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
9288                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9289                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
9290                                 if !updates.is_empty() {
9291                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
9292                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
9293                                 }
9294                         }
9295                 }
9296
9297                 write_tlv_fields!(writer, {
9298                         (1, pending_outbound_payments_no_retry, required),
9299                         (2, pending_intercepted_htlcs, option),
9300                         (3, pending_outbound_payments, required),
9301                         (4, pending_claiming_payments, option),
9302                         (5, self.our_network_pubkey, required),
9303                         (6, monitor_update_blocked_actions_per_peer, option),
9304                         (7, self.fake_scid_rand_bytes, required),
9305                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
9306                         (9, htlc_purposes, required_vec),
9307                         (10, in_flight_monitor_updates, option),
9308                         (11, self.probing_cookie_secret, required),
9309                         (13, htlc_onion_fields, optional_vec),
9310                 });
9311
9312                 Ok(())
9313         }
9314 }
9315
9316 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
9317         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9318                 (self.len() as u64).write(w)?;
9319                 for (event, action) in self.iter() {
9320                         event.write(w)?;
9321                         action.write(w)?;
9322                         #[cfg(debug_assertions)] {
9323                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
9324                                 // be persisted and are regenerated on restart. However, if such an event has a
9325                                 // post-event-handling action we'll write nothing for the event and would have to
9326                                 // either forget the action or fail on deserialization (which we do below). Thus,
9327                                 // check that the event is sane here.
9328                                 let event_encoded = event.encode();
9329                                 let event_read: Option<Event> =
9330                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
9331                                 if action.is_some() { assert!(event_read.is_some()); }
9332                         }
9333                 }
9334                 Ok(())
9335         }
9336 }
9337 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
9338         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9339                 let len: u64 = Readable::read(reader)?;
9340                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
9341                 let mut events: Self = VecDeque::with_capacity(cmp::min(
9342                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
9343                         len) as usize);
9344                 for _ in 0..len {
9345                         let ev_opt = MaybeReadable::read(reader)?;
9346                         let action = Readable::read(reader)?;
9347                         if let Some(ev) = ev_opt {
9348                                 events.push_back((ev, action));
9349                         } else if action.is_some() {
9350                                 return Err(DecodeError::InvalidValue);
9351                         }
9352                 }
9353                 Ok(events)
9354         }
9355 }
9356
9357 impl_writeable_tlv_based_enum!(ChannelShutdownState,
9358         (0, NotShuttingDown) => {},
9359         (2, ShutdownInitiated) => {},
9360         (4, ResolvingHTLCs) => {},
9361         (6, NegotiatingClosingFee) => {},
9362         (8, ShutdownComplete) => {}, ;
9363 );
9364
9365 /// Arguments for the creation of a ChannelManager that are not deserialized.
9366 ///
9367 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
9368 /// is:
9369 /// 1) Deserialize all stored [`ChannelMonitor`]s.
9370 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
9371 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
9372 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
9373 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
9374 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
9375 ///    same way you would handle a [`chain::Filter`] call using
9376 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
9377 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
9378 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
9379 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
9380 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
9381 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
9382 ///    the next step.
9383 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
9384 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
9385 ///
9386 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
9387 /// call any other methods on the newly-deserialized [`ChannelManager`].
9388 ///
9389 /// Note that because some channels may be closed during deserialization, it is critical that you
9390 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
9391 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
9392 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
9393 /// not force-close the same channels but consider them live), you may end up revoking a state for
9394 /// which you've already broadcasted the transaction.
9395 ///
9396 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
9397 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9398 where
9399         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9400         T::Target: BroadcasterInterface,
9401         ES::Target: EntropySource,
9402         NS::Target: NodeSigner,
9403         SP::Target: SignerProvider,
9404         F::Target: FeeEstimator,
9405         R::Target: Router,
9406         L::Target: Logger,
9407 {
9408         /// A cryptographically secure source of entropy.
9409         pub entropy_source: ES,
9410
9411         /// A signer that is able to perform node-scoped cryptographic operations.
9412         pub node_signer: NS,
9413
9414         /// The keys provider which will give us relevant keys. Some keys will be loaded during
9415         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
9416         /// signing data.
9417         pub signer_provider: SP,
9418
9419         /// The fee_estimator for use in the ChannelManager in the future.
9420         ///
9421         /// No calls to the FeeEstimator will be made during deserialization.
9422         pub fee_estimator: F,
9423         /// The chain::Watch for use in the ChannelManager in the future.
9424         ///
9425         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
9426         /// you have deserialized ChannelMonitors separately and will add them to your
9427         /// chain::Watch after deserializing this ChannelManager.
9428         pub chain_monitor: M,
9429
9430         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
9431         /// used to broadcast the latest local commitment transactions of channels which must be
9432         /// force-closed during deserialization.
9433         pub tx_broadcaster: T,
9434         /// The router which will be used in the ChannelManager in the future for finding routes
9435         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
9436         ///
9437         /// No calls to the router will be made during deserialization.
9438         pub router: R,
9439         /// The Logger for use in the ChannelManager and which may be used to log information during
9440         /// deserialization.
9441         pub logger: L,
9442         /// Default settings used for new channels. Any existing channels will continue to use the
9443         /// runtime settings which were stored when the ChannelManager was serialized.
9444         pub default_config: UserConfig,
9445
9446         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
9447         /// value.context.get_funding_txo() should be the key).
9448         ///
9449         /// If a monitor is inconsistent with the channel state during deserialization the channel will
9450         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
9451         /// is true for missing channels as well. If there is a monitor missing for which we find
9452         /// channel data Err(DecodeError::InvalidValue) will be returned.
9453         ///
9454         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
9455         /// this struct.
9456         ///
9457         /// This is not exported to bindings users because we have no HashMap bindings
9458         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
9459 }
9460
9461 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9462                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
9463 where
9464         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9465         T::Target: BroadcasterInterface,
9466         ES::Target: EntropySource,
9467         NS::Target: NodeSigner,
9468         SP::Target: SignerProvider,
9469         F::Target: FeeEstimator,
9470         R::Target: Router,
9471         L::Target: Logger,
9472 {
9473         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
9474         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
9475         /// populate a HashMap directly from C.
9476         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,
9477                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
9478                 Self {
9479                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
9480                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
9481                 }
9482         }
9483 }
9484
9485 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
9486 // SipmleArcChannelManager type:
9487 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9488         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
9489 where
9490         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9491         T::Target: BroadcasterInterface,
9492         ES::Target: EntropySource,
9493         NS::Target: NodeSigner,
9494         SP::Target: SignerProvider,
9495         F::Target: FeeEstimator,
9496         R::Target: Router,
9497         L::Target: Logger,
9498 {
9499         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9500                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
9501                 Ok((blockhash, Arc::new(chan_manager)))
9502         }
9503 }
9504
9505 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9506         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
9507 where
9508         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9509         T::Target: BroadcasterInterface,
9510         ES::Target: EntropySource,
9511         NS::Target: NodeSigner,
9512         SP::Target: SignerProvider,
9513         F::Target: FeeEstimator,
9514         R::Target: Router,
9515         L::Target: Logger,
9516 {
9517         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9518                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
9519
9520                 let chain_hash: ChainHash = Readable::read(reader)?;
9521                 let best_block_height: u32 = Readable::read(reader)?;
9522                 let best_block_hash: BlockHash = Readable::read(reader)?;
9523
9524                 let mut failed_htlcs = Vec::new();
9525
9526                 let channel_count: u64 = Readable::read(reader)?;
9527                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
9528                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9529                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9530                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9531                 let mut channel_closures = VecDeque::new();
9532                 let mut close_background_events = Vec::new();
9533                 for _ in 0..channel_count {
9534                         let mut channel: Channel<SP> = Channel::read(reader, (
9535                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
9536                         ))?;
9537                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
9538                         funding_txo_set.insert(funding_txo.clone());
9539                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
9540                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
9541                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
9542                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
9543                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9544                                         // But if the channel is behind of the monitor, close the channel:
9545                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
9546                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
9547                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9548                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
9549                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
9550                                         }
9551                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
9552                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
9553                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
9554                                         }
9555                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
9556                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
9557                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
9558                                         }
9559                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
9560                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
9561                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
9562                                         }
9563                                         let (monitor_update, mut new_failed_htlcs, batch_funding_txid) = channel.context.force_shutdown(true);
9564                                         if batch_funding_txid.is_some() {
9565                                                 return Err(DecodeError::InvalidValue);
9566                                         }
9567                                         if let Some((counterparty_node_id, funding_txo, update)) = monitor_update {
9568                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
9569                                                         counterparty_node_id, funding_txo, update
9570                                                 });
9571                                         }
9572                                         failed_htlcs.append(&mut new_failed_htlcs);
9573                                         channel_closures.push_back((events::Event::ChannelClosed {
9574                                                 channel_id: channel.context.channel_id(),
9575                                                 user_channel_id: channel.context.get_user_id(),
9576                                                 reason: ClosureReason::OutdatedChannelManager,
9577                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9578                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9579                                         }, None));
9580                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
9581                                                 let mut found_htlc = false;
9582                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
9583                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
9584                                                 }
9585                                                 if !found_htlc {
9586                                                         // If we have some HTLCs in the channel which are not present in the newer
9587                                                         // ChannelMonitor, they have been removed and should be failed back to
9588                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
9589                                                         // were actually claimed we'd have generated and ensured the previous-hop
9590                                                         // claim update ChannelMonitor updates were persisted prior to persising
9591                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
9592                                                         // backwards leg of the HTLC will simply be rejected.
9593                                                         log_info!(args.logger,
9594                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
9595                                                                 &channel.context.channel_id(), &payment_hash);
9596                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9597                                                 }
9598                                         }
9599                                 } else {
9600                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
9601                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
9602                                                 monitor.get_latest_update_id());
9603                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
9604                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9605                                         }
9606                                         if channel.context.is_funding_broadcast() {
9607                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
9608                                         }
9609                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
9610                                                 hash_map::Entry::Occupied(mut entry) => {
9611                                                         let by_id_map = entry.get_mut();
9612                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9613                                                 },
9614                                                 hash_map::Entry::Vacant(entry) => {
9615                                                         let mut by_id_map = HashMap::new();
9616                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9617                                                         entry.insert(by_id_map);
9618                                                 }
9619                                         }
9620                                 }
9621                         } else if channel.is_awaiting_initial_mon_persist() {
9622                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
9623                                 // was in-progress, we never broadcasted the funding transaction and can still
9624                                 // safely discard the channel.
9625                                 let _ = channel.context.force_shutdown(false);
9626                                 channel_closures.push_back((events::Event::ChannelClosed {
9627                                         channel_id: channel.context.channel_id(),
9628                                         user_channel_id: channel.context.get_user_id(),
9629                                         reason: ClosureReason::DisconnectedPeer,
9630                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9631                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9632                                 }, None));
9633                         } else {
9634                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
9635                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9636                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9637                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
9638                                 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");
9639                                 return Err(DecodeError::InvalidValue);
9640                         }
9641                 }
9642
9643                 for (funding_txo, _) in args.channel_monitors.iter() {
9644                         if !funding_txo_set.contains(funding_txo) {
9645                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
9646                                         &funding_txo.to_channel_id());
9647                                 let monitor_update = ChannelMonitorUpdate {
9648                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
9649                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
9650                                 };
9651                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
9652                         }
9653                 }
9654
9655                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
9656                 let forward_htlcs_count: u64 = Readable::read(reader)?;
9657                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
9658                 for _ in 0..forward_htlcs_count {
9659                         let short_channel_id = Readable::read(reader)?;
9660                         let pending_forwards_count: u64 = Readable::read(reader)?;
9661                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
9662                         for _ in 0..pending_forwards_count {
9663                                 pending_forwards.push(Readable::read(reader)?);
9664                         }
9665                         forward_htlcs.insert(short_channel_id, pending_forwards);
9666                 }
9667
9668                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
9669                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
9670                 for _ in 0..claimable_htlcs_count {
9671                         let payment_hash = Readable::read(reader)?;
9672                         let previous_hops_len: u64 = Readable::read(reader)?;
9673                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
9674                         for _ in 0..previous_hops_len {
9675                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
9676                         }
9677                         claimable_htlcs_list.push((payment_hash, previous_hops));
9678                 }
9679
9680                 let peer_state_from_chans = |channel_by_id| {
9681                         PeerState {
9682                                 channel_by_id,
9683                                 inbound_channel_request_by_id: HashMap::new(),
9684                                 latest_features: InitFeatures::empty(),
9685                                 pending_msg_events: Vec::new(),
9686                                 in_flight_monitor_updates: BTreeMap::new(),
9687                                 monitor_update_blocked_actions: BTreeMap::new(),
9688                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
9689                                 is_connected: false,
9690                         }
9691                 };
9692
9693                 let peer_count: u64 = Readable::read(reader)?;
9694                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
9695                 for _ in 0..peer_count {
9696                         let peer_pubkey = Readable::read(reader)?;
9697                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
9698                         let mut peer_state = peer_state_from_chans(peer_chans);
9699                         peer_state.latest_features = Readable::read(reader)?;
9700                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
9701                 }
9702
9703                 let event_count: u64 = Readable::read(reader)?;
9704                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
9705                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
9706                 for _ in 0..event_count {
9707                         match MaybeReadable::read(reader)? {
9708                                 Some(event) => pending_events_read.push_back((event, None)),
9709                                 None => continue,
9710                         }
9711                 }
9712
9713                 let background_event_count: u64 = Readable::read(reader)?;
9714                 for _ in 0..background_event_count {
9715                         match <u8 as Readable>::read(reader)? {
9716                                 0 => {
9717                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
9718                                         // however we really don't (and never did) need them - we regenerate all
9719                                         // on-startup monitor updates.
9720                                         let _: OutPoint = Readable::read(reader)?;
9721                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
9722                                 }
9723                                 _ => return Err(DecodeError::InvalidValue),
9724                         }
9725                 }
9726
9727                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
9728                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
9729
9730                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
9731                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
9732                 for _ in 0..pending_inbound_payment_count {
9733                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
9734                                 return Err(DecodeError::InvalidValue);
9735                         }
9736                 }
9737
9738                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
9739                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
9740                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
9741                 for _ in 0..pending_outbound_payments_count_compat {
9742                         let session_priv = Readable::read(reader)?;
9743                         let payment = PendingOutboundPayment::Legacy {
9744                                 session_privs: [session_priv].iter().cloned().collect()
9745                         };
9746                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
9747                                 return Err(DecodeError::InvalidValue)
9748                         };
9749                 }
9750
9751                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
9752                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
9753                 let mut pending_outbound_payments = None;
9754                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
9755                 let mut received_network_pubkey: Option<PublicKey> = None;
9756                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
9757                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
9758                 let mut claimable_htlc_purposes = None;
9759                 let mut claimable_htlc_onion_fields = None;
9760                 let mut pending_claiming_payments = Some(HashMap::new());
9761                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
9762                 let mut events_override = None;
9763                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
9764                 read_tlv_fields!(reader, {
9765                         (1, pending_outbound_payments_no_retry, option),
9766                         (2, pending_intercepted_htlcs, option),
9767                         (3, pending_outbound_payments, option),
9768                         (4, pending_claiming_payments, option),
9769                         (5, received_network_pubkey, option),
9770                         (6, monitor_update_blocked_actions_per_peer, option),
9771                         (7, fake_scid_rand_bytes, option),
9772                         (8, events_override, option),
9773                         (9, claimable_htlc_purposes, optional_vec),
9774                         (10, in_flight_monitor_updates, option),
9775                         (11, probing_cookie_secret, option),
9776                         (13, claimable_htlc_onion_fields, optional_vec),
9777                 });
9778                 if fake_scid_rand_bytes.is_none() {
9779                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
9780                 }
9781
9782                 if probing_cookie_secret.is_none() {
9783                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
9784                 }
9785
9786                 if let Some(events) = events_override {
9787                         pending_events_read = events;
9788                 }
9789
9790                 if !channel_closures.is_empty() {
9791                         pending_events_read.append(&mut channel_closures);
9792                 }
9793
9794                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
9795                         pending_outbound_payments = Some(pending_outbound_payments_compat);
9796                 } else if pending_outbound_payments.is_none() {
9797                         let mut outbounds = HashMap::new();
9798                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
9799                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
9800                         }
9801                         pending_outbound_payments = Some(outbounds);
9802                 }
9803                 let pending_outbounds = OutboundPayments {
9804                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
9805                         retry_lock: Mutex::new(())
9806                 };
9807
9808                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
9809                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
9810                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
9811                 // replayed, and for each monitor update we have to replay we have to ensure there's a
9812                 // `ChannelMonitor` for it.
9813                 //
9814                 // In order to do so we first walk all of our live channels (so that we can check their
9815                 // state immediately after doing the update replays, when we have the `update_id`s
9816                 // available) and then walk any remaining in-flight updates.
9817                 //
9818                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
9819                 let mut pending_background_events = Vec::new();
9820                 macro_rules! handle_in_flight_updates {
9821                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
9822                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
9823                         ) => { {
9824                                 let mut max_in_flight_update_id = 0;
9825                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
9826                                 for update in $chan_in_flight_upds.iter() {
9827                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
9828                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
9829                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
9830                                         pending_background_events.push(
9831                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
9832                                                         counterparty_node_id: $counterparty_node_id,
9833                                                         funding_txo: $funding_txo,
9834                                                         update: update.clone(),
9835                                                 });
9836                                 }
9837                                 if $chan_in_flight_upds.is_empty() {
9838                                         // We had some updates to apply, but it turns out they had completed before we
9839                                         // were serialized, we just weren't notified of that. Thus, we may have to run
9840                                         // the completion actions for any monitor updates, but otherwise are done.
9841                                         pending_background_events.push(
9842                                                 BackgroundEvent::MonitorUpdatesComplete {
9843                                                         counterparty_node_id: $counterparty_node_id,
9844                                                         channel_id: $funding_txo.to_channel_id(),
9845                                                 });
9846                                 }
9847                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
9848                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
9849                                         return Err(DecodeError::InvalidValue);
9850                                 }
9851                                 max_in_flight_update_id
9852                         } }
9853                 }
9854
9855                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
9856                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
9857                         let peer_state = &mut *peer_state_lock;
9858                         for phase in peer_state.channel_by_id.values() {
9859                                 if let ChannelPhase::Funded(chan) = phase {
9860                                         // Channels that were persisted have to be funded, otherwise they should have been
9861                                         // discarded.
9862                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
9863                                         let monitor = args.channel_monitors.get(&funding_txo)
9864                                                 .expect("We already checked for monitor presence when loading channels");
9865                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
9866                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
9867                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
9868                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
9869                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
9870                                                                         funding_txo, monitor, peer_state, ""));
9871                                                 }
9872                                         }
9873                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
9874                                                 // If the channel is ahead of the monitor, return InvalidValue:
9875                                                 log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
9876                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
9877                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
9878                                                 log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
9879                                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9880                                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9881                                                 log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
9882                                                 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");
9883                                                 return Err(DecodeError::InvalidValue);
9884                                         }
9885                                 } else {
9886                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
9887                                         // created in this `channel_by_id` map.
9888                                         debug_assert!(false);
9889                                         return Err(DecodeError::InvalidValue);
9890                                 }
9891                         }
9892                 }
9893
9894                 if let Some(in_flight_upds) = in_flight_monitor_updates {
9895                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
9896                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
9897                                         // Now that we've removed all the in-flight monitor updates for channels that are
9898                                         // still open, we need to replay any monitor updates that are for closed channels,
9899                                         // creating the neccessary peer_state entries as we go.
9900                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
9901                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
9902                                         });
9903                                         let mut peer_state = peer_state_mutex.lock().unwrap();
9904                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
9905                                                 funding_txo, monitor, peer_state, "closed ");
9906                                 } else {
9907                                         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!");
9908                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
9909                                                 &funding_txo.to_channel_id());
9910                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9911                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9912                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
9913                                         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");
9914                                         return Err(DecodeError::InvalidValue);
9915                                 }
9916                         }
9917                 }
9918
9919                 // Note that we have to do the above replays before we push new monitor updates.
9920                 pending_background_events.append(&mut close_background_events);
9921
9922                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
9923                 // should ensure we try them again on the inbound edge. We put them here and do so after we
9924                 // have a fully-constructed `ChannelManager` at the end.
9925                 let mut pending_claims_to_replay = Vec::new();
9926
9927                 {
9928                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
9929                         // ChannelMonitor data for any channels for which we do not have authorative state
9930                         // (i.e. those for which we just force-closed above or we otherwise don't have a
9931                         // corresponding `Channel` at all).
9932                         // This avoids several edge-cases where we would otherwise "forget" about pending
9933                         // payments which are still in-flight via their on-chain state.
9934                         // We only rebuild the pending payments map if we were most recently serialized by
9935                         // 0.0.102+
9936                         for (_, monitor) in args.channel_monitors.iter() {
9937                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
9938                                 if counterparty_opt.is_none() {
9939                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
9940                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
9941                                                         if path.hops.is_empty() {
9942                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
9943                                                                 return Err(DecodeError::InvalidValue);
9944                                                         }
9945
9946                                                         let path_amt = path.final_value_msat();
9947                                                         let mut session_priv_bytes = [0; 32];
9948                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
9949                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
9950                                                                 hash_map::Entry::Occupied(mut entry) => {
9951                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
9952                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
9953                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), &htlc.payment_hash);
9954                                                                 },
9955                                                                 hash_map::Entry::Vacant(entry) => {
9956                                                                         let path_fee = path.fee_msat();
9957                                                                         entry.insert(PendingOutboundPayment::Retryable {
9958                                                                                 retry_strategy: None,
9959                                                                                 attempts: PaymentAttempts::new(),
9960                                                                                 payment_params: None,
9961                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
9962                                                                                 payment_hash: htlc.payment_hash,
9963                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
9964                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
9965                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
9966                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
9967                                                                                 pending_amt_msat: path_amt,
9968                                                                                 pending_fee_msat: Some(path_fee),
9969                                                                                 total_msat: path_amt,
9970                                                                                 starting_block_height: best_block_height,
9971                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
9972                                                                         });
9973                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
9974                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
9975                                                                 }
9976                                                         }
9977                                                 }
9978                                         }
9979                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
9980                                                 match htlc_source {
9981                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
9982                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
9983                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
9984                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
9985                                                                 };
9986                                                                 // The ChannelMonitor is now responsible for this HTLC's
9987                                                                 // failure/success and will let us know what its outcome is. If we
9988                                                                 // still have an entry for this HTLC in `forward_htlcs` or
9989                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
9990                                                                 // the monitor was when forwarding the payment.
9991                                                                 forward_htlcs.retain(|_, forwards| {
9992                                                                         forwards.retain(|forward| {
9993                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
9994                                                                                         if pending_forward_matches_htlc(&htlc_info) {
9995                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
9996                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
9997                                                                                                 false
9998                                                                                         } else { true }
9999                                                                                 } else { true }
10000                                                                         });
10001                                                                         !forwards.is_empty()
10002                                                                 });
10003                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10004                                                                         if pending_forward_matches_htlc(&htlc_info) {
10005                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10006                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
10007                                                                                 pending_events_read.retain(|(event, _)| {
10008                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10009                                                                                                 intercepted_id != ev_id
10010                                                                                         } else { true }
10011                                                                                 });
10012                                                                                 false
10013                                                                         } else { true }
10014                                                                 });
10015                                                         },
10016                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10017                                                                 if let Some(preimage) = preimage_opt {
10018                                                                         let pending_events = Mutex::new(pending_events_read);
10019                                                                         // Note that we set `from_onchain` to "false" here,
10020                                                                         // deliberately keeping the pending payment around forever.
10021                                                                         // Given it should only occur when we have a channel we're
10022                                                                         // force-closing for being stale that's okay.
10023                                                                         // The alternative would be to wipe the state when claiming,
10024                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10025                                                                         // it and the `PaymentSent` on every restart until the
10026                                                                         // `ChannelMonitor` is removed.
10027                                                                         let compl_action =
10028                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10029                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10030                                                                                         counterparty_node_id: path.hops[0].pubkey,
10031                                                                                 };
10032                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10033                                                                                 path, false, compl_action, &pending_events, &args.logger);
10034                                                                         pending_events_read = pending_events.into_inner().unwrap();
10035                                                                 }
10036                                                         },
10037                                                 }
10038                                         }
10039                                 }
10040
10041                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10042                                 // preimages from it which may be needed in upstream channels for forwarded
10043                                 // payments.
10044                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10045                                         .into_iter()
10046                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10047                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10048                                                         if let Some(payment_preimage) = preimage_opt {
10049                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10050                                                                         // Check if `counterparty_opt.is_none()` to see if the
10051                                                                         // downstream chan is closed (because we don't have a
10052                                                                         // channel_id -> peer map entry).
10053                                                                         counterparty_opt.is_none(),
10054                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10055                                                                         monitor.get_funding_txo().0))
10056                                                         } else { None }
10057                                                 } else {
10058                                                         // If it was an outbound payment, we've handled it above - if a preimage
10059                                                         // came in and we persisted the `ChannelManager` we either handled it and
10060                                                         // are good to go or the channel force-closed - we don't have to handle the
10061                                                         // channel still live case here.
10062                                                         None
10063                                                 }
10064                                         });
10065                                 for tuple in outbound_claimed_htlcs_iter {
10066                                         pending_claims_to_replay.push(tuple);
10067                                 }
10068                         }
10069                 }
10070
10071                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10072                         // If we have pending HTLCs to forward, assume we either dropped a
10073                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10074                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10075                         // constant as enough time has likely passed that we should simply handle the forwards
10076                         // now, or at least after the user gets a chance to reconnect to our peers.
10077                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10078                                 time_forwardable: Duration::from_secs(2),
10079                         }, None));
10080                 }
10081
10082                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10083                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10084
10085                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10086                 if let Some(purposes) = claimable_htlc_purposes {
10087                         if purposes.len() != claimable_htlcs_list.len() {
10088                                 return Err(DecodeError::InvalidValue);
10089                         }
10090                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10091                                 if onion_fields.len() != claimable_htlcs_list.len() {
10092                                         return Err(DecodeError::InvalidValue);
10093                                 }
10094                                 for (purpose, (onion, (payment_hash, htlcs))) in
10095                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10096                                 {
10097                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10098                                                 purpose, htlcs, onion_fields: onion,
10099                                         });
10100                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10101                                 }
10102                         } else {
10103                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10104                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10105                                                 purpose, htlcs, onion_fields: None,
10106                                         });
10107                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10108                                 }
10109                         }
10110                 } else {
10111                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10112                         // include a `_legacy_hop_data` in the `OnionPayload`.
10113                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10114                                 if htlcs.is_empty() {
10115                                         return Err(DecodeError::InvalidValue);
10116                                 }
10117                                 let purpose = match &htlcs[0].onion_payload {
10118                                         OnionPayload::Invoice { _legacy_hop_data } => {
10119                                                 if let Some(hop_data) = _legacy_hop_data {
10120                                                         events::PaymentPurpose::InvoicePayment {
10121                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10122                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10123                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10124                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10125                                                                                 Err(()) => {
10126                                                                                         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);
10127                                                                                         return Err(DecodeError::InvalidValue);
10128                                                                                 }
10129                                                                         }
10130                                                                 },
10131                                                                 payment_secret: hop_data.payment_secret,
10132                                                         }
10133                                                 } else { return Err(DecodeError::InvalidValue); }
10134                                         },
10135                                         OnionPayload::Spontaneous(payment_preimage) =>
10136                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10137                                 };
10138                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10139                                         purpose, htlcs, onion_fields: None,
10140                                 });
10141                         }
10142                 }
10143
10144                 let mut secp_ctx = Secp256k1::new();
10145                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10146
10147                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10148                         Ok(key) => key,
10149                         Err(()) => return Err(DecodeError::InvalidValue)
10150                 };
10151                 if let Some(network_pubkey) = received_network_pubkey {
10152                         if network_pubkey != our_network_pubkey {
10153                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10154                                 return Err(DecodeError::InvalidValue);
10155                         }
10156                 }
10157
10158                 let mut outbound_scid_aliases = HashSet::new();
10159                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10160                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10161                         let peer_state = &mut *peer_state_lock;
10162                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10163                                 if let ChannelPhase::Funded(chan) = phase {
10164                                         if chan.context.outbound_scid_alias() == 0 {
10165                                                 let mut outbound_scid_alias;
10166                                                 loop {
10167                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10168                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10169                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10170                                                 }
10171                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10172                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10173                                                 // Note that in rare cases its possible to hit this while reading an older
10174                                                 // channel if we just happened to pick a colliding outbound alias above.
10175                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10176                                                 return Err(DecodeError::InvalidValue);
10177                                         }
10178                                         if chan.context.is_usable() {
10179                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10180                                                         // Note that in rare cases its possible to hit this while reading an older
10181                                                         // channel if we just happened to pick a colliding outbound alias above.
10182                                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10183                                                         return Err(DecodeError::InvalidValue);
10184                                                 }
10185                                         }
10186                                 } else {
10187                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10188                                         // created in this `channel_by_id` map.
10189                                         debug_assert!(false);
10190                                         return Err(DecodeError::InvalidValue);
10191                                 }
10192                         }
10193                 }
10194
10195                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10196
10197                 for (_, monitor) in args.channel_monitors.iter() {
10198                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10199                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10200                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10201                                         let mut claimable_amt_msat = 0;
10202                                         let mut receiver_node_id = Some(our_network_pubkey);
10203                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
10204                                         if phantom_shared_secret.is_some() {
10205                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
10206                                                         .expect("Failed to get node_id for phantom node recipient");
10207                                                 receiver_node_id = Some(phantom_pubkey)
10208                                         }
10209                                         for claimable_htlc in &payment.htlcs {
10210                                                 claimable_amt_msat += claimable_htlc.value;
10211
10212                                                 // Add a holding-cell claim of the payment to the Channel, which should be
10213                                                 // applied ~immediately on peer reconnection. Because it won't generate a
10214                                                 // new commitment transaction we can just provide the payment preimage to
10215                                                 // the corresponding ChannelMonitor and nothing else.
10216                                                 //
10217                                                 // We do so directly instead of via the normal ChannelMonitor update
10218                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
10219                                                 // we're not allowed to call it directly yet. Further, we do the update
10220                                                 // without incrementing the ChannelMonitor update ID as there isn't any
10221                                                 // reason to.
10222                                                 // If we were to generate a new ChannelMonitor update ID here and then
10223                                                 // crash before the user finishes block connect we'd end up force-closing
10224                                                 // this channel as well. On the flip side, there's no harm in restarting
10225                                                 // without the new monitor persisted - we'll end up right back here on
10226                                                 // restart.
10227                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
10228                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
10229                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
10230                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10231                                                         let peer_state = &mut *peer_state_lock;
10232                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
10233                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
10234                                                         }
10235                                                 }
10236                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
10237                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
10238                                                 }
10239                                         }
10240                                         pending_events_read.push_back((events::Event::PaymentClaimed {
10241                                                 receiver_node_id,
10242                                                 payment_hash,
10243                                                 purpose: payment.purpose,
10244                                                 amount_msat: claimable_amt_msat,
10245                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
10246                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
10247                                         }, None));
10248                                 }
10249                         }
10250                 }
10251
10252                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
10253                         if let Some(peer_state) = per_peer_state.get(&node_id) {
10254                                 for (_, actions) in monitor_update_blocked_actions.iter() {
10255                                         for action in actions.iter() {
10256                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
10257                                                         downstream_counterparty_and_funding_outpoint:
10258                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
10259                                                 } = action {
10260                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
10261                                                                 log_trace!(args.logger,
10262                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
10263                                                                         blocked_channel_outpoint.to_channel_id());
10264                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
10265                                                                         .entry(blocked_channel_outpoint.to_channel_id())
10266                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
10267                                                         } else {
10268                                                                 // If the channel we were blocking has closed, we don't need to
10269                                                                 // worry about it - the blocked monitor update should never have
10270                                                                 // been released from the `Channel` object so it can't have
10271                                                                 // completed, and if the channel closed there's no reason to bother
10272                                                                 // anymore.
10273                                                         }
10274                                                 }
10275                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
10276                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
10277                                                 }
10278                                         }
10279                                 }
10280                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
10281                         } else {
10282                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
10283                                 return Err(DecodeError::InvalidValue);
10284                         }
10285                 }
10286
10287                 let channel_manager = ChannelManager {
10288                         chain_hash,
10289                         fee_estimator: bounded_fee_estimator,
10290                         chain_monitor: args.chain_monitor,
10291                         tx_broadcaster: args.tx_broadcaster,
10292                         router: args.router,
10293
10294                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
10295
10296                         inbound_payment_key: expanded_inbound_key,
10297                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
10298                         pending_outbound_payments: pending_outbounds,
10299                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
10300
10301                         forward_htlcs: Mutex::new(forward_htlcs),
10302                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
10303                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
10304                         id_to_peer: Mutex::new(id_to_peer),
10305                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
10306                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
10307
10308                         probing_cookie_secret: probing_cookie_secret.unwrap(),
10309
10310                         our_network_pubkey,
10311                         secp_ctx,
10312
10313                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
10314
10315                         per_peer_state: FairRwLock::new(per_peer_state),
10316
10317                         pending_events: Mutex::new(pending_events_read),
10318                         pending_events_processor: AtomicBool::new(false),
10319                         pending_background_events: Mutex::new(pending_background_events),
10320                         total_consistency_lock: RwLock::new(()),
10321                         background_events_processed_since_startup: AtomicBool::new(false),
10322
10323                         event_persist_notifier: Notifier::new(),
10324                         needs_persist_flag: AtomicBool::new(false),
10325
10326                         funding_batch_states: Mutex::new(BTreeMap::new()),
10327
10328                         entropy_source: args.entropy_source,
10329                         node_signer: args.node_signer,
10330                         signer_provider: args.signer_provider,
10331
10332                         logger: args.logger,
10333                         default_configuration: args.default_config,
10334                 };
10335
10336                 for htlc_source in failed_htlcs.drain(..) {
10337                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
10338                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
10339                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
10340                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
10341                 }
10342
10343                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
10344                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
10345                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
10346                         // channel is closed we just assume that it probably came from an on-chain claim.
10347                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
10348                                 downstream_closed, true, downstream_node_id, downstream_funding);
10349                 }
10350
10351                 //TODO: Broadcast channel update for closed channels, but only after we've made a
10352                 //connection or two.
10353
10354                 Ok((best_block_hash.clone(), channel_manager))
10355         }
10356 }
10357
10358 #[cfg(test)]
10359 mod tests {
10360         use bitcoin::hashes::Hash;
10361         use bitcoin::hashes::sha256::Hash as Sha256;
10362         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10363         use core::sync::atomic::Ordering;
10364         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
10365         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
10366         use crate::ln::ChannelId;
10367         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
10368         use crate::ln::functional_test_utils::*;
10369         use crate::ln::msgs::{self, ErrorAction};
10370         use crate::ln::msgs::ChannelMessageHandler;
10371         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
10372         use crate::util::errors::APIError;
10373         use crate::util::test_utils;
10374         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
10375         use crate::sign::EntropySource;
10376
10377         #[test]
10378         fn test_notify_limits() {
10379                 // Check that a few cases which don't require the persistence of a new ChannelManager,
10380                 // indeed, do not cause the persistence of a new ChannelManager.
10381                 let chanmon_cfgs = create_chanmon_cfgs(3);
10382                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10383                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10384                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10385
10386                 // All nodes start with a persistable update pending as `create_network` connects each node
10387                 // with all other nodes to make most tests simpler.
10388                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10389                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10390                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10391
10392                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10393
10394                 // We check that the channel info nodes have doesn't change too early, even though we try
10395                 // to connect messages with new values
10396                 chan.0.contents.fee_base_msat *= 2;
10397                 chan.1.contents.fee_base_msat *= 2;
10398                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
10399                         &nodes[1].node.get_our_node_id()).pop().unwrap();
10400                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
10401                         &nodes[0].node.get_our_node_id()).pop().unwrap();
10402
10403                 // The first two nodes (which opened a channel) should now require fresh persistence
10404                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10405                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10406                 // ... but the last node should not.
10407                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10408                 // After persisting the first two nodes they should no longer need fresh persistence.
10409                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10410                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10411
10412                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
10413                 // about the channel.
10414                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
10415                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
10416                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10417
10418                 // The nodes which are a party to the channel should also ignore messages from unrelated
10419                 // parties.
10420                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10421                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10422                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10423                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10424                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10425                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10426
10427                 // At this point the channel info given by peers should still be the same.
10428                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10429                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10430
10431                 // An earlier version of handle_channel_update didn't check the directionality of the
10432                 // update message and would always update the local fee info, even if our peer was
10433                 // (spuriously) forwarding us our own channel_update.
10434                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
10435                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
10436                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
10437
10438                 // First deliver each peers' own message, checking that the node doesn't need to be
10439                 // persisted and that its channel info remains the same.
10440                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
10441                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
10442                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10443                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10444                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10445                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10446
10447                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
10448                 // the channel info has updated.
10449                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
10450                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
10451                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10452                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10453                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
10454                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
10455         }
10456
10457         #[test]
10458         fn test_keysend_dup_hash_partial_mpp() {
10459                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
10460                 // expected.
10461                 let chanmon_cfgs = create_chanmon_cfgs(2);
10462                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10463                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10464                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10465                 create_announced_chan_between_nodes(&nodes, 0, 1);
10466
10467                 // First, send a partial MPP payment.
10468                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
10469                 let mut mpp_route = route.clone();
10470                 mpp_route.paths.push(mpp_route.paths[0].clone());
10471
10472                 let payment_id = PaymentId([42; 32]);
10473                 // Use the utility function send_payment_along_path to send the payment with MPP data which
10474                 // indicates there are more HTLCs coming.
10475                 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.
10476                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
10477                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
10478                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
10479                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
10480                 check_added_monitors!(nodes[0], 1);
10481                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10482                 assert_eq!(events.len(), 1);
10483                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10484
10485                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
10486                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10487                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10488                 check_added_monitors!(nodes[0], 1);
10489                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10490                 assert_eq!(events.len(), 1);
10491                 let ev = events.drain(..).next().unwrap();
10492                 let payment_event = SendEvent::from_event(ev);
10493                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10494                 check_added_monitors!(nodes[1], 0);
10495                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10496                 expect_pending_htlcs_forwardable!(nodes[1]);
10497                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
10498                 check_added_monitors!(nodes[1], 1);
10499                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10500                 assert!(updates.update_add_htlcs.is_empty());
10501                 assert!(updates.update_fulfill_htlcs.is_empty());
10502                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10503                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10504                 assert!(updates.update_fee.is_none());
10505                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10506                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10507                 expect_payment_failed!(nodes[0], our_payment_hash, true);
10508
10509                 // Send the second half of the original MPP payment.
10510                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
10511                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
10512                 check_added_monitors!(nodes[0], 1);
10513                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10514                 assert_eq!(events.len(), 1);
10515                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
10516
10517                 // Claim the full MPP payment. Note that we can't use a test utility like
10518                 // claim_funds_along_route because the ordering of the messages causes the second half of the
10519                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
10520                 // lightning messages manually.
10521                 nodes[1].node.claim_funds(payment_preimage);
10522                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
10523                 check_added_monitors!(nodes[1], 2);
10524
10525                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10526                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
10527                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
10528                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
10529                 check_added_monitors!(nodes[0], 1);
10530                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10531                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
10532                 check_added_monitors!(nodes[1], 1);
10533                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10534                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
10535                 check_added_monitors!(nodes[1], 1);
10536                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10537                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
10538                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
10539                 check_added_monitors!(nodes[0], 1);
10540                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10541                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
10542                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10543                 check_added_monitors!(nodes[0], 1);
10544                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
10545                 check_added_monitors!(nodes[1], 1);
10546                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
10547                 check_added_monitors!(nodes[1], 1);
10548                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10549                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
10550                 check_added_monitors!(nodes[0], 1);
10551
10552                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
10553                 // path's success and a PaymentPathSuccessful event for each path's success.
10554                 let events = nodes[0].node.get_and_clear_pending_events();
10555                 assert_eq!(events.len(), 2);
10556                 match events[0] {
10557                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10558                                 assert_eq!(payment_id, *actual_payment_id);
10559                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10560                                 assert_eq!(route.paths[0], *path);
10561                         },
10562                         _ => panic!("Unexpected event"),
10563                 }
10564                 match events[1] {
10565                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10566                                 assert_eq!(payment_id, *actual_payment_id);
10567                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10568                                 assert_eq!(route.paths[0], *path);
10569                         },
10570                         _ => panic!("Unexpected event"),
10571                 }
10572         }
10573
10574         #[test]
10575         fn test_keysend_dup_payment_hash() {
10576                 do_test_keysend_dup_payment_hash(false);
10577                 do_test_keysend_dup_payment_hash(true);
10578         }
10579
10580         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
10581                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
10582                 //      outbound regular payment fails as expected.
10583                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
10584                 //      fails as expected.
10585                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
10586                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
10587                 //      reject MPP keysend payments, since in this case where the payment has no payment
10588                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
10589                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
10590                 //      payment secrets and reject otherwise.
10591                 let chanmon_cfgs = create_chanmon_cfgs(2);
10592                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10593                 let mut mpp_keysend_cfg = test_default_channel_config();
10594                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
10595                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
10596                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10597                 create_announced_chan_between_nodes(&nodes, 0, 1);
10598                 let scorer = test_utils::TestScorer::new();
10599                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10600
10601                 // To start (1), send a regular payment but don't claim it.
10602                 let expected_route = [&nodes[1]];
10603                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
10604
10605                 // Next, attempt a keysend payment and make sure it fails.
10606                 let route_params = RouteParameters::from_payment_params_and_value(
10607                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
10608                         TEST_FINAL_CLTV, false), 100_000);
10609                 let route = find_route(
10610                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10611                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10612                 ).unwrap();
10613                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10614                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10615                 check_added_monitors!(nodes[0], 1);
10616                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10617                 assert_eq!(events.len(), 1);
10618                 let ev = events.drain(..).next().unwrap();
10619                 let payment_event = SendEvent::from_event(ev);
10620                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10621                 check_added_monitors!(nodes[1], 0);
10622                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10623                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
10624                 // fails), the second will process the resulting failure and fail the HTLC backward
10625                 expect_pending_htlcs_forwardable!(nodes[1]);
10626                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10627                 check_added_monitors!(nodes[1], 1);
10628                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10629                 assert!(updates.update_add_htlcs.is_empty());
10630                 assert!(updates.update_fulfill_htlcs.is_empty());
10631                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10632                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10633                 assert!(updates.update_fee.is_none());
10634                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10635                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10636                 expect_payment_failed!(nodes[0], payment_hash, true);
10637
10638                 // Finally, claim the original payment.
10639                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10640
10641                 // To start (2), send a keysend payment but don't claim it.
10642                 let payment_preimage = PaymentPreimage([42; 32]);
10643                 let route = find_route(
10644                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10645                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10646                 ).unwrap();
10647                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10648                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10649                 check_added_monitors!(nodes[0], 1);
10650                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10651                 assert_eq!(events.len(), 1);
10652                 let event = events.pop().unwrap();
10653                 let path = vec![&nodes[1]];
10654                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10655
10656                 // Next, attempt a regular payment and make sure it fails.
10657                 let payment_secret = PaymentSecret([43; 32]);
10658                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10659                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10660                 check_added_monitors!(nodes[0], 1);
10661                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10662                 assert_eq!(events.len(), 1);
10663                 let ev = events.drain(..).next().unwrap();
10664                 let payment_event = SendEvent::from_event(ev);
10665                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10666                 check_added_monitors!(nodes[1], 0);
10667                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10668                 expect_pending_htlcs_forwardable!(nodes[1]);
10669                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10670                 check_added_monitors!(nodes[1], 1);
10671                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10672                 assert!(updates.update_add_htlcs.is_empty());
10673                 assert!(updates.update_fulfill_htlcs.is_empty());
10674                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10675                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10676                 assert!(updates.update_fee.is_none());
10677                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10678                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10679                 expect_payment_failed!(nodes[0], payment_hash, true);
10680
10681                 // Finally, succeed the keysend payment.
10682                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10683
10684                 // To start (3), send a keysend payment but don't claim it.
10685                 let payment_id_1 = PaymentId([44; 32]);
10686                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10687                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
10688                 check_added_monitors!(nodes[0], 1);
10689                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10690                 assert_eq!(events.len(), 1);
10691                 let event = events.pop().unwrap();
10692                 let path = vec![&nodes[1]];
10693                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10694
10695                 // Next, attempt a keysend payment and make sure it fails.
10696                 let route_params = RouteParameters::from_payment_params_and_value(
10697                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
10698                         100_000
10699                 );
10700                 let route = find_route(
10701                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10702                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10703                 ).unwrap();
10704                 let payment_id_2 = PaymentId([45; 32]);
10705                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10706                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
10707                 check_added_monitors!(nodes[0], 1);
10708                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10709                 assert_eq!(events.len(), 1);
10710                 let ev = events.drain(..).next().unwrap();
10711                 let payment_event = SendEvent::from_event(ev);
10712                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10713                 check_added_monitors!(nodes[1], 0);
10714                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10715                 expect_pending_htlcs_forwardable!(nodes[1]);
10716                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10717                 check_added_monitors!(nodes[1], 1);
10718                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10719                 assert!(updates.update_add_htlcs.is_empty());
10720                 assert!(updates.update_fulfill_htlcs.is_empty());
10721                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10722                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10723                 assert!(updates.update_fee.is_none());
10724                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10725                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10726                 expect_payment_failed!(nodes[0], payment_hash, true);
10727
10728                 // Finally, claim the original payment.
10729                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10730         }
10731
10732         #[test]
10733         fn test_keysend_hash_mismatch() {
10734                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
10735                 // preimage doesn't match the msg's payment hash.
10736                 let chanmon_cfgs = create_chanmon_cfgs(2);
10737                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10738                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10739                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10740
10741                 let payer_pubkey = nodes[0].node.get_our_node_id();
10742                 let payee_pubkey = nodes[1].node.get_our_node_id();
10743
10744                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10745                 let route_params = RouteParameters::from_payment_params_and_value(
10746                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10747                 let network_graph = nodes[0].network_graph.clone();
10748                 let first_hops = nodes[0].node.list_usable_channels();
10749                 let scorer = test_utils::TestScorer::new();
10750                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10751                 let route = find_route(
10752                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10753                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10754                 ).unwrap();
10755
10756                 let test_preimage = PaymentPreimage([42; 32]);
10757                 let mismatch_payment_hash = PaymentHash([43; 32]);
10758                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
10759                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
10760                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
10761                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
10762                 check_added_monitors!(nodes[0], 1);
10763
10764                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10765                 assert_eq!(updates.update_add_htlcs.len(), 1);
10766                 assert!(updates.update_fulfill_htlcs.is_empty());
10767                 assert!(updates.update_fail_htlcs.is_empty());
10768                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10769                 assert!(updates.update_fee.is_none());
10770                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
10771
10772                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
10773         }
10774
10775         #[test]
10776         fn test_keysend_msg_with_secret_err() {
10777                 // Test that we error as expected if we receive a keysend payment that includes a payment
10778                 // secret when we don't support MPP keysend.
10779                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
10780                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
10781                 let chanmon_cfgs = create_chanmon_cfgs(2);
10782                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10783                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
10784                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10785
10786                 let payer_pubkey = nodes[0].node.get_our_node_id();
10787                 let payee_pubkey = nodes[1].node.get_our_node_id();
10788
10789                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10790                 let route_params = RouteParameters::from_payment_params_and_value(
10791                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10792                 let network_graph = nodes[0].network_graph.clone();
10793                 let first_hops = nodes[0].node.list_usable_channels();
10794                 let scorer = test_utils::TestScorer::new();
10795                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10796                 let route = find_route(
10797                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10798                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10799                 ).unwrap();
10800
10801                 let test_preimage = PaymentPreimage([42; 32]);
10802                 let test_secret = PaymentSecret([43; 32]);
10803                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
10804                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
10805                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
10806                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
10807                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
10808                         PaymentId(payment_hash.0), None, session_privs).unwrap();
10809                 check_added_monitors!(nodes[0], 1);
10810
10811                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10812                 assert_eq!(updates.update_add_htlcs.len(), 1);
10813                 assert!(updates.update_fulfill_htlcs.is_empty());
10814                 assert!(updates.update_fail_htlcs.is_empty());
10815                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10816                 assert!(updates.update_fee.is_none());
10817                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
10818
10819                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
10820         }
10821
10822         #[test]
10823         fn test_multi_hop_missing_secret() {
10824                 let chanmon_cfgs = create_chanmon_cfgs(4);
10825                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10826                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10827                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10828
10829                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
10830                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
10831                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
10832                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
10833
10834                 // Marshall an MPP route.
10835                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
10836                 let path = route.paths[0].clone();
10837                 route.paths.push(path);
10838                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
10839                 route.paths[0].hops[0].short_channel_id = chan_1_id;
10840                 route.paths[0].hops[1].short_channel_id = chan_3_id;
10841                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
10842                 route.paths[1].hops[0].short_channel_id = chan_2_id;
10843                 route.paths[1].hops[1].short_channel_id = chan_4_id;
10844
10845                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
10846                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
10847                 .unwrap_err() {
10848                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
10849                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
10850                         },
10851                         _ => panic!("unexpected error")
10852                 }
10853         }
10854
10855         #[test]
10856         fn test_drop_disconnected_peers_when_removing_channels() {
10857                 let chanmon_cfgs = create_chanmon_cfgs(2);
10858                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10859                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10860                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10861
10862                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10863
10864                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10865                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10866
10867                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
10868                 check_closed_broadcast!(nodes[0], true);
10869                 check_added_monitors!(nodes[0], 1);
10870                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
10871
10872                 {
10873                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
10874                         // disconnected and the channel between has been force closed.
10875                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10876                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
10877                         assert_eq!(nodes_0_per_peer_state.len(), 1);
10878                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
10879                 }
10880
10881                 nodes[0].node.timer_tick_occurred();
10882
10883                 {
10884                         // Assert that nodes[1] has now been removed.
10885                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
10886                 }
10887         }
10888
10889         #[test]
10890         fn bad_inbound_payment_hash() {
10891                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
10892                 let chanmon_cfgs = create_chanmon_cfgs(2);
10893                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10894                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10895                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10896
10897                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
10898                 let payment_data = msgs::FinalOnionHopData {
10899                         payment_secret,
10900                         total_msat: 100_000,
10901                 };
10902
10903                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
10904                 // payment verification fails as expected.
10905                 let mut bad_payment_hash = payment_hash.clone();
10906                 bad_payment_hash.0[0] += 1;
10907                 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) {
10908                         Ok(_) => panic!("Unexpected ok"),
10909                         Err(()) => {
10910                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
10911                         }
10912                 }
10913
10914                 // Check that using the original payment hash succeeds.
10915                 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());
10916         }
10917
10918         #[test]
10919         fn test_id_to_peer_coverage() {
10920                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
10921                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
10922                 // the channel is successfully closed.
10923                 let chanmon_cfgs = create_chanmon_cfgs(2);
10924                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10925                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10926                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10927
10928                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10929                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10930                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
10931                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10932                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
10933
10934                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10935                 let channel_id = ChannelId::from_bytes(tx.txid().into_inner());
10936                 {
10937                         // Ensure that the `id_to_peer` map is empty until either party has received the
10938                         // funding transaction, and have the real `channel_id`.
10939                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
10940                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10941                 }
10942
10943                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10944                 {
10945                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
10946                         // as it has the funding transaction.
10947                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10948                         assert_eq!(nodes_0_lock.len(), 1);
10949                         assert!(nodes_0_lock.contains_key(&channel_id));
10950                 }
10951
10952                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10953
10954                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10955
10956                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
10957                 {
10958                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10959                         assert_eq!(nodes_0_lock.len(), 1);
10960                         assert!(nodes_0_lock.contains_key(&channel_id));
10961                 }
10962                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10963
10964                 {
10965                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
10966                         // as it has the funding transaction.
10967                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
10968                         assert_eq!(nodes_1_lock.len(), 1);
10969                         assert!(nodes_1_lock.contains_key(&channel_id));
10970                 }
10971                 check_added_monitors!(nodes[1], 1);
10972                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10973                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
10974                 check_added_monitors!(nodes[0], 1);
10975                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
10976                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10977                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10978                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
10979
10980                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
10981                 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()));
10982                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
10983                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
10984
10985                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
10986                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
10987                 {
10988                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
10989                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
10990                         // fee for the closing transaction has been negotiated and the parties has the other
10991                         // party's signature for the fee negotiated closing transaction.)
10992                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10993                         assert_eq!(nodes_0_lock.len(), 1);
10994                         assert!(nodes_0_lock.contains_key(&channel_id));
10995                 }
10996
10997                 {
10998                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
10999                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11000                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11001                         // kept in the `nodes[1]`'s `id_to_peer` map.
11002                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11003                         assert_eq!(nodes_1_lock.len(), 1);
11004                         assert!(nodes_1_lock.contains_key(&channel_id));
11005                 }
11006
11007                 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()));
11008                 {
11009                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11010                         // therefore has all it needs to fully close the channel (both signatures for the
11011                         // closing transaction).
11012                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
11013                         // fully closed by `nodes[0]`.
11014                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
11015
11016                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
11017                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11018                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
11019                         assert_eq!(nodes_1_lock.len(), 1);
11020                         assert!(nodes_1_lock.contains_key(&channel_id));
11021                 }
11022
11023                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11024
11025                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11026                 {
11027                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
11028                         // they both have everything required to fully close the channel.
11029                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
11030                 }
11031                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11032
11033                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11034                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11035         }
11036
11037         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11038                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11039                 check_api_error_message(expected_message, res_err)
11040         }
11041
11042         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11043                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11044                 check_api_error_message(expected_message, res_err)
11045         }
11046
11047         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11048                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11049                 check_api_error_message(expected_message, res_err)
11050         }
11051
11052         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11053                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11054                 check_api_error_message(expected_message, res_err)
11055         }
11056
11057         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11058                 match res_err {
11059                         Err(APIError::APIMisuseError { err }) => {
11060                                 assert_eq!(err, expected_err_message);
11061                         },
11062                         Err(APIError::ChannelUnavailable { err }) => {
11063                                 assert_eq!(err, expected_err_message);
11064                         },
11065                         Ok(_) => panic!("Unexpected Ok"),
11066                         Err(_) => panic!("Unexpected Error"),
11067                 }
11068         }
11069
11070         #[test]
11071         fn test_api_calls_with_unkown_counterparty_node() {
11072                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11073                 // expected if the `counterparty_node_id` is an unkown peer in the
11074                 // `ChannelManager::per_peer_state` map.
11075                 let chanmon_cfg = create_chanmon_cfgs(2);
11076                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11077                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11078                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11079
11080                 // Dummy values
11081                 let channel_id = ChannelId::from_bytes([4; 32]);
11082                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11083                 let intercept_id = InterceptId([0; 32]);
11084
11085                 // Test the API functions.
11086                 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);
11087
11088                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11089
11090                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11091
11092                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11093
11094                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11095
11096                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
11097
11098                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
11099         }
11100
11101         #[test]
11102         fn test_api_calls_with_unavailable_channel() {
11103                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
11104                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
11105                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
11106                 // the given `channel_id`.
11107                 let chanmon_cfg = create_chanmon_cfgs(2);
11108                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11109                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11110                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11111
11112                 let counterparty_node_id = nodes[1].node.get_our_node_id();
11113
11114                 // Dummy values
11115                 let channel_id = ChannelId::from_bytes([4; 32]);
11116
11117                 // Test the API functions.
11118                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
11119
11120                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11121
11122                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11123
11124                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
11125
11126                 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);
11127
11128                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
11129         }
11130
11131         #[test]
11132         fn test_connection_limiting() {
11133                 // Test that we limit un-channel'd peers and un-funded channels properly.
11134                 let chanmon_cfgs = create_chanmon_cfgs(2);
11135                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11136                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11137                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11138
11139                 // Note that create_network connects the nodes together for us
11140
11141                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11142                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11143
11144                 let mut funding_tx = None;
11145                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11146                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11147                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11148
11149                         if idx == 0 {
11150                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11151                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
11152                                 funding_tx = Some(tx.clone());
11153                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
11154                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11155
11156                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11157                                 check_added_monitors!(nodes[1], 1);
11158                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11159
11160                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11161
11162                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11163                                 check_added_monitors!(nodes[0], 1);
11164                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11165                         }
11166                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11167                 }
11168
11169                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11170                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11171                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11172                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11173                         open_channel_msg.temporary_channel_id);
11174
11175                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11176                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11177                 // limit.
11178                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11179                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11180                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11181                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11182                         peer_pks.push(random_pk);
11183                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11184                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11185                         }, true).unwrap();
11186                 }
11187                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11188                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11189                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11190                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11191                 }, true).unwrap_err();
11192
11193                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11194                 // them if we have too many un-channel'd peers.
11195                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11196                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11197                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
11198                 for ev in chan_closed_events {
11199                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
11200                 }
11201                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11202                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11203                 }, true).unwrap();
11204                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11205                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11206                 }, true).unwrap_err();
11207
11208                 // but of course if the connection is outbound its allowed...
11209                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11210                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11211                 }, false).unwrap();
11212                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11213
11214                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
11215                 // Even though we accept one more connection from new peers, we won't actually let them
11216                 // open channels.
11217                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
11218                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11219                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
11220                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
11221                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11222                 }
11223                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11224                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11225                         open_channel_msg.temporary_channel_id);
11226
11227                 // Of course, however, outbound channels are always allowed
11228                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
11229                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
11230
11231                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
11232                 // "protected" and can connect again.
11233                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
11234                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11235                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11236                 }, true).unwrap();
11237                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
11238
11239                 // Further, because the first channel was funded, we can open another channel with
11240                 // last_random_pk.
11241                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11242                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11243         }
11244
11245         #[test]
11246         fn test_outbound_chans_unlimited() {
11247                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
11248                 let chanmon_cfgs = create_chanmon_cfgs(2);
11249                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11250                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11251                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11252
11253                 // Note that create_network connects the nodes together for us
11254
11255                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11256                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11257
11258                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11259                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11260                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11261                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11262                 }
11263
11264                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
11265                 // rejected.
11266                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11267                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11268                         open_channel_msg.temporary_channel_id);
11269
11270                 // but we can still open an outbound channel.
11271                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11272                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
11273
11274                 // but even with such an outbound channel, additional inbound channels will still fail.
11275                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11276                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11277                         open_channel_msg.temporary_channel_id);
11278         }
11279
11280         #[test]
11281         fn test_0conf_limiting() {
11282                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11283                 // flag set and (sometimes) accept channels as 0conf.
11284                 let chanmon_cfgs = create_chanmon_cfgs(2);
11285                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11286                 let mut settings = test_default_channel_config();
11287                 settings.manually_accept_inbound_channels = true;
11288                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
11289                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11290
11291                 // Note that create_network connects the nodes together for us
11292
11293                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11294                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11295
11296                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
11297                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11298                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11299                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11300                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11301                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11302                         }, true).unwrap();
11303
11304                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
11305                         let events = nodes[1].node.get_and_clear_pending_events();
11306                         match events[0] {
11307                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11308                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
11309                                 }
11310                                 _ => panic!("Unexpected event"),
11311                         }
11312                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
11313                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11314                 }
11315
11316                 // If we try to accept a channel from another peer non-0conf it will fail.
11317                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11318                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11319                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11320                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11321                 }, true).unwrap();
11322                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11323                 let events = nodes[1].node.get_and_clear_pending_events();
11324                 match events[0] {
11325                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11326                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
11327                                         Err(APIError::APIMisuseError { err }) =>
11328                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
11329                                         _ => panic!(),
11330                                 }
11331                         }
11332                         _ => panic!("Unexpected event"),
11333                 }
11334                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11335                         open_channel_msg.temporary_channel_id);
11336
11337                 // ...however if we accept the same channel 0conf it should work just fine.
11338                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11339                 let events = nodes[1].node.get_and_clear_pending_events();
11340                 match events[0] {
11341                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11342                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
11343                         }
11344                         _ => panic!("Unexpected event"),
11345                 }
11346                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11347         }
11348
11349         #[test]
11350         fn reject_excessively_underpaying_htlcs() {
11351                 let chanmon_cfg = create_chanmon_cfgs(1);
11352                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11353                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11354                 let node = create_network(1, &node_cfg, &node_chanmgr);
11355                 let sender_intended_amt_msat = 100;
11356                 let extra_fee_msat = 10;
11357                 let hop_data = msgs::InboundOnionPayload::Receive {
11358                         amt_msat: 100,
11359                         outgoing_cltv_value: 42,
11360                         payment_metadata: None,
11361                         keysend_preimage: None,
11362                         payment_data: Some(msgs::FinalOnionHopData {
11363                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11364                         }),
11365                         custom_tlvs: Vec::new(),
11366                 };
11367                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
11368                 // intended amount, we fail the payment.
11369                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
11370                         node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11371                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat))
11372                 {
11373                         assert_eq!(err_code, 19);
11374                 } else { panic!(); }
11375
11376                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
11377                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
11378                         amt_msat: 100,
11379                         outgoing_cltv_value: 42,
11380                         payment_metadata: None,
11381                         keysend_preimage: None,
11382                         payment_data: Some(msgs::FinalOnionHopData {
11383                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11384                         }),
11385                         custom_tlvs: Vec::new(),
11386                 };
11387                 assert!(node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11388                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat)).is_ok());
11389         }
11390
11391         #[test]
11392         fn test_final_incorrect_cltv(){
11393                 let chanmon_cfg = create_chanmon_cfgs(1);
11394                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11395                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11396                 let node = create_network(1, &node_cfg, &node_chanmgr);
11397
11398                 let result = node[0].node.construct_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
11399                         amt_msat: 100,
11400                         outgoing_cltv_value: 22,
11401                         payment_metadata: None,
11402                         keysend_preimage: None,
11403                         payment_data: Some(msgs::FinalOnionHopData {
11404                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
11405                         }),
11406                         custom_tlvs: Vec::new(),
11407                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None);
11408
11409                 // Should not return an error as this condition:
11410                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
11411                 // is not satisfied.
11412                 assert!(result.is_ok());
11413         }
11414
11415         #[test]
11416         fn test_inbound_anchors_manual_acceptance() {
11417                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11418                 // flag set and (sometimes) accept channels as 0conf.
11419                 let mut anchors_cfg = test_default_channel_config();
11420                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11421
11422                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
11423                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
11424
11425                 let chanmon_cfgs = create_chanmon_cfgs(3);
11426                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11427                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
11428                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
11429                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11430
11431                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11432                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11433
11434                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11435                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11436                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
11437                 match &msg_events[0] {
11438                         MessageSendEvent::HandleError { node_id, action } => {
11439                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
11440                                 match action {
11441                                         ErrorAction::SendErrorMessage { msg } =>
11442                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
11443                                         _ => panic!("Unexpected error action"),
11444                                 }
11445                         }
11446                         _ => panic!("Unexpected event"),
11447                 }
11448
11449                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11450                 let events = nodes[2].node.get_and_clear_pending_events();
11451                 match events[0] {
11452                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
11453                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
11454                         _ => panic!("Unexpected event"),
11455                 }
11456                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11457         }
11458
11459         #[test]
11460         fn test_anchors_zero_fee_htlc_tx_fallback() {
11461                 // Tests that if both nodes support anchors, but the remote node does not want to accept
11462                 // anchor channels at the moment, an error it sent to the local node such that it can retry
11463                 // the channel without the anchors feature.
11464                 let chanmon_cfgs = create_chanmon_cfgs(2);
11465                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11466                 let mut anchors_config = test_default_channel_config();
11467                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11468                 anchors_config.manually_accept_inbound_channels = true;
11469                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
11470                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11471
11472                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
11473                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11474                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
11475
11476                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11477                 let events = nodes[1].node.get_and_clear_pending_events();
11478                 match events[0] {
11479                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11480                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
11481                         }
11482                         _ => panic!("Unexpected event"),
11483                 }
11484
11485                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
11486                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
11487
11488                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11489                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
11490
11491                 // Since nodes[1] should not have accepted the channel, it should
11492                 // not have generated any events.
11493                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11494         }
11495
11496         #[test]
11497         fn test_update_channel_config() {
11498                 let chanmon_cfg = create_chanmon_cfgs(2);
11499                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11500                 let mut user_config = test_default_channel_config();
11501                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11502                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11503                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
11504                 let channel = &nodes[0].node.list_channels()[0];
11505
11506                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11507                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11508                 assert_eq!(events.len(), 0);
11509
11510                 user_config.channel_config.forwarding_fee_base_msat += 10;
11511                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11512                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
11513                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11514                 assert_eq!(events.len(), 1);
11515                 match &events[0] {
11516                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11517                         _ => panic!("expected BroadcastChannelUpdate event"),
11518                 }
11519
11520                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
11521                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11522                 assert_eq!(events.len(), 0);
11523
11524                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
11525                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11526                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
11527                         ..Default::default()
11528                 }).unwrap();
11529                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11530                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11531                 assert_eq!(events.len(), 1);
11532                 match &events[0] {
11533                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11534                         _ => panic!("expected BroadcastChannelUpdate event"),
11535                 }
11536
11537                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
11538                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11539                         forwarding_fee_proportional_millionths: Some(new_fee),
11540                         ..Default::default()
11541                 }).unwrap();
11542                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11543                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
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                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
11552                 // should be applied to ensure update atomicity as specified in the API docs.
11553                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
11554                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
11555                 let new_fee = current_fee + 100;
11556                 assert!(
11557                         matches!(
11558                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
11559                                         forwarding_fee_proportional_millionths: Some(new_fee),
11560                                         ..Default::default()
11561                                 }),
11562                                 Err(APIError::ChannelUnavailable { err: _ }),
11563                         )
11564                 );
11565                 // Check that the fee hasn't changed for the channel that exists.
11566                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
11567                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11568                 assert_eq!(events.len(), 0);
11569         }
11570
11571         #[test]
11572         fn test_payment_display() {
11573                 let payment_id = PaymentId([42; 32]);
11574                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11575                 let payment_hash = PaymentHash([42; 32]);
11576                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11577                 let payment_preimage = PaymentPreimage([42; 32]);
11578                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11579         }
11580
11581         #[test]
11582         fn test_trigger_lnd_force_close() {
11583                 let chanmon_cfg = create_chanmon_cfgs(2);
11584                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11585                 let user_config = test_default_channel_config();
11586                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11587                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11588
11589                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
11590                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
11591                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11592                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11593                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
11594                 check_closed_broadcast(&nodes[0], 1, true);
11595                 check_added_monitors(&nodes[0], 1);
11596                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11597                 {
11598                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
11599                         assert_eq!(txn.len(), 1);
11600                         check_spends!(txn[0], funding_tx);
11601                 }
11602
11603                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
11604                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
11605                 // their side.
11606                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
11607                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
11608                 }, true).unwrap();
11609                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11610                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11611                 }, false).unwrap();
11612                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
11613                 let channel_reestablish = get_event_msg!(
11614                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
11615                 );
11616                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
11617
11618                 // Alice should respond with an error since the channel isn't known, but a bogus
11619                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
11620                 // close even if it was an lnd node.
11621                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
11622                 assert_eq!(msg_events.len(), 2);
11623                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
11624                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
11625                         assert_eq!(msg.next_local_commitment_number, 0);
11626                         assert_eq!(msg.next_remote_commitment_number, 0);
11627                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
11628                 } else { panic!() };
11629                 check_closed_broadcast(&nodes[1], 1, true);
11630                 check_added_monitors(&nodes[1], 1);
11631                 let expected_close_reason = ClosureReason::ProcessingError {
11632                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
11633                 };
11634                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
11635                 {
11636                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
11637                         assert_eq!(txn.len(), 1);
11638                         check_spends!(txn[0], funding_tx);
11639                 }
11640         }
11641 }
11642
11643 #[cfg(ldk_bench)]
11644 pub mod bench {
11645         use crate::chain::Listen;
11646         use crate::chain::chainmonitor::{ChainMonitor, Persist};
11647         use crate::sign::{KeysManager, InMemorySigner};
11648         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
11649         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
11650         use crate::ln::functional_test_utils::*;
11651         use crate::ln::msgs::{ChannelMessageHandler, Init};
11652         use crate::routing::gossip::NetworkGraph;
11653         use crate::routing::router::{PaymentParameters, RouteParameters};
11654         use crate::util::test_utils;
11655         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
11656
11657         use bitcoin::hashes::Hash;
11658         use bitcoin::hashes::sha256::Hash as Sha256;
11659         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
11660
11661         use crate::sync::{Arc, Mutex, RwLock};
11662
11663         use criterion::Criterion;
11664
11665         type Manager<'a, P> = ChannelManager<
11666                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
11667                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
11668                         &'a test_utils::TestLogger, &'a P>,
11669                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
11670                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
11671                 &'a test_utils::TestLogger>;
11672
11673         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
11674                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
11675         }
11676         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
11677                 type CM = Manager<'chan_mon_cfg, P>;
11678                 #[inline]
11679                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
11680                 #[inline]
11681                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
11682         }
11683
11684         pub fn bench_sends(bench: &mut Criterion) {
11685                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
11686         }
11687
11688         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
11689                 // Do a simple benchmark of sending a payment back and forth between two nodes.
11690                 // Note that this is unrealistic as each payment send will require at least two fsync
11691                 // calls per node.
11692                 let network = bitcoin::Network::Testnet;
11693                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
11694
11695                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
11696                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
11697                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
11698                 let scorer = RwLock::new(test_utils::TestScorer::new());
11699                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
11700
11701                 let mut config: UserConfig = Default::default();
11702                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
11703                 config.channel_handshake_config.minimum_depth = 1;
11704
11705                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
11706                 let seed_a = [1u8; 32];
11707                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
11708                 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 {
11709                         network,
11710                         best_block: BestBlock::from_network(network),
11711                 }, genesis_block.header.time);
11712                 let node_a_holder = ANodeHolder { node: &node_a };
11713
11714                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
11715                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
11716                 let seed_b = [2u8; 32];
11717                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
11718                 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 {
11719                         network,
11720                         best_block: BestBlock::from_network(network),
11721                 }, genesis_block.header.time);
11722                 let node_b_holder = ANodeHolder { node: &node_b };
11723
11724                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
11725                         features: node_b.init_features(), networks: None, remote_network_address: None
11726                 }, true).unwrap();
11727                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
11728                         features: node_a.init_features(), networks: None, remote_network_address: None
11729                 }, false).unwrap();
11730                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
11731                 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()));
11732                 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()));
11733
11734                 let tx;
11735                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
11736                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
11737                                 value: 8_000_000, script_pubkey: output_script,
11738                         }]};
11739                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
11740                 } else { panic!(); }
11741
11742                 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()));
11743                 let events_b = node_b.get_and_clear_pending_events();
11744                 assert_eq!(events_b.len(), 1);
11745                 match events_b[0] {
11746                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11747                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11748                         },
11749                         _ => panic!("Unexpected event"),
11750                 }
11751
11752                 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()));
11753                 let events_a = node_a.get_and_clear_pending_events();
11754                 assert_eq!(events_a.len(), 1);
11755                 match events_a[0] {
11756                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11757                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11758                         },
11759                         _ => panic!("Unexpected event"),
11760                 }
11761
11762                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
11763
11764                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
11765                 Listen::block_connected(&node_a, &block, 1);
11766                 Listen::block_connected(&node_b, &block, 1);
11767
11768                 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()));
11769                 let msg_events = node_a.get_and_clear_pending_msg_events();
11770                 assert_eq!(msg_events.len(), 2);
11771                 match msg_events[0] {
11772                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
11773                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
11774                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
11775                         },
11776                         _ => panic!(),
11777                 }
11778                 match msg_events[1] {
11779                         MessageSendEvent::SendChannelUpdate { .. } => {},
11780                         _ => panic!(),
11781                 }
11782
11783                 let events_a = node_a.get_and_clear_pending_events();
11784                 assert_eq!(events_a.len(), 1);
11785                 match events_a[0] {
11786                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11787                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11788                         },
11789                         _ => panic!("Unexpected event"),
11790                 }
11791
11792                 let events_b = node_b.get_and_clear_pending_events();
11793                 assert_eq!(events_b.len(), 1);
11794                 match events_b[0] {
11795                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11796                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11797                         },
11798                         _ => panic!("Unexpected event"),
11799                 }
11800
11801                 let mut payment_count: u64 = 0;
11802                 macro_rules! send_payment {
11803                         ($node_a: expr, $node_b: expr) => {
11804                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
11805                                         .with_bolt11_features($node_b.invoice_features()).unwrap();
11806                                 let mut payment_preimage = PaymentPreimage([0; 32]);
11807                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
11808                                 payment_count += 1;
11809                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
11810                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
11811
11812                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
11813                                         PaymentId(payment_hash.0),
11814                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
11815                                         Retry::Attempts(0)).unwrap();
11816                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
11817                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
11818                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
11819                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
11820                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
11821                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
11822                                 $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()));
11823
11824                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
11825                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
11826                                 $node_b.claim_funds(payment_preimage);
11827                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
11828
11829                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
11830                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
11831                                                 assert_eq!(node_id, $node_a.get_our_node_id());
11832                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
11833                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
11834                                         },
11835                                         _ => panic!("Failed to generate claim event"),
11836                                 }
11837
11838                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
11839                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
11840                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
11841                                 $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()));
11842
11843                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
11844                         }
11845                 }
11846
11847                 bench.bench_function(bench_name, |b| b.iter(|| {
11848                         send_payment!(node_a, node_b);
11849                         send_payment!(node_b, node_a);
11850                 }));
11851         }
11852 }