Clean up typos and unused variables/imports
[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 enum BackgroundEvent {
572         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
573         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
574         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
575         /// channel has been force-closed we do not need the counterparty node_id.
576         ///
577         /// Note that any such events are lost on shutdown, so in general they must be updates which
578         /// are regenerated on startup.
579         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
580         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
581         /// channel to continue normal operation.
582         ///
583         /// In general this should be used rather than
584         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
585         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
586         /// error the other variant is acceptable.
587         ///
588         /// Note that any such events are lost on shutdown, so in general they must be updates which
589         /// are regenerated on startup.
590         MonitorUpdateRegeneratedOnStartup {
591                 counterparty_node_id: PublicKey,
592                 funding_txo: OutPoint,
593                 update: ChannelMonitorUpdate
594         },
595         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
596         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
597         /// on a channel.
598         MonitorUpdatesComplete {
599                 counterparty_node_id: PublicKey,
600                 channel_id: ChannelId,
601         },
602 }
603
604 #[derive(Debug)]
605 pub(crate) enum MonitorUpdateCompletionAction {
606         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
607         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
608         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
609         /// event can be generated.
610         PaymentClaimed { payment_hash: PaymentHash },
611         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
612         /// operation of another channel.
613         ///
614         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
615         /// from completing a monitor update which removes the payment preimage until the inbound edge
616         /// completes a monitor update containing the payment preimage. In that case, after the inbound
617         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
618         /// outbound edge.
619         EmitEventAndFreeOtherChannel {
620                 event: events::Event,
621                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
622         },
623 }
624
625 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
626         (0, PaymentClaimed) => { (0, payment_hash, required) },
627         (2, EmitEventAndFreeOtherChannel) => {
628                 (0, event, upgradable_required),
629                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
630                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
631                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
632                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
633                 // downgrades to prior versions.
634                 (1, downstream_counterparty_and_funding_outpoint, option),
635         },
636 );
637
638 #[derive(Clone, Debug, PartialEq, Eq)]
639 pub(crate) enum EventCompletionAction {
640         ReleaseRAAChannelMonitorUpdate {
641                 counterparty_node_id: PublicKey,
642                 channel_funding_outpoint: OutPoint,
643         },
644 }
645 impl_writeable_tlv_based_enum!(EventCompletionAction,
646         (0, ReleaseRAAChannelMonitorUpdate) => {
647                 (0, channel_funding_outpoint, required),
648                 (2, counterparty_node_id, required),
649         };
650 );
651
652 #[derive(Clone, PartialEq, Eq, Debug)]
653 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
654 /// the blocked action here. See enum variants for more info.
655 pub(crate) enum RAAMonitorUpdateBlockingAction {
656         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
657         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
658         /// durably to disk.
659         ForwardedPaymentInboundClaim {
660                 /// The upstream channel ID (i.e. the inbound edge).
661                 channel_id: ChannelId,
662                 /// The HTLC ID on the inbound edge.
663                 htlc_id: u64,
664         },
665 }
666
667 impl RAAMonitorUpdateBlockingAction {
668         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
669                 Self::ForwardedPaymentInboundClaim {
670                         channel_id: prev_hop.outpoint.to_channel_id(),
671                         htlc_id: prev_hop.htlc_id,
672                 }
673         }
674 }
675
676 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
677         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
678 ;);
679
680
681 /// State we hold per-peer.
682 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
683         /// `channel_id` -> `ChannelPhase`
684         ///
685         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
686         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
687         /// `temporary_channel_id` -> `InboundChannelRequest`.
688         ///
689         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
690         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
691         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
692         /// the channel is rejected, then the entry is simply removed.
693         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
694         /// The latest `InitFeatures` we heard from the peer.
695         latest_features: InitFeatures,
696         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
697         /// for broadcast messages, where ordering isn't as strict).
698         pub(super) pending_msg_events: Vec<MessageSendEvent>,
699         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
700         /// user but which have not yet completed.
701         ///
702         /// Note that the channel may no longer exist. For example if the channel was closed but we
703         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
704         /// for a missing channel.
705         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
706         /// Map from a specific channel to some action(s) that should be taken when all pending
707         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
708         ///
709         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
710         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
711         /// channels with a peer this will just be one allocation and will amount to a linear list of
712         /// channels to walk, avoiding the whole hashing rigmarole.
713         ///
714         /// Note that the channel may no longer exist. For example, if a channel was closed but we
715         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
716         /// for a missing channel. While a malicious peer could construct a second channel with the
717         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
718         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
719         /// duplicates do not occur, so such channels should fail without a monitor update completing.
720         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
721         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
722         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
723         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
724         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
725         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
726         /// The peer is currently connected (i.e. we've seen a
727         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
728         /// [`ChannelMessageHandler::peer_disconnected`].
729         is_connected: bool,
730 }
731
732 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
733         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
734         /// If true is passed for `require_disconnected`, the function will return false if we haven't
735         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
736         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
737                 if require_disconnected && self.is_connected {
738                         return false
739                 }
740                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
741                         && self.monitor_update_blocked_actions.is_empty()
742                         && self.in_flight_monitor_updates.is_empty()
743         }
744
745         // Returns a count of all channels we have with this peer, including unfunded channels.
746         fn total_channel_count(&self) -> usize {
747                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
748         }
749
750         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
751         fn has_channel(&self, channel_id: &ChannelId) -> bool {
752                 self.channel_by_id.contains_key(channel_id) ||
753                         self.inbound_channel_request_by_id.contains_key(channel_id)
754         }
755 }
756
757 /// A not-yet-accepted inbound (from counterparty) channel. Once
758 /// accepted, the parameters will be used to construct a channel.
759 pub(super) struct InboundChannelRequest {
760         /// The original OpenChannel message.
761         pub open_channel_msg: msgs::OpenChannel,
762         /// The number of ticks remaining before the request expires.
763         pub ticks_remaining: i32,
764 }
765
766 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
767 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
768 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
769
770 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
771 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
772 ///
773 /// For users who don't want to bother doing their own payment preimage storage, we also store that
774 /// here.
775 ///
776 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
777 /// and instead encoding it in the payment secret.
778 struct PendingInboundPayment {
779         /// The payment secret that the sender must use for us to accept this payment
780         payment_secret: PaymentSecret,
781         /// Time at which this HTLC expires - blocks with a header time above this value will result in
782         /// this payment being removed.
783         expiry_time: u64,
784         /// Arbitrary identifier the user specifies (or not)
785         user_payment_id: u64,
786         // Other required attributes of the payment, optionally enforced:
787         payment_preimage: Option<PaymentPreimage>,
788         min_value_msat: Option<u64>,
789 }
790
791 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
792 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
793 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
794 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
795 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
796 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
797 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
798 /// of [`KeysManager`] and [`DefaultRouter`].
799 ///
800 /// This is not exported to bindings users as Arcs don't make sense in bindings
801 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
802         Arc<M>,
803         Arc<T>,
804         Arc<KeysManager>,
805         Arc<KeysManager>,
806         Arc<KeysManager>,
807         Arc<F>,
808         Arc<DefaultRouter<
809                 Arc<NetworkGraph<Arc<L>>>,
810                 Arc<L>,
811                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
812                 ProbabilisticScoringFeeParameters,
813                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
814         >>,
815         Arc<L>
816 >;
817
818 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
819 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
820 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
821 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
822 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
823 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
824 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
825 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
826 /// of [`KeysManager`] and [`DefaultRouter`].
827 ///
828 /// This is not exported to bindings users as Arcs don't make sense in bindings
829 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
830         ChannelManager<
831                 &'a M,
832                 &'b T,
833                 &'c KeysManager,
834                 &'c KeysManager,
835                 &'c KeysManager,
836                 &'d F,
837                 &'e DefaultRouter<
838                         &'f NetworkGraph<&'g L>,
839                         &'g L,
840                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
841                         ProbabilisticScoringFeeParameters,
842                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
843                 >,
844                 &'g L
845         >;
846
847 /// A trivial trait which describes any [`ChannelManager`].
848 ///
849 /// This is not exported to bindings users as general cover traits aren't useful in other
850 /// languages.
851 pub trait AChannelManager {
852         /// A type implementing [`chain::Watch`].
853         type Watch: chain::Watch<Self::Signer> + ?Sized;
854         /// A type that may be dereferenced to [`Self::Watch`].
855         type M: Deref<Target = Self::Watch>;
856         /// A type implementing [`BroadcasterInterface`].
857         type Broadcaster: BroadcasterInterface + ?Sized;
858         /// A type that may be dereferenced to [`Self::Broadcaster`].
859         type T: Deref<Target = Self::Broadcaster>;
860         /// A type implementing [`EntropySource`].
861         type EntropySource: EntropySource + ?Sized;
862         /// A type that may be dereferenced to [`Self::EntropySource`].
863         type ES: Deref<Target = Self::EntropySource>;
864         /// A type implementing [`NodeSigner`].
865         type NodeSigner: NodeSigner + ?Sized;
866         /// A type that may be dereferenced to [`Self::NodeSigner`].
867         type NS: Deref<Target = Self::NodeSigner>;
868         /// A type implementing [`WriteableEcdsaChannelSigner`].
869         type Signer: WriteableEcdsaChannelSigner + Sized;
870         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
871         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
872         /// A type that may be dereferenced to [`Self::SignerProvider`].
873         type SP: Deref<Target = Self::SignerProvider>;
874         /// A type implementing [`FeeEstimator`].
875         type FeeEstimator: FeeEstimator + ?Sized;
876         /// A type that may be dereferenced to [`Self::FeeEstimator`].
877         type F: Deref<Target = Self::FeeEstimator>;
878         /// A type implementing [`Router`].
879         type Router: Router + ?Sized;
880         /// A type that may be dereferenced to [`Self::Router`].
881         type R: Deref<Target = Self::Router>;
882         /// A type implementing [`Logger`].
883         type Logger: Logger + ?Sized;
884         /// A type that may be dereferenced to [`Self::Logger`].
885         type L: Deref<Target = Self::Logger>;
886         /// Returns a reference to the actual [`ChannelManager`] object.
887         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
888 }
889
890 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
891 for ChannelManager<M, T, ES, NS, SP, F, R, L>
892 where
893         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
894         T::Target: BroadcasterInterface,
895         ES::Target: EntropySource,
896         NS::Target: NodeSigner,
897         SP::Target: SignerProvider,
898         F::Target: FeeEstimator,
899         R::Target: Router,
900         L::Target: Logger,
901 {
902         type Watch = M::Target;
903         type M = M;
904         type Broadcaster = T::Target;
905         type T = T;
906         type EntropySource = ES::Target;
907         type ES = ES;
908         type NodeSigner = NS::Target;
909         type NS = NS;
910         type Signer = <SP::Target as SignerProvider>::Signer;
911         type SignerProvider = SP::Target;
912         type SP = SP;
913         type FeeEstimator = F::Target;
914         type F = F;
915         type Router = R::Target;
916         type R = R;
917         type Logger = L::Target;
918         type L = L;
919         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
920 }
921
922 /// Manager which keeps track of a number of channels and sends messages to the appropriate
923 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
924 ///
925 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
926 /// to individual Channels.
927 ///
928 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
929 /// all peers during write/read (though does not modify this instance, only the instance being
930 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
931 /// called [`funding_transaction_generated`] for outbound channels) being closed.
932 ///
933 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
934 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
935 /// [`ChannelMonitorUpdate`] before returning from
936 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
937 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
938 /// `ChannelManager` operations from occurring during the serialization process). If the
939 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
940 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
941 /// will be lost (modulo on-chain transaction fees).
942 ///
943 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
944 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
945 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
946 ///
947 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
948 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
949 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
950 /// offline for a full minute. In order to track this, you must call
951 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
952 ///
953 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
954 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
955 /// not have a channel with being unable to connect to us or open new channels with us if we have
956 /// many peers with unfunded channels.
957 ///
958 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
959 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
960 /// never limited. Please ensure you limit the count of such channels yourself.
961 ///
962 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
963 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
964 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
965 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
966 /// you're using lightning-net-tokio.
967 ///
968 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
969 /// [`funding_created`]: msgs::FundingCreated
970 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
971 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
972 /// [`update_channel`]: chain::Watch::update_channel
973 /// [`ChannelUpdate`]: msgs::ChannelUpdate
974 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
975 /// [`read`]: ReadableArgs::read
976 //
977 // Lock order:
978 // The tree structure below illustrates the lock order requirements for the different locks of the
979 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
980 // and should then be taken in the order of the lowest to the highest level in the tree.
981 // Note that locks on different branches shall not be taken at the same time, as doing so will
982 // create a new lock order for those specific locks in the order they were taken.
983 //
984 // Lock order tree:
985 //
986 // `total_consistency_lock`
987 //  |
988 //  |__`forward_htlcs`
989 //  |   |
990 //  |   |__`pending_intercepted_htlcs`
991 //  |
992 //  |__`per_peer_state`
993 //  |   |
994 //  |   |__`pending_inbound_payments`
995 //  |       |
996 //  |       |__`claimable_payments`
997 //  |       |
998 //  |       |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
999 //  |           |
1000 //  |           |__`peer_state`
1001 //  |               |
1002 //  |               |__`id_to_peer`
1003 //  |               |
1004 //  |               |__`short_to_chan_info`
1005 //  |               |
1006 //  |               |__`outbound_scid_aliases`
1007 //  |               |
1008 //  |               |__`best_block`
1009 //  |               |
1010 //  |               |__`pending_events`
1011 //  |                   |
1012 //  |                   |__`pending_background_events`
1013 //
1014 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1015 where
1016         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
1017         T::Target: BroadcasterInterface,
1018         ES::Target: EntropySource,
1019         NS::Target: NodeSigner,
1020         SP::Target: SignerProvider,
1021         F::Target: FeeEstimator,
1022         R::Target: Router,
1023         L::Target: Logger,
1024 {
1025         default_configuration: UserConfig,
1026         chain_hash: ChainHash,
1027         fee_estimator: LowerBoundedFeeEstimator<F>,
1028         chain_monitor: M,
1029         tx_broadcaster: T,
1030         #[allow(unused)]
1031         router: R,
1032
1033         /// See `ChannelManager` struct-level documentation for lock order requirements.
1034         #[cfg(test)]
1035         pub(super) best_block: RwLock<BestBlock>,
1036         #[cfg(not(test))]
1037         best_block: RwLock<BestBlock>,
1038         secp_ctx: Secp256k1<secp256k1::All>,
1039
1040         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1041         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1042         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1043         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1044         ///
1045         /// See `ChannelManager` struct-level documentation for lock order requirements.
1046         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1047
1048         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1049         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1050         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1051         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1052         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1053         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1054         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1055         /// after reloading from disk while replaying blocks against ChannelMonitors.
1056         ///
1057         /// See `PendingOutboundPayment` documentation for more info.
1058         ///
1059         /// See `ChannelManager` struct-level documentation for lock order requirements.
1060         pending_outbound_payments: OutboundPayments,
1061
1062         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1063         ///
1064         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1065         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1066         /// and via the classic SCID.
1067         ///
1068         /// Note that no consistency guarantees are made about the existence of a channel with the
1069         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1070         ///
1071         /// See `ChannelManager` struct-level documentation for lock order requirements.
1072         #[cfg(test)]
1073         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1074         #[cfg(not(test))]
1075         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1076         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1077         /// until the user tells us what we should do with them.
1078         ///
1079         /// See `ChannelManager` struct-level documentation for lock order requirements.
1080         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1081
1082         /// The sets of payments which are claimable or currently being claimed. See
1083         /// [`ClaimablePayments`]' individual field docs for more info.
1084         ///
1085         /// See `ChannelManager` struct-level documentation for lock order requirements.
1086         claimable_payments: Mutex<ClaimablePayments>,
1087
1088         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1089         /// and some closed channels which reached a usable state prior to being closed. This is used
1090         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1091         /// active channel list on load.
1092         ///
1093         /// See `ChannelManager` struct-level documentation for lock order requirements.
1094         outbound_scid_aliases: Mutex<HashSet<u64>>,
1095
1096         /// `channel_id` -> `counterparty_node_id`.
1097         ///
1098         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1099         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1100         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1101         ///
1102         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1103         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1104         /// the handling of the events.
1105         ///
1106         /// Note that no consistency guarantees are made about the existence of a peer with the
1107         /// `counterparty_node_id` in our other maps.
1108         ///
1109         /// TODO:
1110         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1111         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1112         /// would break backwards compatability.
1113         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1114         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1115         /// required to access the channel with the `counterparty_node_id`.
1116         ///
1117         /// See `ChannelManager` struct-level documentation for lock order requirements.
1118         id_to_peer: Mutex<HashMap<ChannelId, PublicKey>>,
1119
1120         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1121         ///
1122         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1123         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1124         /// confirmation depth.
1125         ///
1126         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1127         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1128         /// channel with the `channel_id` in our other maps.
1129         ///
1130         /// See `ChannelManager` struct-level documentation for lock order requirements.
1131         #[cfg(test)]
1132         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1133         #[cfg(not(test))]
1134         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1135
1136         our_network_pubkey: PublicKey,
1137
1138         inbound_payment_key: inbound_payment::ExpandedKey,
1139
1140         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1141         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1142         /// we encrypt the namespace identifier using these bytes.
1143         ///
1144         /// [fake scids]: crate::util::scid_utils::fake_scid
1145         fake_scid_rand_bytes: [u8; 32],
1146
1147         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1148         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1149         /// keeping additional state.
1150         probing_cookie_secret: [u8; 32],
1151
1152         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1153         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1154         /// very far in the past, and can only ever be up to two hours in the future.
1155         highest_seen_timestamp: AtomicUsize,
1156
1157         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1158         /// basis, as well as the peer's latest features.
1159         ///
1160         /// If we are connected to a peer we always at least have an entry here, even if no channels
1161         /// are currently open with that peer.
1162         ///
1163         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1164         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1165         /// channels.
1166         ///
1167         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1168         ///
1169         /// See `ChannelManager` struct-level documentation for lock order requirements.
1170         #[cfg(not(any(test, feature = "_test_utils")))]
1171         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1172         #[cfg(any(test, feature = "_test_utils"))]
1173         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1174
1175         /// The set of events which we need to give to the user to handle. In some cases an event may
1176         /// require some further action after the user handles it (currently only blocking a monitor
1177         /// update from being handed to the user to ensure the included changes to the channel state
1178         /// are handled by the user before they're persisted durably to disk). In that case, the second
1179         /// element in the tuple is set to `Some` with further details of the action.
1180         ///
1181         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1182         /// could be in the middle of being processed without the direct mutex held.
1183         ///
1184         /// See `ChannelManager` struct-level documentation for lock order requirements.
1185         #[cfg(not(any(test, feature = "_test_utils")))]
1186         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1187         #[cfg(any(test, feature = "_test_utils"))]
1188         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1189
1190         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1191         pending_events_processor: AtomicBool,
1192
1193         /// If we are running during init (either directly during the deserialization method or in
1194         /// block connection methods which run after deserialization but before normal operation) we
1195         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1196         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1197         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1198         ///
1199         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1200         ///
1201         /// See `ChannelManager` struct-level documentation for lock order requirements.
1202         ///
1203         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1204         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1205         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1206         /// Essentially just when we're serializing ourselves out.
1207         /// Taken first everywhere where we are making changes before any other locks.
1208         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1209         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1210         /// Notifier the lock contains sends out a notification when the lock is released.
1211         total_consistency_lock: RwLock<()>,
1212         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1213         /// received and the monitor has been persisted.
1214         ///
1215         /// This information does not need to be persisted as funding nodes can forget
1216         /// unfunded channels upon disconnection.
1217         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1218
1219         background_events_processed_since_startup: AtomicBool,
1220
1221         event_persist_notifier: Notifier,
1222         needs_persist_flag: AtomicBool,
1223
1224         entropy_source: ES,
1225         node_signer: NS,
1226         signer_provider: SP,
1227
1228         logger: L,
1229 }
1230
1231 /// Chain-related parameters used to construct a new `ChannelManager`.
1232 ///
1233 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1234 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1235 /// are not needed when deserializing a previously constructed `ChannelManager`.
1236 #[derive(Clone, Copy, PartialEq)]
1237 pub struct ChainParameters {
1238         /// The network for determining the `chain_hash` in Lightning messages.
1239         pub network: Network,
1240
1241         /// The hash and height of the latest block successfully connected.
1242         ///
1243         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1244         pub best_block: BestBlock,
1245 }
1246
1247 #[derive(Copy, Clone, PartialEq)]
1248 #[must_use]
1249 enum NotifyOption {
1250         DoPersist,
1251         SkipPersistHandleEvents,
1252         SkipPersistNoEvents,
1253 }
1254
1255 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1256 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1257 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1258 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1259 /// sending the aforementioned notification (since the lock being released indicates that the
1260 /// updates are ready for persistence).
1261 ///
1262 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1263 /// notify or not based on whether relevant changes have been made, providing a closure to
1264 /// `optionally_notify` which returns a `NotifyOption`.
1265 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1266         event_persist_notifier: &'a Notifier,
1267         needs_persist_flag: &'a AtomicBool,
1268         should_persist: F,
1269         // We hold onto this result so the lock doesn't get released immediately.
1270         _read_guard: RwLockReadGuard<'a, ()>,
1271 }
1272
1273 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1274         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1275         /// events to handle.
1276         ///
1277         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1278         /// other cases where losing the changes on restart may result in a force-close or otherwise
1279         /// isn't ideal.
1280         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1281                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1282         }
1283
1284         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1285         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1286                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1287                 let force_notify = cm.get_cm().process_background_events();
1288
1289                 PersistenceNotifierGuard {
1290                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1291                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1292                         should_persist: move || {
1293                                 // Pick the "most" action between `persist_check` and the background events
1294                                 // processing and return that.
1295                                 let notify = persist_check();
1296                                 match (notify, force_notify) {
1297                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1298                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1299                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1300                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1301                                         _ => NotifyOption::SkipPersistNoEvents,
1302                                 }
1303                         },
1304                         _read_guard: read_guard,
1305                 }
1306         }
1307
1308         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1309         /// [`ChannelManager::process_background_events`] MUST be called first (or
1310         /// [`Self::optionally_notify`] used).
1311         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1312         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1313                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1314
1315                 PersistenceNotifierGuard {
1316                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1317                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1318                         should_persist: persist_check,
1319                         _read_guard: read_guard,
1320                 }
1321         }
1322 }
1323
1324 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1325         fn drop(&mut self) {
1326                 match (self.should_persist)() {
1327                         NotifyOption::DoPersist => {
1328                                 self.needs_persist_flag.store(true, Ordering::Release);
1329                                 self.event_persist_notifier.notify()
1330                         },
1331                         NotifyOption::SkipPersistHandleEvents =>
1332                                 self.event_persist_notifier.notify(),
1333                         NotifyOption::SkipPersistNoEvents => {},
1334                 }
1335         }
1336 }
1337
1338 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1339 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1340 ///
1341 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1342 ///
1343 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1344 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1345 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1346 /// the maximum required amount in lnd as of March 2021.
1347 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1348
1349 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1350 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1351 ///
1352 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1353 ///
1354 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1355 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1356 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1357 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1358 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1359 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1360 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1361 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1362 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1363 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1364 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1365 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1366 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1367
1368 /// Minimum CLTV difference between the current block height and received inbound payments.
1369 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1370 /// this value.
1371 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1372 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1373 // a payment was being routed, so we add an extra block to be safe.
1374 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1375
1376 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1377 // ie that if the next-hop peer fails the HTLC within
1378 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1379 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1380 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1381 // LATENCY_GRACE_PERIOD_BLOCKS.
1382 #[deny(const_err)]
1383 #[allow(dead_code)]
1384 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;
1385
1386 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1387 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1388 #[deny(const_err)]
1389 #[allow(dead_code)]
1390 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1391
1392 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1393 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1394
1395 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1396 /// until we mark the channel disabled and gossip the update.
1397 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1398
1399 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1400 /// we mark the channel enabled and gossip the update.
1401 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1402
1403 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1404 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1405 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1406 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1407
1408 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1409 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1410 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1411
1412 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1413 /// many peers we reject new (inbound) connections.
1414 const MAX_NO_CHANNEL_PEERS: usize = 250;
1415
1416 /// Information needed for constructing an invoice route hint for this channel.
1417 #[derive(Clone, Debug, PartialEq)]
1418 pub struct CounterpartyForwardingInfo {
1419         /// Base routing fee in millisatoshis.
1420         pub fee_base_msat: u32,
1421         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1422         pub fee_proportional_millionths: u32,
1423         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1424         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1425         /// `cltv_expiry_delta` for more details.
1426         pub cltv_expiry_delta: u16,
1427 }
1428
1429 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1430 /// to better separate parameters.
1431 #[derive(Clone, Debug, PartialEq)]
1432 pub struct ChannelCounterparty {
1433         /// The node_id of our counterparty
1434         pub node_id: PublicKey,
1435         /// The Features the channel counterparty provided upon last connection.
1436         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1437         /// many routing-relevant features are present in the init context.
1438         pub features: InitFeatures,
1439         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1440         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1441         /// claiming at least this value on chain.
1442         ///
1443         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1444         ///
1445         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1446         pub unspendable_punishment_reserve: u64,
1447         /// Information on the fees and requirements that the counterparty requires when forwarding
1448         /// payments to us through this channel.
1449         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1450         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1451         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1452         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1453         pub outbound_htlc_minimum_msat: Option<u64>,
1454         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1455         pub outbound_htlc_maximum_msat: Option<u64>,
1456 }
1457
1458 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1459 #[derive(Clone, Debug, PartialEq)]
1460 pub struct ChannelDetails {
1461         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1462         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1463         /// Note that this means this value is *not* persistent - it can change once during the
1464         /// lifetime of the channel.
1465         pub channel_id: ChannelId,
1466         /// Parameters which apply to our counterparty. See individual fields for more information.
1467         pub counterparty: ChannelCounterparty,
1468         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1469         /// our counterparty already.
1470         ///
1471         /// Note that, if this has been set, `channel_id` will be equivalent to
1472         /// `funding_txo.unwrap().to_channel_id()`.
1473         pub funding_txo: Option<OutPoint>,
1474         /// The features which this channel operates with. See individual features for more info.
1475         ///
1476         /// `None` until negotiation completes and the channel type is finalized.
1477         pub channel_type: Option<ChannelTypeFeatures>,
1478         /// The position of the funding transaction in the chain. None if the funding transaction has
1479         /// not yet been confirmed and the channel fully opened.
1480         ///
1481         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1482         /// payments instead of this. See [`get_inbound_payment_scid`].
1483         ///
1484         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1485         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1486         ///
1487         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1488         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1489         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1490         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1491         /// [`confirmations_required`]: Self::confirmations_required
1492         pub short_channel_id: Option<u64>,
1493         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1494         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1495         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1496         /// `Some(0)`).
1497         ///
1498         /// This will be `None` as long as the channel is not available for routing outbound payments.
1499         ///
1500         /// [`short_channel_id`]: Self::short_channel_id
1501         /// [`confirmations_required`]: Self::confirmations_required
1502         pub outbound_scid_alias: Option<u64>,
1503         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1504         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1505         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1506         /// when they see a payment to be routed to us.
1507         ///
1508         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1509         /// previous values for inbound payment forwarding.
1510         ///
1511         /// [`short_channel_id`]: Self::short_channel_id
1512         pub inbound_scid_alias: Option<u64>,
1513         /// The value, in satoshis, of this channel as appears in the funding output
1514         pub channel_value_satoshis: u64,
1515         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1516         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1517         /// this value on chain.
1518         ///
1519         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1520         ///
1521         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1522         ///
1523         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1524         pub unspendable_punishment_reserve: Option<u64>,
1525         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1526         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1527         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1528         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1529         /// serialized with LDK versions prior to 0.0.113.
1530         ///
1531         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1532         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1533         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1534         pub user_channel_id: u128,
1535         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1536         /// which is applied to commitment and HTLC transactions.
1537         ///
1538         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1539         pub feerate_sat_per_1000_weight: Option<u32>,
1540         /// Our total balance.  This is the amount we would get if we close the channel.
1541         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1542         /// amount is not likely to be recoverable on close.
1543         ///
1544         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1545         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1546         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1547         /// This does not consider any on-chain fees.
1548         ///
1549         /// See also [`ChannelDetails::outbound_capacity_msat`]
1550         pub balance_msat: u64,
1551         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1552         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1553         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1554         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1555         ///
1556         /// See also [`ChannelDetails::balance_msat`]
1557         ///
1558         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1559         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1560         /// should be able to spend nearly this amount.
1561         pub outbound_capacity_msat: u64,
1562         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1563         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1564         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1565         /// to use a limit as close as possible to the HTLC limit we can currently send.
1566         ///
1567         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1568         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1569         pub next_outbound_htlc_limit_msat: u64,
1570         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1571         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1572         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1573         /// route which is valid.
1574         pub next_outbound_htlc_minimum_msat: u64,
1575         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1576         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1577         /// available for inclusion in new inbound HTLCs).
1578         /// Note that there are some corner cases not fully handled here, so the actual available
1579         /// inbound capacity may be slightly higher than this.
1580         ///
1581         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1582         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1583         /// However, our counterparty should be able to spend nearly this amount.
1584         pub inbound_capacity_msat: u64,
1585         /// The number of required confirmations on the funding transaction before the funding will be
1586         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1587         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1588         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1589         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1590         ///
1591         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1592         ///
1593         /// [`is_outbound`]: ChannelDetails::is_outbound
1594         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1595         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1596         pub confirmations_required: Option<u32>,
1597         /// The current number of confirmations on the funding transaction.
1598         ///
1599         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1600         pub confirmations: Option<u32>,
1601         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1602         /// until we can claim our funds after we force-close the channel. During this time our
1603         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1604         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1605         /// time to claim our non-HTLC-encumbered funds.
1606         ///
1607         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1608         pub force_close_spend_delay: Option<u16>,
1609         /// True if the channel was initiated (and thus funded) by us.
1610         pub is_outbound: bool,
1611         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1612         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1613         /// required confirmation count has been reached (and we were connected to the peer at some
1614         /// point after the funding transaction received enough confirmations). The required
1615         /// confirmation count is provided in [`confirmations_required`].
1616         ///
1617         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1618         pub is_channel_ready: bool,
1619         /// The stage of the channel's shutdown.
1620         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1621         pub channel_shutdown_state: Option<ChannelShutdownState>,
1622         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1623         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1624         ///
1625         /// This is a strict superset of `is_channel_ready`.
1626         pub is_usable: bool,
1627         /// True if this channel is (or will be) publicly-announced.
1628         pub is_public: bool,
1629         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1630         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1631         pub inbound_htlc_minimum_msat: Option<u64>,
1632         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1633         pub inbound_htlc_maximum_msat: Option<u64>,
1634         /// Set of configurable parameters that affect channel operation.
1635         ///
1636         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1637         pub config: Option<ChannelConfig>,
1638 }
1639
1640 impl ChannelDetails {
1641         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1642         /// This should be used for providing invoice hints or in any other context where our
1643         /// counterparty will forward a payment to us.
1644         ///
1645         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1646         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1647         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1648                 self.inbound_scid_alias.or(self.short_channel_id)
1649         }
1650
1651         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1652         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1653         /// we're sending or forwarding a payment outbound over this channel.
1654         ///
1655         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1656         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1657         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1658                 self.short_channel_id.or(self.outbound_scid_alias)
1659         }
1660
1661         fn from_channel_context<SP: Deref, F: Deref>(
1662                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1663                 fee_estimator: &LowerBoundedFeeEstimator<F>
1664         ) -> Self
1665         where
1666                 SP::Target: SignerProvider,
1667                 F::Target: FeeEstimator
1668         {
1669                 let balance = context.get_available_balances(fee_estimator);
1670                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1671                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1672                 ChannelDetails {
1673                         channel_id: context.channel_id(),
1674                         counterparty: ChannelCounterparty {
1675                                 node_id: context.get_counterparty_node_id(),
1676                                 features: latest_features,
1677                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1678                                 forwarding_info: context.counterparty_forwarding_info(),
1679                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1680                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1681                                 // message (as they are always the first message from the counterparty).
1682                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1683                                 // default `0` value set by `Channel::new_outbound`.
1684                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1685                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1686                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1687                         },
1688                         funding_txo: context.get_funding_txo(),
1689                         // Note that accept_channel (or open_channel) is always the first message, so
1690                         // `have_received_message` indicates that type negotiation has completed.
1691                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1692                         short_channel_id: context.get_short_channel_id(),
1693                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1694                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1695                         channel_value_satoshis: context.get_value_satoshis(),
1696                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1697                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1698                         balance_msat: balance.balance_msat,
1699                         inbound_capacity_msat: balance.inbound_capacity_msat,
1700                         outbound_capacity_msat: balance.outbound_capacity_msat,
1701                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1702                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1703                         user_channel_id: context.get_user_id(),
1704                         confirmations_required: context.minimum_depth(),
1705                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1706                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1707                         is_outbound: context.is_outbound(),
1708                         is_channel_ready: context.is_usable(),
1709                         is_usable: context.is_live(),
1710                         is_public: context.should_announce(),
1711                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1712                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1713                         config: Some(context.config()),
1714                         channel_shutdown_state: Some(context.shutdown_state()),
1715                 }
1716         }
1717 }
1718
1719 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1720 /// Further information on the details of the channel shutdown.
1721 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1722 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1723 /// the channel will be removed shortly.
1724 /// Also note, that in normal operation, peers could disconnect at any of these states
1725 /// and require peer re-connection before making progress onto other states
1726 pub enum ChannelShutdownState {
1727         /// Channel has not sent or received a shutdown message.
1728         NotShuttingDown,
1729         /// Local node has sent a shutdown message for this channel.
1730         ShutdownInitiated,
1731         /// Shutdown message exchanges have concluded and the channels are in the midst of
1732         /// resolving all existing open HTLCs before closing can continue.
1733         ResolvingHTLCs,
1734         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1735         NegotiatingClosingFee,
1736         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1737         /// to drop the channel.
1738         ShutdownComplete,
1739 }
1740
1741 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1742 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1743 #[derive(Debug, PartialEq)]
1744 pub enum RecentPaymentDetails {
1745         /// When an invoice was requested and thus a payment has not yet been sent.
1746         AwaitingInvoice {
1747                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1748                 /// a payment and ensure idempotency in LDK.
1749                 payment_id: PaymentId,
1750         },
1751         /// When a payment is still being sent and awaiting successful delivery.
1752         Pending {
1753                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1754                 /// a payment and ensure idempotency in LDK.
1755                 payment_id: PaymentId,
1756                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1757                 /// abandoned.
1758                 payment_hash: PaymentHash,
1759                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1760                 /// not just the amount currently inflight.
1761                 total_msat: u64,
1762         },
1763         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1764         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1765         /// payment is removed from tracking.
1766         Fulfilled {
1767                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1768                 /// a payment and ensure idempotency in LDK.
1769                 payment_id: PaymentId,
1770                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1771                 /// made before LDK version 0.0.104.
1772                 payment_hash: Option<PaymentHash>,
1773         },
1774         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1775         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1776         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1777         Abandoned {
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 we have given up trying to send.
1782                 payment_hash: PaymentHash,
1783         },
1784 }
1785
1786 /// Route hints used in constructing invoices for [phantom node payents].
1787 ///
1788 /// [phantom node payments]: crate::sign::PhantomKeysManager
1789 #[derive(Clone)]
1790 pub struct PhantomRouteHints {
1791         /// The list of channels to be included in the invoice route hints.
1792         pub channels: Vec<ChannelDetails>,
1793         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1794         /// route hints.
1795         pub phantom_scid: u64,
1796         /// The pubkey of the real backing node that would ultimately receive the payment.
1797         pub real_node_pubkey: PublicKey,
1798 }
1799
1800 macro_rules! handle_error {
1801         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1802                 // In testing, ensure there are no deadlocks where the lock is already held upon
1803                 // entering the macro.
1804                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1805                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1806
1807                 match $internal {
1808                         Ok(msg) => Ok(msg),
1809                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1810                                 let mut msg_events = Vec::with_capacity(2);
1811
1812                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1813                                         $self.finish_close_channel(shutdown_res);
1814                                         if let Some(update) = update_option {
1815                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1816                                                         msg: update
1817                                                 });
1818                                         }
1819                                         if let Some((channel_id, user_channel_id)) = chan_id {
1820                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1821                                                         channel_id, user_channel_id,
1822                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1823                                                         counterparty_node_id: Some($counterparty_node_id),
1824                                                         channel_capacity_sats: channel_capacity,
1825                                                 }, None));
1826                                         }
1827                                 }
1828
1829                                 log_error!($self.logger, "{}", err.err);
1830                                 if let msgs::ErrorAction::IgnoreError = err.action {
1831                                 } else {
1832                                         msg_events.push(events::MessageSendEvent::HandleError {
1833                                                 node_id: $counterparty_node_id,
1834                                                 action: err.action.clone()
1835                                         });
1836                                 }
1837
1838                                 if !msg_events.is_empty() {
1839                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1840                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1841                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1842                                                 peer_state.pending_msg_events.append(&mut msg_events);
1843                                         }
1844                                 }
1845
1846                                 // Return error in case higher-API need one
1847                                 Err(err)
1848                         },
1849                 }
1850         } };
1851         ($self: ident, $internal: expr) => {
1852                 match $internal {
1853                         Ok(res) => Ok(res),
1854                         Err((chan, msg_handle_err)) => {
1855                                 let counterparty_node_id = chan.get_counterparty_node_id();
1856                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1857                         },
1858                 }
1859         };
1860 }
1861
1862 macro_rules! update_maps_on_chan_removal {
1863         ($self: expr, $channel_context: expr) => {{
1864                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1865                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1866                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1867                         short_to_chan_info.remove(&short_id);
1868                 } else {
1869                         // If the channel was never confirmed on-chain prior to its closure, remove the
1870                         // outbound SCID alias we used for it from the collision-prevention set. While we
1871                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1872                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1873                         // opening a million channels with us which are closed before we ever reach the funding
1874                         // stage.
1875                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1876                         debug_assert!(alias_removed);
1877                 }
1878                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1879         }}
1880 }
1881
1882 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1883 macro_rules! convert_chan_phase_err {
1884         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
1885                 match $err {
1886                         ChannelError::Warn(msg) => {
1887                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
1888                         },
1889                         ChannelError::Ignore(msg) => {
1890                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
1891                         },
1892                         ChannelError::Close(msg) => {
1893                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
1894                                 update_maps_on_chan_removal!($self, $channel.context);
1895                                 let shutdown_res = $channel.context.force_shutdown(true);
1896                                 let user_id = $channel.context.get_user_id();
1897                                 let channel_capacity_satoshis = $channel.context.get_value_satoshis();
1898
1899                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, user_id,
1900                                         shutdown_res, $channel_update, channel_capacity_satoshis))
1901                         },
1902                 }
1903         };
1904         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
1905                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
1906         };
1907         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
1908                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
1909         };
1910         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
1911                 match $channel_phase {
1912                         ChannelPhase::Funded(channel) => {
1913                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
1914                         },
1915                         ChannelPhase::UnfundedOutboundV1(channel) => {
1916                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1917                         },
1918                         ChannelPhase::UnfundedInboundV1(channel) => {
1919                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
1920                         },
1921                 }
1922         };
1923 }
1924
1925 macro_rules! break_chan_phase_entry {
1926         ($self: ident, $res: expr, $entry: expr) => {
1927                 match $res {
1928                         Ok(res) => res,
1929                         Err(e) => {
1930                                 let key = *$entry.key();
1931                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1932                                 if drop {
1933                                         $entry.remove_entry();
1934                                 }
1935                                 break Err(res);
1936                         }
1937                 }
1938         }
1939 }
1940
1941 macro_rules! try_chan_phase_entry {
1942         ($self: ident, $res: expr, $entry: expr) => {
1943                 match $res {
1944                         Ok(res) => res,
1945                         Err(e) => {
1946                                 let key = *$entry.key();
1947                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
1948                                 if drop {
1949                                         $entry.remove_entry();
1950                                 }
1951                                 return Err(res);
1952                         }
1953                 }
1954         }
1955 }
1956
1957 macro_rules! remove_channel_phase {
1958         ($self: expr, $entry: expr) => {
1959                 {
1960                         let channel = $entry.remove_entry().1;
1961                         update_maps_on_chan_removal!($self, &channel.context());
1962                         channel
1963                 }
1964         }
1965 }
1966
1967 macro_rules! send_channel_ready {
1968         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1969                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1970                         node_id: $channel.context.get_counterparty_node_id(),
1971                         msg: $channel_ready_msg,
1972                 });
1973                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1974                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
1975                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1976                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1977                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1978                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1979                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
1980                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1981                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1982                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1983                 }
1984         }}
1985 }
1986
1987 macro_rules! emit_channel_pending_event {
1988         ($locked_events: expr, $channel: expr) => {
1989                 if $channel.context.should_emit_channel_pending_event() {
1990                         $locked_events.push_back((events::Event::ChannelPending {
1991                                 channel_id: $channel.context.channel_id(),
1992                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
1993                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
1994                                 user_channel_id: $channel.context.get_user_id(),
1995                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
1996                         }, None));
1997                         $channel.context.set_channel_pending_event_emitted();
1998                 }
1999         }
2000 }
2001
2002 macro_rules! emit_channel_ready_event {
2003         ($locked_events: expr, $channel: expr) => {
2004                 if $channel.context.should_emit_channel_ready_event() {
2005                         debug_assert!($channel.context.channel_pending_event_emitted());
2006                         $locked_events.push_back((events::Event::ChannelReady {
2007                                 channel_id: $channel.context.channel_id(),
2008                                 user_channel_id: $channel.context.get_user_id(),
2009                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2010                                 channel_type: $channel.context.get_channel_type().clone(),
2011                         }, None));
2012                         $channel.context.set_channel_ready_event_emitted();
2013                 }
2014         }
2015 }
2016
2017 macro_rules! handle_monitor_update_completion {
2018         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2019                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
2020                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2021                         $self.best_block.read().unwrap().height());
2022                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2023                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2024                         // We only send a channel_update in the case where we are just now sending a
2025                         // channel_ready and the channel is in a usable state. We may re-send a
2026                         // channel_update later through the announcement_signatures process for public
2027                         // channels, but there's no reason not to just inform our counterparty of our fees
2028                         // now.
2029                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2030                                 Some(events::MessageSendEvent::SendChannelUpdate {
2031                                         node_id: counterparty_node_id,
2032                                         msg,
2033                                 })
2034                         } else { None }
2035                 } else { None };
2036
2037                 let update_actions = $peer_state.monitor_update_blocked_actions
2038                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2039
2040                 let htlc_forwards = $self.handle_channel_resumption(
2041                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2042                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2043                         updates.funding_broadcastable, updates.channel_ready,
2044                         updates.announcement_sigs);
2045                 if let Some(upd) = channel_update {
2046                         $peer_state.pending_msg_events.push(upd);
2047                 }
2048
2049                 let channel_id = $chan.context.channel_id();
2050                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2051                 core::mem::drop($peer_state_lock);
2052                 core::mem::drop($per_peer_state_lock);
2053
2054                 // If the channel belongs to a batch funding transaction, the progress of the batch
2055                 // should be updated as we have received funding_signed and persisted the monitor.
2056                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2057                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2058                         let mut batch_completed = false;
2059                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2060                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2061                                         *chan_id == channel_id &&
2062                                         *pubkey == counterparty_node_id
2063                                 ));
2064                                 if let Some(channel_state) = channel_state {
2065                                         channel_state.2 = true;
2066                                 } else {
2067                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2068                                 }
2069                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2070                         } else {
2071                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2072                         }
2073
2074                         // When all channels in a batched funding transaction have become ready, it is not necessary
2075                         // to track the progress of the batch anymore and the state of the channels can be updated.
2076                         if batch_completed {
2077                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2078                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2079                                 let mut batch_funding_tx = None;
2080                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2081                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2082                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2083                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2084                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2085                                                         chan.set_batch_ready();
2086                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2087                                                         emit_channel_pending_event!(pending_events, chan);
2088                                                 }
2089                                         }
2090                                 }
2091                                 if let Some(tx) = batch_funding_tx {
2092                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2093                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2094                                 }
2095                         }
2096                 }
2097
2098                 $self.handle_monitor_update_completion_actions(update_actions);
2099
2100                 if let Some(forwards) = htlc_forwards {
2101                         $self.forward_htlcs(&mut [forwards][..]);
2102                 }
2103                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2104                 for failure in updates.failed_htlcs.drain(..) {
2105                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2106                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2107                 }
2108         } }
2109 }
2110
2111 macro_rules! handle_new_monitor_update {
2112         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2113                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2114                 match $update_res {
2115                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2116                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2117                                 log_error!($self.logger, "{}", err_str);
2118                                 panic!("{}", err_str);
2119                         },
2120                         ChannelMonitorUpdateStatus::InProgress => {
2121                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2122                                         &$chan.context.channel_id());
2123                                 false
2124                         },
2125                         ChannelMonitorUpdateStatus::Completed => {
2126                                 $completed;
2127                                 true
2128                         },
2129                 }
2130         } };
2131         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2132                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2133                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2134         };
2135         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2136                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2137                         .or_insert_with(Vec::new);
2138                 // During startup, we push monitor updates as background events through to here in
2139                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2140                 // filter for uniqueness here.
2141                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2142                         .unwrap_or_else(|| {
2143                                 in_flight_updates.push($update);
2144                                 in_flight_updates.len() - 1
2145                         });
2146                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2147                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2148                         {
2149                                 let _ = in_flight_updates.remove(idx);
2150                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2151                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2152                                 }
2153                         })
2154         } };
2155 }
2156
2157 macro_rules! process_events_body {
2158         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2159                 let mut processed_all_events = false;
2160                 while !processed_all_events {
2161                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2162                                 return;
2163                         }
2164
2165                         let mut result;
2166
2167                         {
2168                                 // We'll acquire our total consistency lock so that we can be sure no other
2169                                 // persists happen while processing monitor events.
2170                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2171
2172                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2173                                 // ensure any startup-generated background events are handled first.
2174                                 result = $self.process_background_events();
2175
2176                                 // TODO: This behavior should be documented. It's unintuitive that we query
2177                                 // ChannelMonitors when clearing other events.
2178                                 if $self.process_pending_monitor_events() {
2179                                         result = NotifyOption::DoPersist;
2180                                 }
2181                         }
2182
2183                         let pending_events = $self.pending_events.lock().unwrap().clone();
2184                         let num_events = pending_events.len();
2185                         if !pending_events.is_empty() {
2186                                 result = NotifyOption::DoPersist;
2187                         }
2188
2189                         let mut post_event_actions = Vec::new();
2190
2191                         for (event, action_opt) in pending_events {
2192                                 $event_to_handle = event;
2193                                 $handle_event;
2194                                 if let Some(action) = action_opt {
2195                                         post_event_actions.push(action);
2196                                 }
2197                         }
2198
2199                         {
2200                                 let mut pending_events = $self.pending_events.lock().unwrap();
2201                                 pending_events.drain(..num_events);
2202                                 processed_all_events = pending_events.is_empty();
2203                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2204                                 // updated here with the `pending_events` lock acquired.
2205                                 $self.pending_events_processor.store(false, Ordering::Release);
2206                         }
2207
2208                         if !post_event_actions.is_empty() {
2209                                 $self.handle_post_event_actions(post_event_actions);
2210                                 // If we had some actions, go around again as we may have more events now
2211                                 processed_all_events = false;
2212                         }
2213
2214                         match result {
2215                                 NotifyOption::DoPersist => {
2216                                         $self.needs_persist_flag.store(true, Ordering::Release);
2217                                         $self.event_persist_notifier.notify();
2218                                 },
2219                                 NotifyOption::SkipPersistHandleEvents =>
2220                                         $self.event_persist_notifier.notify(),
2221                                 NotifyOption::SkipPersistNoEvents => {},
2222                         }
2223                 }
2224         }
2225 }
2226
2227 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>
2228 where
2229         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2230         T::Target: BroadcasterInterface,
2231         ES::Target: EntropySource,
2232         NS::Target: NodeSigner,
2233         SP::Target: SignerProvider,
2234         F::Target: FeeEstimator,
2235         R::Target: Router,
2236         L::Target: Logger,
2237 {
2238         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2239         ///
2240         /// The current time or latest block header time can be provided as the `current_timestamp`.
2241         ///
2242         /// This is the main "logic hub" for all channel-related actions, and implements
2243         /// [`ChannelMessageHandler`].
2244         ///
2245         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2246         ///
2247         /// Users need to notify the new `ChannelManager` when a new block is connected or
2248         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2249         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2250         /// more details.
2251         ///
2252         /// [`block_connected`]: chain::Listen::block_connected
2253         /// [`block_disconnected`]: chain::Listen::block_disconnected
2254         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2255         pub fn new(
2256                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2257                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2258                 current_timestamp: u32,
2259         ) -> Self {
2260                 let mut secp_ctx = Secp256k1::new();
2261                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2262                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2263                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2264                 ChannelManager {
2265                         default_configuration: config.clone(),
2266                         chain_hash: ChainHash::using_genesis_block(params.network),
2267                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2268                         chain_monitor,
2269                         tx_broadcaster,
2270                         router,
2271
2272                         best_block: RwLock::new(params.best_block),
2273
2274                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2275                         pending_inbound_payments: Mutex::new(HashMap::new()),
2276                         pending_outbound_payments: OutboundPayments::new(),
2277                         forward_htlcs: Mutex::new(HashMap::new()),
2278                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2279                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2280                         id_to_peer: Mutex::new(HashMap::new()),
2281                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2282
2283                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2284                         secp_ctx,
2285
2286                         inbound_payment_key: expanded_inbound_key,
2287                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2288
2289                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2290
2291                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2292
2293                         per_peer_state: FairRwLock::new(HashMap::new()),
2294
2295                         pending_events: Mutex::new(VecDeque::new()),
2296                         pending_events_processor: AtomicBool::new(false),
2297                         pending_background_events: Mutex::new(Vec::new()),
2298                         total_consistency_lock: RwLock::new(()),
2299                         background_events_processed_since_startup: AtomicBool::new(false),
2300                         event_persist_notifier: Notifier::new(),
2301                         needs_persist_flag: AtomicBool::new(false),
2302                         funding_batch_states: Mutex::new(BTreeMap::new()),
2303
2304                         entropy_source,
2305                         node_signer,
2306                         signer_provider,
2307
2308                         logger,
2309                 }
2310         }
2311
2312         /// Gets the current configuration applied to all new channels.
2313         pub fn get_current_default_configuration(&self) -> &UserConfig {
2314                 &self.default_configuration
2315         }
2316
2317         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2318                 let height = self.best_block.read().unwrap().height();
2319                 let mut outbound_scid_alias = 0;
2320                 let mut i = 0;
2321                 loop {
2322                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2323                                 outbound_scid_alias += 1;
2324                         } else {
2325                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2326                         }
2327                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2328                                 break;
2329                         }
2330                         i += 1;
2331                         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"); }
2332                 }
2333                 outbound_scid_alias
2334         }
2335
2336         /// Creates a new outbound channel to the given remote node and with the given value.
2337         ///
2338         /// `user_channel_id` will be provided back as in
2339         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2340         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2341         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2342         /// is simply copied to events and otherwise ignored.
2343         ///
2344         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2345         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2346         ///
2347         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2348         /// generate a shutdown scriptpubkey or destination script set by
2349         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2350         ///
2351         /// Note that we do not check if you are currently connected to the given peer. If no
2352         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2353         /// the channel eventually being silently forgotten (dropped on reload).
2354         ///
2355         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2356         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2357         /// [`ChannelDetails::channel_id`] until after
2358         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2359         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2360         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2361         ///
2362         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2363         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2364         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2365         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> {
2366                 if channel_value_satoshis < 1000 {
2367                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2368                 }
2369
2370                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2371                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2372                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2373
2374                 let per_peer_state = self.per_peer_state.read().unwrap();
2375
2376                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2377                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2378
2379                 let mut peer_state = peer_state_mutex.lock().unwrap();
2380                 let channel = {
2381                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2382                         let their_features = &peer_state.latest_features;
2383                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2384                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2385                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2386                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2387                         {
2388                                 Ok(res) => res,
2389                                 Err(e) => {
2390                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2391                                         return Err(e);
2392                                 },
2393                         }
2394                 };
2395                 let res = channel.get_open_channel(self.chain_hash);
2396
2397                 let temporary_channel_id = channel.context.channel_id();
2398                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2399                         hash_map::Entry::Occupied(_) => {
2400                                 if cfg!(fuzzing) {
2401                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2402                                 } else {
2403                                         panic!("RNG is bad???");
2404                                 }
2405                         },
2406                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2407                 }
2408
2409                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2410                         node_id: their_network_key,
2411                         msg: res,
2412                 });
2413                 Ok(temporary_channel_id)
2414         }
2415
2416         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2417                 // Allocate our best estimate of the number of channels we have in the `res`
2418                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2419                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2420                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2421                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2422                 // the same channel.
2423                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2424                 {
2425                         let best_block_height = self.best_block.read().unwrap().height();
2426                         let per_peer_state = self.per_peer_state.read().unwrap();
2427                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2428                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2429                                 let peer_state = &mut *peer_state_lock;
2430                                 res.extend(peer_state.channel_by_id.iter()
2431                                         .filter_map(|(chan_id, phase)| match phase {
2432                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2433                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2434                                                 _ => None,
2435                                         })
2436                                         .filter(f)
2437                                         .map(|(_channel_id, channel)| {
2438                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2439                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2440                                         })
2441                                 );
2442                         }
2443                 }
2444                 res
2445         }
2446
2447         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2448         /// more information.
2449         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2450                 // Allocate our best estimate of the number of channels we have in the `res`
2451                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2452                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2453                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2454                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2455                 // the same channel.
2456                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2457                 {
2458                         let best_block_height = self.best_block.read().unwrap().height();
2459                         let per_peer_state = self.per_peer_state.read().unwrap();
2460                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2461                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2462                                 let peer_state = &mut *peer_state_lock;
2463                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2464                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2465                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2466                                         res.push(details);
2467                                 }
2468                         }
2469                 }
2470                 res
2471         }
2472
2473         /// Gets the list of usable channels, in random order. Useful as an argument to
2474         /// [`Router::find_route`] to ensure non-announced channels are used.
2475         ///
2476         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2477         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2478         /// are.
2479         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2480                 // Note we use is_live here instead of usable which leads to somewhat confused
2481                 // internal/external nomenclature, but that's ok cause that's probably what the user
2482                 // really wanted anyway.
2483                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2484         }
2485
2486         /// Gets the list of channels we have with a given counterparty, in random order.
2487         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2488                 let best_block_height = self.best_block.read().unwrap().height();
2489                 let per_peer_state = self.per_peer_state.read().unwrap();
2490
2491                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2492                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2493                         let peer_state = &mut *peer_state_lock;
2494                         let features = &peer_state.latest_features;
2495                         let context_to_details = |context| {
2496                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2497                         };
2498                         return peer_state.channel_by_id
2499                                 .iter()
2500                                 .map(|(_, phase)| phase.context())
2501                                 .map(context_to_details)
2502                                 .collect();
2503                 }
2504                 vec![]
2505         }
2506
2507         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2508         /// successful path, or have unresolved HTLCs.
2509         ///
2510         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2511         /// result of a crash. If such a payment exists, is not listed here, and an
2512         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2513         ///
2514         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2515         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2516                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2517                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2518                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2519                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2520                                 },
2521                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2522                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2523                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2524                                 },
2525                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2526                                         Some(RecentPaymentDetails::Pending {
2527                                                 payment_id: *payment_id,
2528                                                 payment_hash: *payment_hash,
2529                                                 total_msat: *total_msat,
2530                                         })
2531                                 },
2532                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2533                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2534                                 },
2535                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2536                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2537                                 },
2538                                 PendingOutboundPayment::Legacy { .. } => None
2539                         })
2540                         .collect()
2541         }
2542
2543         /// Helper function that issues the channel close events
2544         fn issue_channel_close_events(&self, context: &ChannelContext<SP>, closure_reason: ClosureReason) {
2545                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2546                 match context.unbroadcasted_funding() {
2547                         Some(transaction) => {
2548                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2549                                         channel_id: context.channel_id(), transaction
2550                                 }, None));
2551                         },
2552                         None => {},
2553                 }
2554                 pending_events_lock.push_back((events::Event::ChannelClosed {
2555                         channel_id: context.channel_id(),
2556                         user_channel_id: context.get_user_id(),
2557                         reason: closure_reason,
2558                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2559                         channel_capacity_sats: Some(context.get_value_satoshis()),
2560                 }, None));
2561         }
2562
2563         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> {
2564                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2565
2566                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2567                 let mut shutdown_result = None;
2568                 loop {
2569                         let per_peer_state = self.per_peer_state.read().unwrap();
2570
2571                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2572                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2573
2574                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2575                         let peer_state = &mut *peer_state_lock;
2576
2577                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2578                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2579                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2580                                                 let funding_txo_opt = chan.context.get_funding_txo();
2581                                                 let their_features = &peer_state.latest_features;
2582                                                 let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
2583                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2584                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2585                                                 failed_htlcs = htlcs;
2586
2587                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2588                                                 // here as we don't need the monitor update to complete until we send a
2589                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2590                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2591                                                         node_id: *counterparty_node_id,
2592                                                         msg: shutdown_msg,
2593                                                 });
2594
2595                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2596                                                         "We can't both complete shutdown and generate a monitor update");
2597
2598                                                 // Update the monitor with the shutdown script if necessary.
2599                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2600                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2601                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2602                                                         break;
2603                                                 }
2604
2605                                                 if chan.is_shutdown() {
2606                                                         if let ChannelPhase::Funded(chan) = remove_channel_phase!(self, chan_phase_entry) {
2607                                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&chan) {
2608                                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2609                                                                                 msg: channel_update
2610                                                                         });
2611                                                                 }
2612                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
2613                                                                 shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
2614                                                         }
2615                                                 }
2616                                                 break;
2617                                         }
2618                                 },
2619                                 hash_map::Entry::Vacant(_) => {
2620                                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2621                                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2622                                         //
2623                                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2624                                         mem::drop(peer_state_lock);
2625                                         mem::drop(per_peer_state);
2626                                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2627                                 },
2628                         }
2629                 }
2630
2631                 for htlc_source in failed_htlcs.drain(..) {
2632                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2633                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2634                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2635                 }
2636
2637                 if let Some(shutdown_result) = shutdown_result {
2638                         self.finish_close_channel(shutdown_result);
2639                 }
2640
2641                 Ok(())
2642         }
2643
2644         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2645         /// will be accepted on the given channel, and after additional timeout/the closing of all
2646         /// pending HTLCs, the channel will be closed on chain.
2647         ///
2648         ///  * If we are the channel initiator, we will pay between our [`Background`] and
2649         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2650         ///    estimate.
2651         ///  * If our counterparty is the channel initiator, we will require a channel closing
2652         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
2653         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2654         ///    counterparty to pay as much fee as they'd like, however.
2655         ///
2656         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2657         ///
2658         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2659         /// generate a shutdown scriptpubkey or destination script set by
2660         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2661         /// channel.
2662         ///
2663         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2664         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2665         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2666         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2667         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2668                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2669         }
2670
2671         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2672         /// will be accepted on the given channel, and after additional timeout/the closing of all
2673         /// pending HTLCs, the channel will be closed on chain.
2674         ///
2675         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2676         /// the channel being closed or not:
2677         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2678         ///    transaction. The upper-bound is set by
2679         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2680         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2681         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2682         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2683         ///    will appear on a force-closure transaction, whichever is lower).
2684         ///
2685         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2686         /// Will fail if a shutdown script has already been set for this channel by
2687         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2688         /// also be compatible with our and the counterparty's features.
2689         ///
2690         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2691         ///
2692         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2693         /// generate a shutdown scriptpubkey or destination script set by
2694         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2695         /// channel.
2696         ///
2697         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2698         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2699         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2700         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2701         pub fn close_channel_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> {
2702                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2703         }
2704
2705         fn finish_close_channel(&self, shutdown_res: ShutdownResult) {
2706                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2707                 #[cfg(debug_assertions)]
2708                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2709                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2710                 }
2711
2712                 let (monitor_update_option, mut failed_htlcs, unbroadcasted_batch_funding_txid) = shutdown_res;
2713                 log_debug!(self.logger, "Finishing closure of channel with {} HTLCs to fail", failed_htlcs.len());
2714                 for htlc_source in failed_htlcs.drain(..) {
2715                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2716                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2717                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2718                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2719                 }
2720                 if let Some((_, funding_txo, monitor_update)) = monitor_update_option {
2721                         // There isn't anything we can do if we get an update failure - we're already
2722                         // force-closing. The monitor update on the required in-memory copy should broadcast
2723                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2724                         // ignore the result here.
2725                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2726                 }
2727                 let mut shutdown_results = Vec::new();
2728                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2729                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2730                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2731                         let per_peer_state = self.per_peer_state.read().unwrap();
2732                         let mut has_uncompleted_channel = None;
2733                         for (channel_id, counterparty_node_id, state) in affected_channels {
2734                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2735                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2736                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2737                                                 update_maps_on_chan_removal!(self, &chan.context());
2738                                                 self.issue_channel_close_events(&chan.context(), ClosureReason::FundingBatchClosure);
2739                                                 shutdown_results.push(chan.context_mut().force_shutdown(false));
2740                                         }
2741                                 }
2742                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2743                         }
2744                         debug_assert!(
2745                                 has_uncompleted_channel.unwrap_or(true),
2746                                 "Closing a batch where all channels have completed initial monitor update",
2747                         );
2748                 }
2749                 for shutdown_result in shutdown_results.drain(..) {
2750                         self.finish_close_channel(shutdown_result);
2751                 }
2752         }
2753
2754         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2755         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2756         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2757         -> Result<PublicKey, APIError> {
2758                 let per_peer_state = self.per_peer_state.read().unwrap();
2759                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2760                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2761                 let (update_opt, counterparty_node_id) = {
2762                         let mut peer_state = peer_state_mutex.lock().unwrap();
2763                         let closure_reason = if let Some(peer_msg) = peer_msg {
2764                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2765                         } else {
2766                                 ClosureReason::HolderForceClosed
2767                         };
2768                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2769                                 log_error!(self.logger, "Force-closing channel {}", channel_id);
2770                                 self.issue_channel_close_events(&chan_phase_entry.get().context(), closure_reason);
2771                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2772                                 mem::drop(peer_state);
2773                                 mem::drop(per_peer_state);
2774                                 match chan_phase {
2775                                         ChannelPhase::Funded(mut chan) => {
2776                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast));
2777                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2778                                         },
2779                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2780                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false));
2781                                                 // Unfunded channel has no update
2782                                                 (None, chan_phase.context().get_counterparty_node_id())
2783                                         },
2784                                 }
2785                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2786                                 log_error!(self.logger, "Force-closing channel {}", &channel_id);
2787                                 // N.B. that we don't send any channel close event here: we
2788                                 // don't have a user_channel_id, and we never sent any opening
2789                                 // events anyway.
2790                                 (None, *peer_node_id)
2791                         } else {
2792                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2793                         }
2794                 };
2795                 if let Some(update) = update_opt {
2796                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2797                         // not try to broadcast it via whatever peer we have.
2798                         let per_peer_state = self.per_peer_state.read().unwrap();
2799                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2800                                 .ok_or(per_peer_state.values().next());
2801                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
2802                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
2803                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2804                                         msg: update
2805                                 });
2806                         }
2807                 }
2808
2809                 Ok(counterparty_node_id)
2810         }
2811
2812         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2813                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2814                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2815                         Ok(counterparty_node_id) => {
2816                                 let per_peer_state = self.per_peer_state.read().unwrap();
2817                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2818                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2819                                         peer_state.pending_msg_events.push(
2820                                                 events::MessageSendEvent::HandleError {
2821                                                         node_id: counterparty_node_id,
2822                                                         action: msgs::ErrorAction::DisconnectPeer {
2823                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2824                                                         },
2825                                                 }
2826                                         );
2827                                 }
2828                                 Ok(())
2829                         },
2830                         Err(e) => Err(e)
2831                 }
2832         }
2833
2834         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2835         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2836         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2837         /// channel.
2838         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2839         -> Result<(), APIError> {
2840                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2841         }
2842
2843         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2844         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2845         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2846         ///
2847         /// You can always get the latest local transaction(s) to broadcast from
2848         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2849         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
2850         -> Result<(), APIError> {
2851                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2852         }
2853
2854         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2855         /// for each to the chain and rejecting new HTLCs on each.
2856         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2857                 for chan in self.list_channels() {
2858                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2859                 }
2860         }
2861
2862         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2863         /// local transaction(s).
2864         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2865                 for chan in self.list_channels() {
2866                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2867                 }
2868         }
2869
2870         fn construct_fwd_pending_htlc_info(
2871                 &self, msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
2872                 new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
2873                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
2874         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2875                 debug_assert!(next_packet_pubkey_opt.is_some());
2876                 let outgoing_packet = msgs::OnionPacket {
2877                         version: 0,
2878                         public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
2879                         hop_data: new_packet_bytes,
2880                         hmac: hop_hmac,
2881                 };
2882
2883                 let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
2884                         msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
2885                                 (short_channel_id, amt_to_forward, outgoing_cltv_value),
2886                         msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
2887                                 return Err(InboundOnionErr {
2888                                         msg: "Final Node OnionHopData provided for us as an intermediary node",
2889                                         err_code: 0x4000 | 22,
2890                                         err_data: Vec::new(),
2891                                 }),
2892                 };
2893
2894                 Ok(PendingHTLCInfo {
2895                         routing: PendingHTLCRouting::Forward {
2896                                 onion_packet: outgoing_packet,
2897                                 short_channel_id,
2898                         },
2899                         payment_hash: msg.payment_hash,
2900                         incoming_shared_secret: shared_secret,
2901                         incoming_amt_msat: Some(msg.amount_msat),
2902                         outgoing_amt_msat: amt_to_forward,
2903                         outgoing_cltv_value,
2904                         skimmed_fee_msat: None,
2905                 })
2906         }
2907
2908         fn construct_recv_pending_htlc_info(
2909                 &self, hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
2910                 amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
2911                 counterparty_skimmed_fee_msat: Option<u64>,
2912         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2913                 let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
2914                         msgs::InboundOnionPayload::Receive {
2915                                 payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
2916                         } =>
2917                                 (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
2918                         msgs::InboundOnionPayload::BlindedReceive {
2919                                 amt_msat, total_msat, outgoing_cltv_value, payment_secret, ..
2920                         } => {
2921                                 let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
2922                                 (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
2923                         }
2924                         msgs::InboundOnionPayload::Forward { .. } => {
2925                                 return Err(InboundOnionErr {
2926                                         err_code: 0x4000|22,
2927                                         err_data: Vec::new(),
2928                                         msg: "Got non final data with an HMAC of 0",
2929                                 })
2930                         },
2931                 };
2932                 // final_incorrect_cltv_expiry
2933                 if outgoing_cltv_value > cltv_expiry {
2934                         return Err(InboundOnionErr {
2935                                 msg: "Upstream node set CLTV to less than the CLTV set by the sender",
2936                                 err_code: 18,
2937                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2938                         })
2939                 }
2940                 // final_expiry_too_soon
2941                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2942                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2943                 //
2944                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2945                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2946                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2947                 let current_height: u32 = self.best_block.read().unwrap().height();
2948                 if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
2949                         let mut err_data = Vec::with_capacity(12);
2950                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2951                         err_data.extend_from_slice(&current_height.to_be_bytes());
2952                         return Err(InboundOnionErr {
2953                                 err_code: 0x4000 | 15, err_data,
2954                                 msg: "The final CLTV expiry is too soon to handle",
2955                         });
2956                 }
2957                 if (!allow_underpay && onion_amt_msat > amt_msat) ||
2958                         (allow_underpay && onion_amt_msat >
2959                          amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
2960                 {
2961                         return Err(InboundOnionErr {
2962                                 err_code: 19,
2963                                 err_data: amt_msat.to_be_bytes().to_vec(),
2964                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2965                         });
2966                 }
2967
2968                 let routing = if let Some(payment_preimage) = keysend_preimage {
2969                         // We need to check that the sender knows the keysend preimage before processing this
2970                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
2971                         // could discover the final destination of X, by probing the adjacent nodes on the route
2972                         // with a keysend payment of identical payment hash to X and observing the processing
2973                         // time discrepancies due to a hash collision with X.
2974                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2975                         if hashed_preimage != payment_hash {
2976                                 return Err(InboundOnionErr {
2977                                         err_code: 0x4000|22,
2978                                         err_data: Vec::new(),
2979                                         msg: "Payment preimage didn't match payment hash",
2980                                 });
2981                         }
2982                         if !self.default_configuration.accept_mpp_keysend && payment_data.is_some() {
2983                                 return Err(InboundOnionErr {
2984                                         err_code: 0x4000|22,
2985                                         err_data: Vec::new(),
2986                                         msg: "We don't support MPP keysend payments",
2987                                 });
2988                         }
2989                         PendingHTLCRouting::ReceiveKeysend {
2990                                 payment_data,
2991                                 payment_preimage,
2992                                 payment_metadata,
2993                                 incoming_cltv_expiry: outgoing_cltv_value,
2994                                 custom_tlvs,
2995                         }
2996                 } else if let Some(data) = payment_data {
2997                         PendingHTLCRouting::Receive {
2998                                 payment_data: data,
2999                                 payment_metadata,
3000                                 incoming_cltv_expiry: outgoing_cltv_value,
3001                                 phantom_shared_secret,
3002                                 custom_tlvs,
3003                         }
3004                 } else {
3005                         return Err(InboundOnionErr {
3006                                 err_code: 0x4000|0x2000|3,
3007                                 err_data: Vec::new(),
3008                                 msg: "We require payment_secrets",
3009                         });
3010                 };
3011                 Ok(PendingHTLCInfo {
3012                         routing,
3013                         payment_hash,
3014                         incoming_shared_secret: shared_secret,
3015                         incoming_amt_msat: Some(amt_msat),
3016                         outgoing_amt_msat: onion_amt_msat,
3017                         outgoing_cltv_value,
3018                         skimmed_fee_msat: counterparty_skimmed_fee_msat,
3019                 })
3020         }
3021
3022         fn decode_update_add_htlc_onion(
3023                 &self, msg: &msgs::UpdateAddHTLC
3024         ) -> Result<(onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg> {
3025                 macro_rules! return_malformed_err {
3026                         ($msg: expr, $err_code: expr) => {
3027                                 {
3028                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3029                                         return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3030                                                 channel_id: msg.channel_id,
3031                                                 htlc_id: msg.htlc_id,
3032                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
3033                                                 failure_code: $err_code,
3034                                         }));
3035                                 }
3036                         }
3037                 }
3038
3039                 if let Err(_) = msg.onion_routing_packet.public_key {
3040                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
3041                 }
3042
3043                 let shared_secret = self.node_signer.ecdh(
3044                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
3045                 ).unwrap().secret_bytes();
3046
3047                 if msg.onion_routing_packet.version != 0 {
3048                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
3049                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
3050                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
3051                         //receiving node would have to brute force to figure out which version was put in the
3052                         //packet by the node that send us the message, in the case of hashing the hop_data, the
3053                         //node knows the HMAC matched, so they already know what is there...
3054                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
3055                 }
3056                 macro_rules! return_err {
3057                         ($msg: expr, $err_code: expr, $data: expr) => {
3058                                 {
3059                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3060                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3061                                                 channel_id: msg.channel_id,
3062                                                 htlc_id: msg.htlc_id,
3063                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3064                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3065                                         }));
3066                                 }
3067                         }
3068                 }
3069
3070                 let next_hop = match onion_utils::decode_next_payment_hop(
3071                         shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
3072                         msg.payment_hash, &self.node_signer
3073                 ) {
3074                         Ok(res) => res,
3075                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3076                                 return_malformed_err!(err_msg, err_code);
3077                         },
3078                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3079                                 return_err!(err_msg, err_code, &[0; 0]);
3080                         },
3081                 };
3082                 let (outgoing_scid, outgoing_amt_msat, outgoing_cltv_value, next_packet_pk_opt) = match next_hop {
3083                         onion_utils::Hop::Forward {
3084                                 next_hop_data: msgs::InboundOnionPayload::Forward {
3085                                         short_channel_id, amt_to_forward, outgoing_cltv_value
3086                                 }, ..
3087                         } => {
3088                                 let next_packet_pk = onion_utils::next_hop_pubkey(&self.secp_ctx,
3089                                         msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
3090                                 (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(next_packet_pk))
3091                         },
3092                         // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
3093                         // inbound channel's state.
3094                         onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
3095                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
3096                                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
3097                         {
3098                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
3099                         }
3100                 };
3101
3102                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3103                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3104                 if let Some((err, mut code, chan_update)) = loop {
3105                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3106                         let forwarding_chan_info_opt = match id_option {
3107                                 None => { // unknown_next_peer
3108                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3109                                         // phantom or an intercept.
3110                                         if (self.default_configuration.accept_intercept_htlcs &&
3111                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3112                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3113                                         {
3114                                                 None
3115                                         } else {
3116                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3117                                         }
3118                                 },
3119                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3120                         };
3121                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3122                                 let per_peer_state = self.per_peer_state.read().unwrap();
3123                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3124                                 if peer_state_mutex_opt.is_none() {
3125                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3126                                 }
3127                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3128                                 let peer_state = &mut *peer_state_lock;
3129                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3130                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3131                                 ).flatten() {
3132                                         None => {
3133                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3134                                                 // have no consistency guarantees.
3135                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3136                                         },
3137                                         Some(chan) => chan
3138                                 };
3139                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3140                                         // Note that the behavior here should be identical to the above block - we
3141                                         // should NOT reveal the existence or non-existence of a private channel if
3142                                         // we don't allow forwards outbound over them.
3143                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3144                                 }
3145                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3146                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3147                                         // "refuse to forward unless the SCID alias was used", so we pretend
3148                                         // we don't have the channel here.
3149                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3150                                 }
3151                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3152
3153                                 // Note that we could technically not return an error yet here and just hope
3154                                 // that the connection is reestablished or monitor updated by the time we get
3155                                 // around to doing the actual forward, but better to fail early if we can and
3156                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3157                                 // on a small/per-node/per-channel scale.
3158                                 if !chan.context.is_live() { // channel_disabled
3159                                         // If the channel_update we're going to return is disabled (i.e. the
3160                                         // peer has been disabled for some time), return `channel_disabled`,
3161                                         // otherwise return `temporary_channel_failure`.
3162                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3163                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3164                                         } else {
3165                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3166                                         }
3167                                 }
3168                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3169                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3170                                 }
3171                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3172                                         break Some((err, code, chan_update_opt));
3173                                 }
3174                                 chan_update_opt
3175                         } else {
3176                                 if (msg.cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
3177                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3178                                         // forwarding over a real channel we can't generate a channel_update
3179                                         // for it. Instead we just return a generic temporary_node_failure.
3180                                         break Some((
3181                                                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
3182                                                         0x2000 | 2, None,
3183                                         ));
3184                                 }
3185                                 None
3186                         };
3187
3188                         let cur_height = self.best_block.read().unwrap().height() + 1;
3189                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
3190                         // but we want to be robust wrt to counterparty packet sanitization (see
3191                         // HTLC_FAIL_BACK_BUFFER rationale).
3192                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
3193                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
3194                         }
3195                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
3196                                 break Some(("CLTV expiry is too far in the future", 21, None));
3197                         }
3198                         // If the HTLC expires ~now, don't bother trying to forward it to our
3199                         // counterparty. They should fail it anyway, but we don't want to bother with
3200                         // the round-trips or risk them deciding they definitely want the HTLC and
3201                         // force-closing to ensure they get it if we're offline.
3202                         // We previously had a much more aggressive check here which tried to ensure
3203                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
3204                         // but there is no need to do that, and since we're a bit conservative with our
3205                         // risk threshold it just results in failing to forward payments.
3206                         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
3207                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
3208                         }
3209
3210                         break None;
3211                 }
3212                 {
3213                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3214                         if let Some(chan_update) = chan_update {
3215                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3216                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3217                                 }
3218                                 else if code == 0x1000 | 13 {
3219                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3220                                 }
3221                                 else if code == 0x1000 | 20 {
3222                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3223                                         0u16.write(&mut res).expect("Writes cannot fail");
3224                                 }
3225                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3226                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3227                                 chan_update.write(&mut res).expect("Writes cannot fail");
3228                         } else if code & 0x1000 == 0x1000 {
3229                                 // If we're trying to return an error that requires a `channel_update` but
3230                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3231                                 // generate an update), just use the generic "temporary_node_failure"
3232                                 // instead.
3233                                 code = 0x2000 | 2;
3234                         }
3235                         return_err!(err, code, &res.0[..]);
3236                 }
3237                 Ok((next_hop, shared_secret, next_packet_pk_opt))
3238         }
3239
3240         fn construct_pending_htlc_status<'a>(
3241                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3242                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3243         ) -> PendingHTLCStatus {
3244                 macro_rules! return_err {
3245                         ($msg: expr, $err_code: expr, $data: expr) => {
3246                                 {
3247                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3248                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3249                                                 channel_id: msg.channel_id,
3250                                                 htlc_id: msg.htlc_id,
3251                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3252                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3253                                         }));
3254                                 }
3255                         }
3256                 }
3257                 match decoded_hop {
3258                         onion_utils::Hop::Receive(next_hop_data) => {
3259                                 // OUR PAYMENT!
3260                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3261                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat)
3262                                 {
3263                                         Ok(info) => {
3264                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3265                                                 // message, however that would leak that we are the recipient of this payment, so
3266                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3267                                                 // delay) once they've send us a commitment_signed!
3268                                                 PendingHTLCStatus::Forward(info)
3269                                         },
3270                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3271                                 }
3272                         },
3273                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3274                                 match self.construct_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3275                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3276                                         Ok(info) => PendingHTLCStatus::Forward(info),
3277                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3278                                 }
3279                         }
3280                 }
3281         }
3282
3283         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3284         /// public, and thus should be called whenever the result is going to be passed out in a
3285         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3286         ///
3287         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3288         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3289         /// storage and the `peer_state` lock has been dropped.
3290         ///
3291         /// [`channel_update`]: msgs::ChannelUpdate
3292         /// [`internal_closing_signed`]: Self::internal_closing_signed
3293         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3294                 if !chan.context.should_announce() {
3295                         return Err(LightningError {
3296                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3297                                 action: msgs::ErrorAction::IgnoreError
3298                         });
3299                 }
3300                 if chan.context.get_short_channel_id().is_none() {
3301                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3302                 }
3303                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3304                 self.get_channel_update_for_unicast(chan)
3305         }
3306
3307         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3308         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3309         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3310         /// provided evidence that they know about the existence of the channel.
3311         ///
3312         /// Note that through [`internal_closing_signed`], this function is called without the
3313         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3314         /// removed from the 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_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3319                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", &chan.context.channel_id());
3320                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3321                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3322                         Some(id) => id,
3323                 };
3324
3325                 self.get_channel_update_for_onion(short_channel_id, chan)
3326         }
3327
3328         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3329                 log_trace!(self.logger, "Generating channel update for channel {}", &chan.context.channel_id());
3330                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3331
3332                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3333                         ChannelUpdateStatus::Enabled => true,
3334                         ChannelUpdateStatus::DisabledStaged(_) => true,
3335                         ChannelUpdateStatus::Disabled => false,
3336                         ChannelUpdateStatus::EnabledStaged(_) => false,
3337                 };
3338
3339                 let unsigned = msgs::UnsignedChannelUpdate {
3340                         chain_hash: self.chain_hash,
3341                         short_channel_id,
3342                         timestamp: chan.context.get_update_time_counter(),
3343                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3344                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3345                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3346                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3347                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3348                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3349                         excess_data: Vec::new(),
3350                 };
3351                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3352                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3353                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3354                 // channel.
3355                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3356
3357                 Ok(msgs::ChannelUpdate {
3358                         signature: sig,
3359                         contents: unsigned
3360                 })
3361         }
3362
3363         #[cfg(test)]
3364         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> {
3365                 let _lck = self.total_consistency_lock.read().unwrap();
3366                 self.send_payment_along_path(SendAlongPathArgs {
3367                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3368                         session_priv_bytes
3369                 })
3370         }
3371
3372         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3373                 let SendAlongPathArgs {
3374                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3375                         session_priv_bytes
3376                 } = args;
3377                 // The top-level caller should hold the total_consistency_lock read lock.
3378                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3379
3380                 log_trace!(self.logger,
3381                         "Attempting to send payment with payment hash {} along path with next hop {}",
3382                         payment_hash, path.hops.first().unwrap().short_channel_id);
3383                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3384                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3385
3386                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3387                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3388                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3389
3390                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3391                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3392
3393                 let err: Result<(), _> = loop {
3394                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3395                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3396                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3397                         };
3398
3399                         let per_peer_state = self.per_peer_state.read().unwrap();
3400                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3401                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3402                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3403                         let peer_state = &mut *peer_state_lock;
3404                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3405                                 match chan_phase_entry.get_mut() {
3406                                         ChannelPhase::Funded(chan) => {
3407                                                 if !chan.context.is_live() {
3408                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3409                                                 }
3410                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3411                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3412                                                         htlc_cltv, HTLCSource::OutboundRoute {
3413                                                                 path: path.clone(),
3414                                                                 session_priv: session_priv.clone(),
3415                                                                 first_hop_htlc_msat: htlc_msat,
3416                                                                 payment_id,
3417                                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3418                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3419                                                         Some(monitor_update) => {
3420                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3421                                                                         false => {
3422                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3423                                                                                 // docs) that we will resend the commitment update once monitor
3424                                                                                 // updating completes. Therefore, we must return an error
3425                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3426                                                                                 // which we do in the send_payment check for
3427                                                                                 // MonitorUpdateInProgress, below.
3428                                                                                 return Err(APIError::MonitorUpdateInProgress);
3429                                                                         },
3430                                                                         true => {},
3431                                                                 }
3432                                                         },
3433                                                         None => {},
3434                                                 }
3435                                         },
3436                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3437                                 };
3438                         } else {
3439                                 // The channel was likely removed after we fetched the id from the
3440                                 // `short_to_chan_info` map, but before we successfully locked the
3441                                 // `channel_by_id` map.
3442                                 // This can occur as no consistency guarantees exists between the two maps.
3443                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3444                         }
3445                         return Ok(());
3446                 };
3447
3448                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3449                         Ok(_) => unreachable!(),
3450                         Err(e) => {
3451                                 Err(APIError::ChannelUnavailable { err: e.err })
3452                         },
3453                 }
3454         }
3455
3456         /// Sends a payment along a given route.
3457         ///
3458         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3459         /// fields for more info.
3460         ///
3461         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3462         /// [`PeerManager::process_events`]).
3463         ///
3464         /// # Avoiding Duplicate Payments
3465         ///
3466         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3467         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3468         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3469         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3470         /// second payment with the same [`PaymentId`].
3471         ///
3472         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3473         /// tracking of payments, including state to indicate once a payment has completed. Because you
3474         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3475         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3476         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3477         ///
3478         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3479         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3480         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3481         /// [`ChannelManager::list_recent_payments`] for more information.
3482         ///
3483         /// # Possible Error States on [`PaymentSendFailure`]
3484         ///
3485         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3486         /// each entry matching the corresponding-index entry in the route paths, see
3487         /// [`PaymentSendFailure`] for more info.
3488         ///
3489         /// In general, a path may raise:
3490         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3491         ///    node public key) is specified.
3492         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3493         ///    closed, doesn't exist, or the peer is currently disconnected.
3494         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3495         ///    relevant updates.
3496         ///
3497         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3498         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3499         /// different route unless you intend to pay twice!
3500         ///
3501         /// [`RouteHop`]: crate::routing::router::RouteHop
3502         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3503         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3504         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3505         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3506         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3507         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3508                 let best_block_height = self.best_block.read().unwrap().height();
3509                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3510                 self.pending_outbound_payments
3511                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3512                                 &self.entropy_source, &self.node_signer, best_block_height,
3513                                 |args| self.send_payment_along_path(args))
3514         }
3515
3516         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3517         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3518         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3519                 let best_block_height = self.best_block.read().unwrap().height();
3520                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3521                 self.pending_outbound_payments
3522                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3523                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3524                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3525                                 &self.pending_events, |args| self.send_payment_along_path(args))
3526         }
3527
3528         #[cfg(test)]
3529         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> {
3530                 let best_block_height = self.best_block.read().unwrap().height();
3531                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3532                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3533                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3534                         best_block_height, |args| self.send_payment_along_path(args))
3535         }
3536
3537         #[cfg(test)]
3538         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> {
3539                 let best_block_height = self.best_block.read().unwrap().height();
3540                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3541         }
3542
3543         #[cfg(test)]
3544         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3545                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3546         }
3547
3548
3549         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3550         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3551         /// retries are exhausted.
3552         ///
3553         /// # Event Generation
3554         ///
3555         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3556         /// as there are no remaining pending HTLCs for this payment.
3557         ///
3558         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3559         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3560         /// determine the ultimate status of a payment.
3561         ///
3562         /// # Restart Behavior
3563         ///
3564         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3565         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated.
3566         pub fn abandon_payment(&self, payment_id: PaymentId) {
3567                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3568                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3569         }
3570
3571         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3572         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3573         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3574         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3575         /// never reach the recipient.
3576         ///
3577         /// See [`send_payment`] documentation for more details on the return value of this function
3578         /// and idempotency guarantees provided by the [`PaymentId`] key.
3579         ///
3580         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3581         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3582         ///
3583         /// [`send_payment`]: Self::send_payment
3584         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3585                 let best_block_height = self.best_block.read().unwrap().height();
3586                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3587                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3588                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3589                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3590         }
3591
3592         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3593         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3594         ///
3595         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3596         /// payments.
3597         ///
3598         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3599         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> {
3600                 let best_block_height = self.best_block.read().unwrap().height();
3601                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3602                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3603                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3604                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3605                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3606         }
3607
3608         /// Send a payment that is probing the given route for liquidity. We calculate the
3609         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3610         /// us to easily discern them from real payments.
3611         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3612                 let best_block_height = self.best_block.read().unwrap().height();
3613                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3614                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3615                         &self.entropy_source, &self.node_signer, best_block_height,
3616                         |args| self.send_payment_along_path(args))
3617         }
3618
3619         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3620         /// payment probe.
3621         #[cfg(test)]
3622         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3623                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3624         }
3625
3626         /// Sends payment probes over all paths of a route that would be used to pay the given
3627         /// amount to the given `node_id`.
3628         ///
3629         /// See [`ChannelManager::send_preflight_probes`] for more information.
3630         pub fn send_spontaneous_preflight_probes(
3631                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3632                 liquidity_limit_multiplier: Option<u64>,
3633         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3634                 let payment_params =
3635                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3636
3637                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3638
3639                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3640         }
3641
3642         /// Sends payment probes over all paths of a route that would be used to pay a route found
3643         /// according to the given [`RouteParameters`].
3644         ///
3645         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3646         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3647         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3648         /// confirmation in a wallet UI.
3649         ///
3650         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3651         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3652         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3653         /// payment. To mitigate this issue, channels with available liquidity less than the required
3654         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3655         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3656         pub fn send_preflight_probes(
3657                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3658         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3659                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3660
3661                 let payer = self.get_our_node_id();
3662                 let usable_channels = self.list_usable_channels();
3663                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3664                 let inflight_htlcs = self.compute_inflight_htlcs();
3665
3666                 let route = self
3667                         .router
3668                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3669                         .map_err(|e| {
3670                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3671                                 ProbeSendFailure::RouteNotFound
3672                         })?;
3673
3674                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3675
3676                 let mut res = Vec::new();
3677
3678                 for mut path in route.paths {
3679                         // If the last hop is probably an unannounced channel we refrain from probing all the
3680                         // way through to the end and instead probe up to the second-to-last channel.
3681                         while let Some(last_path_hop) = path.hops.last() {
3682                                 if last_path_hop.maybe_announced_channel {
3683                                         // We found a potentially announced last hop.
3684                                         break;
3685                                 } else {
3686                                         // Drop the last hop, as it's likely unannounced.
3687                                         log_debug!(
3688                                                 self.logger,
3689                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3690                                                 last_path_hop.short_channel_id
3691                                         );
3692                                         let final_value_msat = path.final_value_msat();
3693                                         path.hops.pop();
3694                                         if let Some(new_last) = path.hops.last_mut() {
3695                                                 new_last.fee_msat += final_value_msat;
3696                                         }
3697                                 }
3698                         }
3699
3700                         if path.hops.len() < 2 {
3701                                 log_debug!(
3702                                         self.logger,
3703                                         "Skipped sending payment probe over path with less than two hops."
3704                                 );
3705                                 continue;
3706                         }
3707
3708                         if let Some(first_path_hop) = path.hops.first() {
3709                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3710                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3711                                 }) {
3712                                         let path_value = path.final_value_msat() + path.fee_msat();
3713                                         let used_liquidity =
3714                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3715
3716                                         if first_hop.next_outbound_htlc_limit_msat
3717                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3718                                         {
3719                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3720                                                 continue;
3721                                         } else {
3722                                                 *used_liquidity += path_value;
3723                                         }
3724                                 }
3725                         }
3726
3727                         res.push(self.send_probe(path).map_err(|e| {
3728                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3729                                 ProbeSendFailure::SendingFailed(e)
3730                         })?);
3731                 }
3732
3733                 Ok(res)
3734         }
3735
3736         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3737         /// which checks the correctness of the funding transaction given the associated channel.
3738         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3739                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3740                 mut find_funding_output: FundingOutput,
3741         ) -> Result<(), APIError> {
3742                 let per_peer_state = self.per_peer_state.read().unwrap();
3743                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3744                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3745
3746                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3747                 let peer_state = &mut *peer_state_lock;
3748                 let (chan, msg) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3749                         Some(ChannelPhase::UnfundedOutboundV1(chan)) => {
3750                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3751
3752                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &self.logger)
3753                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3754                                                 let channel_id = chan.context.channel_id();
3755                                                 let user_id = chan.context.get_user_id();
3756                                                 let shutdown_res = chan.context.force_shutdown(false);
3757                                                 let channel_capacity = chan.context.get_value_satoshis();
3758                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3759                                         } else { unreachable!(); });
3760                                 match funding_res {
3761                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3762                                         Err((chan, err)) => {
3763                                                 mem::drop(peer_state_lock);
3764                                                 mem::drop(per_peer_state);
3765
3766                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3767                                                 return Err(APIError::ChannelUnavailable {
3768                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3769                                                 });
3770                                         },
3771                                 }
3772                         },
3773                         Some(phase) => {
3774                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3775                                 return Err(APIError::APIMisuseError {
3776                                         err: format!(
3777                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3778                                                 temporary_channel_id, counterparty_node_id),
3779                                 })
3780                         },
3781                         None => return Err(APIError::ChannelUnavailable {err: format!(
3782                                 "Channel with id {} not found for the passed counterparty node_id {}",
3783                                 temporary_channel_id, counterparty_node_id),
3784                                 }),
3785                 };
3786
3787                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3788                         node_id: chan.context.get_counterparty_node_id(),
3789                         msg,
3790                 });
3791                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3792                         hash_map::Entry::Occupied(_) => {
3793                                 panic!("Generated duplicate funding txid?");
3794                         },
3795                         hash_map::Entry::Vacant(e) => {
3796                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3797                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3798                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3799                                 }
3800                                 e.insert(ChannelPhase::Funded(chan));
3801                         }
3802                 }
3803                 Ok(())
3804         }
3805
3806         #[cfg(test)]
3807         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3808                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3809                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3810                 })
3811         }
3812
3813         /// Call this upon creation of a funding transaction for the given channel.
3814         ///
3815         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3816         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3817         ///
3818         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3819         /// across the p2p network.
3820         ///
3821         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3822         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3823         ///
3824         /// May panic if the output found in the funding transaction is duplicative with some other
3825         /// channel (note that this should be trivially prevented by using unique funding transaction
3826         /// keys per-channel).
3827         ///
3828         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3829         /// counterparty's signature the funding transaction will automatically be broadcast via the
3830         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3831         ///
3832         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3833         /// not currently support replacing a funding transaction on an existing channel. Instead,
3834         /// create a new channel with a conflicting funding transaction.
3835         ///
3836         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3837         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3838         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3839         /// for more details.
3840         ///
3841         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3842         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3843         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3844                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3845         }
3846
3847         /// Call this upon creation of a batch funding transaction for the given channels.
3848         ///
3849         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3850         /// each individual channel and transaction output.
3851         ///
3852         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3853         /// will only be broadcast when we have safely received and persisted the counterparty's
3854         /// signature for each channel.
3855         ///
3856         /// If there is an error, all channels in the batch are to be considered closed.
3857         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3858                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3859                 let mut result = Ok(());
3860
3861                 if !funding_transaction.is_coin_base() {
3862                         for inp in funding_transaction.input.iter() {
3863                                 if inp.witness.is_empty() {
3864                                         result = result.and(Err(APIError::APIMisuseError {
3865                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3866                                         }));
3867                                 }
3868                         }
3869                 }
3870                 if funding_transaction.output.len() > u16::max_value() as usize {
3871                         result = result.and(Err(APIError::APIMisuseError {
3872                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3873                         }));
3874                 }
3875                 {
3876                         let height = self.best_block.read().unwrap().height();
3877                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3878                         // lower than the next block height. However, the modules constituting our Lightning
3879                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3880                         // module is ahead of LDK, only allow one more block of headroom.
3881                         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 {
3882                                 result = result.and(Err(APIError::APIMisuseError {
3883                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3884                                 }));
3885                         }
3886                 }
3887
3888                 let txid = funding_transaction.txid();
3889                 let is_batch_funding = temporary_channels.len() > 1;
3890                 let mut funding_batch_states = if is_batch_funding {
3891                         Some(self.funding_batch_states.lock().unwrap())
3892                 } else {
3893                         None
3894                 };
3895                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3896                         match states.entry(txid) {
3897                                 btree_map::Entry::Occupied(_) => {
3898                                         result = result.clone().and(Err(APIError::APIMisuseError {
3899                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3900                                         }));
3901                                         None
3902                                 },
3903                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3904                         }
3905                 });
3906                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3907                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3908                                 temporary_channel_id,
3909                                 counterparty_node_id,
3910                                 funding_transaction.clone(),
3911                                 is_batch_funding,
3912                                 |chan, tx| {
3913                                         let mut output_index = None;
3914                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3915                                         for (idx, outp) in tx.output.iter().enumerate() {
3916                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3917                                                         if output_index.is_some() {
3918                                                                 return Err(APIError::APIMisuseError {
3919                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3920                                                                 });
3921                                                         }
3922                                                         output_index = Some(idx as u16);
3923                                                 }
3924                                         }
3925                                         if output_index.is_none() {
3926                                                 return Err(APIError::APIMisuseError {
3927                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3928                                                 });
3929                                         }
3930                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3931                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3932                                                 funding_batch_state.push((outpoint.to_channel_id(), *counterparty_node_id, false));
3933                                         }
3934                                         Ok(outpoint)
3935                                 })
3936                         );
3937                 }
3938                 if let Err(ref e) = result {
3939                         // Remaining channels need to be removed on any error.
3940                         let e = format!("Error in transaction funding: {:?}", e);
3941                         let mut channels_to_remove = Vec::new();
3942                         channels_to_remove.extend(funding_batch_states.as_mut()
3943                                 .and_then(|states| states.remove(&txid))
3944                                 .into_iter().flatten()
3945                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3946                         );
3947                         channels_to_remove.extend(temporary_channels.iter()
3948                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3949                         );
3950                         let mut shutdown_results = Vec::new();
3951                         {
3952                                 let per_peer_state = self.per_peer_state.read().unwrap();
3953                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3954                                         per_peer_state.get(&counterparty_node_id)
3955                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3956                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3957                                                 .map(|mut chan| {
3958                                                         update_maps_on_chan_removal!(self, &chan.context());
3959                                                         self.issue_channel_close_events(&chan.context(), ClosureReason::ProcessingError { err: e.clone() });
3960                                                         shutdown_results.push(chan.context_mut().force_shutdown(false));
3961                                                 });
3962                                 }
3963                         }
3964                         for shutdown_result in shutdown_results.drain(..) {
3965                                 self.finish_close_channel(shutdown_result);
3966                         }
3967                 }
3968                 result
3969         }
3970
3971         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3972         ///
3973         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3974         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3975         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3976         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3977         ///
3978         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3979         /// `counterparty_node_id` is provided.
3980         ///
3981         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3982         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3983         ///
3984         /// If an error is returned, none of the updates should be considered applied.
3985         ///
3986         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3987         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3988         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3989         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3990         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3991         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3992         /// [`APIMisuseError`]: APIError::APIMisuseError
3993         pub fn update_partial_channel_config(
3994                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
3995         ) -> Result<(), APIError> {
3996                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
3997                         return Err(APIError::APIMisuseError {
3998                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
3999                         });
4000                 }
4001
4002                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4003                 let per_peer_state = self.per_peer_state.read().unwrap();
4004                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4005                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4006                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4007                 let peer_state = &mut *peer_state_lock;
4008                 for channel_id in channel_ids {
4009                         if !peer_state.has_channel(channel_id) {
4010                                 return Err(APIError::ChannelUnavailable {
4011                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4012                                 });
4013                         };
4014                 }
4015                 for channel_id in channel_ids {
4016                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4017                                 let mut config = channel_phase.context().config();
4018                                 config.apply(config_update);
4019                                 if !channel_phase.context_mut().update_config(&config) {
4020                                         continue;
4021                                 }
4022                                 if let ChannelPhase::Funded(channel) = channel_phase {
4023                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4024                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4025                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4026                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4027                                                         node_id: channel.context.get_counterparty_node_id(),
4028                                                         msg,
4029                                                 });
4030                                         }
4031                                 }
4032                                 continue;
4033                         } else {
4034                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4035                                 debug_assert!(false);
4036                                 return Err(APIError::ChannelUnavailable {
4037                                         err: format!(
4038                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4039                                                 channel_id, counterparty_node_id),
4040                                 });
4041                         };
4042                 }
4043                 Ok(())
4044         }
4045
4046         /// Atomically updates the [`ChannelConfig`] for the given channels.
4047         ///
4048         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4049         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4050         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4051         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4052         ///
4053         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4054         /// `counterparty_node_id` is provided.
4055         ///
4056         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4057         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4058         ///
4059         /// If an error is returned, none of the updates should be considered applied.
4060         ///
4061         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4062         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4063         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4064         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4065         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4066         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4067         /// [`APIMisuseError`]: APIError::APIMisuseError
4068         pub fn update_channel_config(
4069                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4070         ) -> Result<(), APIError> {
4071                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4072         }
4073
4074         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4075         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4076         ///
4077         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4078         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4079         ///
4080         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4081         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4082         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4083         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4084         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4085         ///
4086         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4087         /// you from forwarding more than you received. See
4088         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4089         /// than expected.
4090         ///
4091         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4092         /// backwards.
4093         ///
4094         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4095         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4096         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4097         // TODO: when we move to deciding the best outbound channel at forward time, only take
4098         // `next_node_id` and not `next_hop_channel_id`
4099         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> {
4100                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4101
4102                 let next_hop_scid = {
4103                         let peer_state_lock = self.per_peer_state.read().unwrap();
4104                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4105                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4106                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4107                         let peer_state = &mut *peer_state_lock;
4108                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4109                                 Some(ChannelPhase::Funded(chan)) => {
4110                                         if !chan.context.is_usable() {
4111                                                 return Err(APIError::ChannelUnavailable {
4112                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4113                                                 })
4114                                         }
4115                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4116                                 },
4117                                 Some(_) => return Err(APIError::ChannelUnavailable {
4118                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4119                                                 next_hop_channel_id, next_node_id)
4120                                 }),
4121                                 None => return Err(APIError::ChannelUnavailable {
4122                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}",
4123                                                 next_hop_channel_id, next_node_id)
4124                                 })
4125                         }
4126                 };
4127
4128                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4129                         .ok_or_else(|| APIError::APIMisuseError {
4130                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4131                         })?;
4132
4133                 let routing = match payment.forward_info.routing {
4134                         PendingHTLCRouting::Forward { onion_packet, .. } => {
4135                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
4136                         },
4137                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4138                 };
4139                 let skimmed_fee_msat =
4140                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4141                 let pending_htlc_info = PendingHTLCInfo {
4142                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4143                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4144                 };
4145
4146                 let mut per_source_pending_forward = [(
4147                         payment.prev_short_channel_id,
4148                         payment.prev_funding_outpoint,
4149                         payment.prev_user_channel_id,
4150                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4151                 )];
4152                 self.forward_htlcs(&mut per_source_pending_forward);
4153                 Ok(())
4154         }
4155
4156         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4157         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4158         ///
4159         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4160         /// backwards.
4161         ///
4162         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4163         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4164                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4165
4166                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4167                         .ok_or_else(|| APIError::APIMisuseError {
4168                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4169                         })?;
4170
4171                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4172                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4173                                 short_channel_id: payment.prev_short_channel_id,
4174                                 user_channel_id: Some(payment.prev_user_channel_id),
4175                                 outpoint: payment.prev_funding_outpoint,
4176                                 htlc_id: payment.prev_htlc_id,
4177                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4178                                 phantom_shared_secret: None,
4179                         });
4180
4181                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4182                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4183                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4184                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4185
4186                 Ok(())
4187         }
4188
4189         /// Processes HTLCs which are pending waiting on random forward delay.
4190         ///
4191         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4192         /// Will likely generate further events.
4193         pub fn process_pending_htlc_forwards(&self) {
4194                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4195
4196                 let mut new_events = VecDeque::new();
4197                 let mut failed_forwards = Vec::new();
4198                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4199                 {
4200                         let mut forward_htlcs = HashMap::new();
4201                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4202
4203                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4204                                 if short_chan_id != 0 {
4205                                         macro_rules! forwarding_channel_not_found {
4206                                                 () => {
4207                                                         for forward_info in pending_forwards.drain(..) {
4208                                                                 match forward_info {
4209                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4210                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4211                                                                                 forward_info: PendingHTLCInfo {
4212                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4213                                                                                         outgoing_cltv_value, ..
4214                                                                                 }
4215                                                                         }) => {
4216                                                                                 macro_rules! failure_handler {
4217                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4218                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4219
4220                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4221                                                                                                         short_channel_id: prev_short_channel_id,
4222                                                                                                         user_channel_id: Some(prev_user_channel_id),
4223                                                                                                         outpoint: prev_funding_outpoint,
4224                                                                                                         htlc_id: prev_htlc_id,
4225                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4226                                                                                                         phantom_shared_secret: $phantom_ss,
4227                                                                                                 });
4228
4229                                                                                                 let reason = if $next_hop_unknown {
4230                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4231                                                                                                 } else {
4232                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4233                                                                                                 };
4234
4235                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4236                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4237                                                                                                         reason
4238                                                                                                 ));
4239                                                                                                 continue;
4240                                                                                         }
4241                                                                                 }
4242                                                                                 macro_rules! fail_forward {
4243                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4244                                                                                                 {
4245                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4246                                                                                                 }
4247                                                                                         }
4248                                                                                 }
4249                                                                                 macro_rules! failed_payment {
4250                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4251                                                                                                 {
4252                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4253                                                                                                 }
4254                                                                                         }
4255                                                                                 }
4256                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
4257                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4258                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4259                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4260                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4261                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4262                                                                                                         payment_hash, &self.node_signer
4263                                                                                                 ) {
4264                                                                                                         Ok(res) => res,
4265                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4266                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
4267                                                                                                                 // In this scenario, the phantom would have sent us an
4268                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4269                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4270                                                                                                                 // of the onion.
4271                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4272                                                                                                         },
4273                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4274                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4275                                                                                                         },
4276                                                                                                 };
4277                                                                                                 match next_hop {
4278                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4279                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data,
4280                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4281                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None)
4282                                                                                                                 {
4283                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4284                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4285                                                                                                                 }
4286                                                                                                         },
4287                                                                                                         _ => panic!(),
4288                                                                                                 }
4289                                                                                         } else {
4290                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4291                                                                                         }
4292                                                                                 } else {
4293                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4294                                                                                 }
4295                                                                         },
4296                                                                         HTLCForwardInfo::FailHTLC { .. } => {
4297                                                                                 // Channel went away before we could fail it. This implies
4298                                                                                 // the channel is now on chain and our counterparty is
4299                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4300                                                                                 // problem, not ours.
4301                                                                         }
4302                                                                 }
4303                                                         }
4304                                                 }
4305                                         }
4306                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4307                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4308                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4309                                                 None => {
4310                                                         forwarding_channel_not_found!();
4311                                                         continue;
4312                                                 }
4313                                         };
4314                                         let per_peer_state = self.per_peer_state.read().unwrap();
4315                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4316                                         if peer_state_mutex_opt.is_none() {
4317                                                 forwarding_channel_not_found!();
4318                                                 continue;
4319                                         }
4320                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4321                                         let peer_state = &mut *peer_state_lock;
4322                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4323                                                 for forward_info in pending_forwards.drain(..) {
4324                                                         match forward_info {
4325                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4326                                                                         prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4327                                                                         forward_info: PendingHTLCInfo {
4328                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4329                                                                                 routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
4330                                                                         },
4331                                                                 }) => {
4332                                                                         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);
4333                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4334                                                                                 short_channel_id: prev_short_channel_id,
4335                                                                                 user_channel_id: Some(prev_user_channel_id),
4336                                                                                 outpoint: prev_funding_outpoint,
4337                                                                                 htlc_id: prev_htlc_id,
4338                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4339                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4340                                                                                 phantom_shared_secret: None,
4341                                                                         });
4342                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4343                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4344                                                                                 onion_packet, skimmed_fee_msat, &self.fee_estimator,
4345                                                                                 &self.logger)
4346                                                                         {
4347                                                                                 if let ChannelError::Ignore(msg) = e {
4348                                                                                         log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4349                                                                                 } else {
4350                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4351                                                                                 }
4352                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4353                                                                                 failed_forwards.push((htlc_source, payment_hash,
4354                                                                                         HTLCFailReason::reason(failure_code, data),
4355                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4356                                                                                 ));
4357                                                                                 continue;
4358                                                                         }
4359                                                                 },
4360                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4361                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4362                                                                 },
4363                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4364                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4365                                                                         if let Err(e) = chan.queue_fail_htlc(
4366                                                                                 htlc_id, err_packet, &self.logger
4367                                                                         ) {
4368                                                                                 if let ChannelError::Ignore(msg) = e {
4369                                                                                         log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4370                                                                                 } else {
4371                                                                                         panic!("Stated return value requirements in queue_fail_htlc() were not met");
4372                                                                                 }
4373                                                                                 // fail-backs are best-effort, we probably already have one
4374                                                                                 // pending, and if not that's OK, if not, the channel is on
4375                                                                                 // the chain and sending the HTLC-Timeout is their problem.
4376                                                                                 continue;
4377                                                                         }
4378                                                                 },
4379                                                         }
4380                                                 }
4381                                         } else {
4382                                                 forwarding_channel_not_found!();
4383                                                 continue;
4384                                         }
4385                                 } else {
4386                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4387                                                 match forward_info {
4388                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4389                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4390                                                                 forward_info: PendingHTLCInfo {
4391                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4392                                                                         skimmed_fee_msat, ..
4393                                                                 }
4394                                                         }) => {
4395                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4396                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4397                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4398                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4399                                                                                                 payment_metadata, custom_tlvs };
4400                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4401                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4402                                                                         },
4403                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4404                                                                                 let onion_fields = RecipientOnionFields {
4405                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4406                                                                                         payment_metadata,
4407                                                                                         custom_tlvs,
4408                                                                                 };
4409                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4410                                                                                         payment_data, None, onion_fields)
4411                                                                         },
4412                                                                         _ => {
4413                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4414                                                                         }
4415                                                                 };
4416                                                                 let claimable_htlc = ClaimableHTLC {
4417                                                                         prev_hop: HTLCPreviousHopData {
4418                                                                                 short_channel_id: prev_short_channel_id,
4419                                                                                 user_channel_id: Some(prev_user_channel_id),
4420                                                                                 outpoint: prev_funding_outpoint,
4421                                                                                 htlc_id: prev_htlc_id,
4422                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4423                                                                                 phantom_shared_secret,
4424                                                                         },
4425                                                                         // We differentiate the received value from the sender intended value
4426                                                                         // if possible so that we don't prematurely mark MPP payments complete
4427                                                                         // if routing nodes overpay
4428                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4429                                                                         sender_intended_value: outgoing_amt_msat,
4430                                                                         timer_ticks: 0,
4431                                                                         total_value_received: None,
4432                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4433                                                                         cltv_expiry,
4434                                                                         onion_payload,
4435                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4436                                                                 };
4437
4438                                                                 let mut committed_to_claimable = false;
4439
4440                                                                 macro_rules! fail_htlc {
4441                                                                         ($htlc: expr, $payment_hash: expr) => {
4442                                                                                 debug_assert!(!committed_to_claimable);
4443                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4444                                                                                 htlc_msat_height_data.extend_from_slice(
4445                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4446                                                                                 );
4447                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4448                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4449                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4450                                                                                                 outpoint: prev_funding_outpoint,
4451                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4452                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4453                                                                                                 phantom_shared_secret,
4454                                                                                         }), payment_hash,
4455                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4456                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4457                                                                                 ));
4458                                                                                 continue 'next_forwardable_htlc;
4459                                                                         }
4460                                                                 }
4461                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4462                                                                 let mut receiver_node_id = self.our_network_pubkey;
4463                                                                 if phantom_shared_secret.is_some() {
4464                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4465                                                                                 .expect("Failed to get node_id for phantom node recipient");
4466                                                                 }
4467
4468                                                                 macro_rules! check_total_value {
4469                                                                         ($purpose: expr) => {{
4470                                                                                 let mut payment_claimable_generated = false;
4471                                                                                 let is_keysend = match $purpose {
4472                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4473                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4474                                                                                 };
4475                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4476                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4477                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4478                                                                                 }
4479                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4480                                                                                         .entry(payment_hash)
4481                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4482                                                                                         .or_insert_with(|| {
4483                                                                                                 committed_to_claimable = true;
4484                                                                                                 ClaimablePayment {
4485                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4486                                                                                                 }
4487                                                                                         });
4488                                                                                 if $purpose != claimable_payment.purpose {
4489                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4490                                                                                         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));
4491                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4492                                                                                 }
4493                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4494                                                                                         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);
4495                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4496                                                                                 }
4497                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4498                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4499                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4500                                                                                         }
4501                                                                                 } else {
4502                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4503                                                                                 }
4504                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4505                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4506                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4507                                                                                 for htlc in htlcs.iter() {
4508                                                                                         total_value += htlc.sender_intended_value;
4509                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4510                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4511                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4512                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4513                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4514                                                                                         }
4515                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4516                                                                                 }
4517                                                                                 // The condition determining whether an MPP is complete must
4518                                                                                 // match exactly the condition used in `timer_tick_occurred`
4519                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4520                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4521                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4522                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4523                                                                                                 &payment_hash);
4524                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4525                                                                                 } else if total_value >= claimable_htlc.total_msat {
4526                                                                                         #[allow(unused_assignments)] {
4527                                                                                                 committed_to_claimable = true;
4528                                                                                         }
4529                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4530                                                                                         htlcs.push(claimable_htlc);
4531                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4532                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4533                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4534                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4535                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4536                                                                                                 counterparty_skimmed_fee_msat);
4537                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4538                                                                                                 receiver_node_id: Some(receiver_node_id),
4539                                                                                                 payment_hash,
4540                                                                                                 purpose: $purpose,
4541                                                                                                 amount_msat,
4542                                                                                                 counterparty_skimmed_fee_msat,
4543                                                                                                 via_channel_id: Some(prev_channel_id),
4544                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4545                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4546                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4547                                                                                         }, None));
4548                                                                                         payment_claimable_generated = true;
4549                                                                                 } else {
4550                                                                                         // Nothing to do - we haven't reached the total
4551                                                                                         // payment value yet, wait until we receive more
4552                                                                                         // MPP parts.
4553                                                                                         htlcs.push(claimable_htlc);
4554                                                                                         #[allow(unused_assignments)] {
4555                                                                                                 committed_to_claimable = true;
4556                                                                                         }
4557                                                                                 }
4558                                                                                 payment_claimable_generated
4559                                                                         }}
4560                                                                 }
4561
4562                                                                 // Check that the payment hash and secret are known. Note that we
4563                                                                 // MUST take care to handle the "unknown payment hash" and
4564                                                                 // "incorrect payment secret" cases here identically or we'd expose
4565                                                                 // that we are the ultimate recipient of the given payment hash.
4566                                                                 // Further, we must not expose whether we have any other HTLCs
4567                                                                 // associated with the same payment_hash pending or not.
4568                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4569                                                                 match payment_secrets.entry(payment_hash) {
4570                                                                         hash_map::Entry::Vacant(_) => {
4571                                                                                 match claimable_htlc.onion_payload {
4572                                                                                         OnionPayload::Invoice { .. } => {
4573                                                                                                 let payment_data = payment_data.unwrap();
4574                                                                                                 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) {
4575                                                                                                         Ok(result) => result,
4576                                                                                                         Err(()) => {
4577                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4578                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4579                                                                                                         }
4580                                                                                                 };
4581                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4582                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4583                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4584                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4585                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4586                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4587                                                                                                         }
4588                                                                                                 }
4589                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4590                                                                                                         payment_preimage: payment_preimage.clone(),
4591                                                                                                         payment_secret: payment_data.payment_secret,
4592                                                                                                 };
4593                                                                                                 check_total_value!(purpose);
4594                                                                                         },
4595                                                                                         OnionPayload::Spontaneous(preimage) => {
4596                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4597                                                                                                 check_total_value!(purpose);
4598                                                                                         }
4599                                                                                 }
4600                                                                         },
4601                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4602                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4603                                                                                         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);
4604                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4605                                                                                 }
4606                                                                                 let payment_data = payment_data.unwrap();
4607                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4608                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4609                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4610                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4611                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4612                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4613                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4614                                                                                 } else {
4615                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4616                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4617                                                                                                 payment_secret: payment_data.payment_secret,
4618                                                                                         };
4619                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4620                                                                                         if payment_claimable_generated {
4621                                                                                                 inbound_payment.remove_entry();
4622                                                                                         }
4623                                                                                 }
4624                                                                         },
4625                                                                 };
4626                                                         },
4627                                                         HTLCForwardInfo::FailHTLC { .. } => {
4628                                                                 panic!("Got pending fail of our own HTLC");
4629                                                         }
4630                                                 }
4631                                         }
4632                                 }
4633                         }
4634                 }
4635
4636                 let best_block_height = self.best_block.read().unwrap().height();
4637                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4638                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4639                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4640
4641                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4642                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4643                 }
4644                 self.forward_htlcs(&mut phantom_receives);
4645
4646                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4647                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4648                 // nice to do the work now if we can rather than while we're trying to get messages in the
4649                 // network stack.
4650                 self.check_free_holding_cells();
4651
4652                 if new_events.is_empty() { return }
4653                 let mut events = self.pending_events.lock().unwrap();
4654                 events.append(&mut new_events);
4655         }
4656
4657         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4658         ///
4659         /// Expects the caller to have a total_consistency_lock read lock.
4660         fn process_background_events(&self) -> NotifyOption {
4661                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4662
4663                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4664
4665                 let mut background_events = Vec::new();
4666                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4667                 if background_events.is_empty() {
4668                         return NotifyOption::SkipPersistNoEvents;
4669                 }
4670
4671                 for event in background_events.drain(..) {
4672                         match event {
4673                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4674                                         // The channel has already been closed, so no use bothering to care about the
4675                                         // monitor updating completing.
4676                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4677                                 },
4678                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4679                                         let mut updated_chan = false;
4680                                         {
4681                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4682                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4683                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4684                                                         let peer_state = &mut *peer_state_lock;
4685                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4686                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4687                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4688                                                                                 updated_chan = true;
4689                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4690                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4691                                                                         } else {
4692                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4693                                                                         }
4694                                                                 },
4695                                                                 hash_map::Entry::Vacant(_) => {},
4696                                                         }
4697                                                 }
4698                                         }
4699                                         if !updated_chan {
4700                                                 // TODO: Track this as in-flight even though the channel is closed.
4701                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4702                                         }
4703                                 },
4704                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4705                                         let per_peer_state = self.per_peer_state.read().unwrap();
4706                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4707                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4708                                                 let peer_state = &mut *peer_state_lock;
4709                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4710                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4711                                                 } else {
4712                                                         let update_actions = peer_state.monitor_update_blocked_actions
4713                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4714                                                         mem::drop(peer_state_lock);
4715                                                         mem::drop(per_peer_state);
4716                                                         self.handle_monitor_update_completion_actions(update_actions);
4717                                                 }
4718                                         }
4719                                 },
4720                         }
4721                 }
4722                 NotifyOption::DoPersist
4723         }
4724
4725         #[cfg(any(test, feature = "_test_utils"))]
4726         /// Process background events, for functional testing
4727         pub fn test_process_background_events(&self) {
4728                 let _lck = self.total_consistency_lock.read().unwrap();
4729                 let _ = self.process_background_events();
4730         }
4731
4732         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4733                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4734                 // If the feerate has decreased by less than half, don't bother
4735                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4736                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4737                                 log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4738                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4739                         }
4740                         return NotifyOption::SkipPersistNoEvents;
4741                 }
4742                 if !chan.context.is_live() {
4743                         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).",
4744                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4745                         return NotifyOption::SkipPersistNoEvents;
4746                 }
4747                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4748                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4749
4750                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4751                 NotifyOption::DoPersist
4752         }
4753
4754         #[cfg(fuzzing)]
4755         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4756         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4757         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4758         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4759         pub fn maybe_update_chan_fees(&self) {
4760                 PersistenceNotifierGuard::optionally_notify(self, || {
4761                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4762
4763                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4764                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4765
4766                         let per_peer_state = self.per_peer_state.read().unwrap();
4767                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4768                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4769                                 let peer_state = &mut *peer_state_lock;
4770                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4771                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4772                                 ) {
4773                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4774                                                 min_mempool_feerate
4775                                         } else {
4776                                                 normal_feerate
4777                                         };
4778                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4779                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4780                                 }
4781                         }
4782
4783                         should_persist
4784                 });
4785         }
4786
4787         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4788         ///
4789         /// This currently includes:
4790         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4791         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4792         ///    than a minute, informing the network that they should no longer attempt to route over
4793         ///    the channel.
4794         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4795         ///    with the current [`ChannelConfig`].
4796         ///  * Removing peers which have disconnected but and no longer have any channels.
4797         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4798         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4799         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4800         ///    The latter is determined using the system clock in `std` and the block time minus two
4801         ///    hours in `no-std`.
4802         ///
4803         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4804         /// estimate fetches.
4805         ///
4806         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4807         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4808         pub fn timer_tick_occurred(&self) {
4809                 PersistenceNotifierGuard::optionally_notify(self, || {
4810                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4811
4812                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4813                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4814
4815                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4816                         let mut timed_out_mpp_htlcs = Vec::new();
4817                         let mut pending_peers_awaiting_removal = Vec::new();
4818                         let mut shutdown_channels = Vec::new();
4819
4820                         let mut process_unfunded_channel_tick = |
4821                                 chan_id: &ChannelId,
4822                                 context: &mut ChannelContext<SP>,
4823                                 unfunded_context: &mut UnfundedChannelContext,
4824                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4825                                 counterparty_node_id: PublicKey,
4826                         | {
4827                                 context.maybe_expire_prev_config();
4828                                 if unfunded_context.should_expire_unfunded_channel() {
4829                                         log_error!(self.logger,
4830                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4831                                         update_maps_on_chan_removal!(self, &context);
4832                                         self.issue_channel_close_events(&context, ClosureReason::HolderForceClosed);
4833                                         shutdown_channels.push(context.force_shutdown(false));
4834                                         pending_msg_events.push(MessageSendEvent::HandleError {
4835                                                 node_id: counterparty_node_id,
4836                                                 action: msgs::ErrorAction::SendErrorMessage {
4837                                                         msg: msgs::ErrorMessage {
4838                                                                 channel_id: *chan_id,
4839                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4840                                                         },
4841                                                 },
4842                                         });
4843                                         false
4844                                 } else {
4845                                         true
4846                                 }
4847                         };
4848
4849                         {
4850                                 let per_peer_state = self.per_peer_state.read().unwrap();
4851                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4852                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4853                                         let peer_state = &mut *peer_state_lock;
4854                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4855                                         let counterparty_node_id = *counterparty_node_id;
4856                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4857                                                 match phase {
4858                                                         ChannelPhase::Funded(chan) => {
4859                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4860                                                                         min_mempool_feerate
4861                                                                 } else {
4862                                                                         normal_feerate
4863                                                                 };
4864                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4865                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4866
4867                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4868                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4869                                                                         handle_errors.push((Err(err), counterparty_node_id));
4870                                                                         if needs_close { return false; }
4871                                                                 }
4872
4873                                                                 match chan.channel_update_status() {
4874                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4875                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4876                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4877                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4878                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4879                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4880                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4881                                                                                 n += 1;
4882                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4883                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4884                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4885                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4886                                                                                                         msg: update
4887                                                                                                 });
4888                                                                                         }
4889                                                                                         should_persist = NotifyOption::DoPersist;
4890                                                                                 } else {
4891                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4892                                                                                 }
4893                                                                         },
4894                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4895                                                                                 n += 1;
4896                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4897                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4898                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4899                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4900                                                                                                         msg: update
4901                                                                                                 });
4902                                                                                         }
4903                                                                                         should_persist = NotifyOption::DoPersist;
4904                                                                                 } else {
4905                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4906                                                                                 }
4907                                                                         },
4908                                                                         _ => {},
4909                                                                 }
4910
4911                                                                 chan.context.maybe_expire_prev_config();
4912
4913                                                                 if chan.should_disconnect_peer_awaiting_response() {
4914                                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4915                                                                                         counterparty_node_id, chan_id);
4916                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4917                                                                                 node_id: counterparty_node_id,
4918                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4919                                                                                         msg: msgs::WarningMessage {
4920                                                                                                 channel_id: *chan_id,
4921                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4922                                                                                         },
4923                                                                                 },
4924                                                                         });
4925                                                                 }
4926
4927                                                                 true
4928                                                         },
4929                                                         ChannelPhase::UnfundedInboundV1(chan) => {
4930                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4931                                                                         pending_msg_events, counterparty_node_id)
4932                                                         },
4933                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
4934                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
4935                                                                         pending_msg_events, counterparty_node_id)
4936                                                         },
4937                                                 }
4938                                         });
4939
4940                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4941                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4942                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
4943                                                         peer_state.pending_msg_events.push(
4944                                                                 events::MessageSendEvent::HandleError {
4945                                                                         node_id: counterparty_node_id,
4946                                                                         action: msgs::ErrorAction::SendErrorMessage {
4947                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4948                                                                         },
4949                                                                 }
4950                                                         );
4951                                                 }
4952                                         }
4953                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4954
4955                                         if peer_state.ok_to_remove(true) {
4956                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4957                                         }
4958                                 }
4959                         }
4960
4961                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4962                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4963                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4964                         // we therefore need to remove the peer from `peer_state` separately.
4965                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4966                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4967                         // negative effects on parallelism as much as possible.
4968                         if pending_peers_awaiting_removal.len() > 0 {
4969                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4970                                 for counterparty_node_id in pending_peers_awaiting_removal {
4971                                         match per_peer_state.entry(counterparty_node_id) {
4972                                                 hash_map::Entry::Occupied(entry) => {
4973                                                         // Remove the entry if the peer is still disconnected and we still
4974                                                         // have no channels to the peer.
4975                                                         let remove_entry = {
4976                                                                 let peer_state = entry.get().lock().unwrap();
4977                                                                 peer_state.ok_to_remove(true)
4978                                                         };
4979                                                         if remove_entry {
4980                                                                 entry.remove_entry();
4981                                                         }
4982                                                 },
4983                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
4984                                         }
4985                                 }
4986                         }
4987
4988                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
4989                                 if payment.htlcs.is_empty() {
4990                                         // This should be unreachable
4991                                         debug_assert!(false);
4992                                         return false;
4993                                 }
4994                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
4995                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
4996                                         // In this case we're not going to handle any timeouts of the parts here.
4997                                         // This condition determining whether the MPP is complete here must match
4998                                         // exactly the condition used in `process_pending_htlc_forwards`.
4999                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5000                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5001                                         {
5002                                                 return true;
5003                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5004                                                 htlc.timer_ticks += 1;
5005                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5006                                         }) {
5007                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5008                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5009                                                 return false;
5010                                         }
5011                                 }
5012                                 true
5013                         });
5014
5015                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5016                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5017                                 let reason = HTLCFailReason::from_failure_code(23);
5018                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5019                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5020                         }
5021
5022                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5023                                 let _ = handle_error!(self, err, counterparty_node_id);
5024                         }
5025
5026                         for shutdown_res in shutdown_channels {
5027                                 self.finish_close_channel(shutdown_res);
5028                         }
5029
5030                         #[cfg(feature = "std")]
5031                         let duration_since_epoch = std::time::SystemTime::now()
5032                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5033                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5034                         #[cfg(not(feature = "std"))]
5035                         let duration_since_epoch = Duration::from_secs(
5036                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5037                         );
5038
5039                         self.pending_outbound_payments.remove_stale_payments(
5040                                 duration_since_epoch, &self.pending_events
5041                         );
5042
5043                         // Technically we don't need to do this here, but if we have holding cell entries in a
5044                         // channel that need freeing, it's better to do that here and block a background task
5045                         // than block the message queueing pipeline.
5046                         if self.check_free_holding_cells() {
5047                                 should_persist = NotifyOption::DoPersist;
5048                         }
5049
5050                         should_persist
5051                 });
5052         }
5053
5054         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5055         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5056         /// along the path (including in our own channel on which we received it).
5057         ///
5058         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5059         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5060         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5061         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5062         ///
5063         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5064         /// [`ChannelManager::claim_funds`]), you should still monitor for
5065         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5066         /// startup during which time claims that were in-progress at shutdown may be replayed.
5067         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5068                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5069         }
5070
5071         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5072         /// reason for the failure.
5073         ///
5074         /// See [`FailureCode`] for valid failure codes.
5075         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5076                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5077
5078                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5079                 if let Some(payment) = removed_source {
5080                         for htlc in payment.htlcs {
5081                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5082                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5083                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5084                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5085                         }
5086                 }
5087         }
5088
5089         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5090         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5091                 match failure_code {
5092                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5093                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5094                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5095                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5096                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5097                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5098                         },
5099                         FailureCode::InvalidOnionPayload(data) => {
5100                                 let fail_data = match data {
5101                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5102                                         None => Vec::new(),
5103                                 };
5104                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5105                         }
5106                 }
5107         }
5108
5109         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5110         /// that we want to return and a channel.
5111         ///
5112         /// This is for failures on the channel on which the HTLC was *received*, not failures
5113         /// forwarding
5114         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5115                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5116                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5117                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5118                 // an inbound SCID alias before the real SCID.
5119                 let scid_pref = if chan.context.should_announce() {
5120                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5121                 } else {
5122                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5123                 };
5124                 if let Some(scid) = scid_pref {
5125                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5126                 } else {
5127                         (0x4000|10, Vec::new())
5128                 }
5129         }
5130
5131
5132         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5133         /// that we want to return and a channel.
5134         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5135                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5136                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5137                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5138                         if desired_err_code == 0x1000 | 20 {
5139                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5140                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5141                                 0u16.write(&mut enc).expect("Writes cannot fail");
5142                         }
5143                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5144                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5145                         upd.write(&mut enc).expect("Writes cannot fail");
5146                         (desired_err_code, enc.0)
5147                 } else {
5148                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5149                         // which means we really shouldn't have gotten a payment to be forwarded over this
5150                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5151                         // PERM|no_such_channel should be fine.
5152                         (0x4000|10, Vec::new())
5153                 }
5154         }
5155
5156         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5157         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5158         // be surfaced to the user.
5159         fn fail_holding_cell_htlcs(
5160                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5161                 counterparty_node_id: &PublicKey
5162         ) {
5163                 let (failure_code, onion_failure_data) = {
5164                         let per_peer_state = self.per_peer_state.read().unwrap();
5165                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5166                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5167                                 let peer_state = &mut *peer_state_lock;
5168                                 match peer_state.channel_by_id.entry(channel_id) {
5169                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5170                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5171                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5172                                                 } else {
5173                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5174                                                         debug_assert!(false);
5175                                                         (0x4000|10, Vec::new())
5176                                                 }
5177                                         },
5178                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5179                                 }
5180                         } else { (0x4000|10, Vec::new()) }
5181                 };
5182
5183                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5184                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5185                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5186                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5187                 }
5188         }
5189
5190         /// Fails an HTLC backwards to the sender of it to us.
5191         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5192         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5193                 // Ensure that no peer state channel storage lock is held when calling this function.
5194                 // This ensures that future code doesn't introduce a lock-order requirement for
5195                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5196                 // this function with any `per_peer_state` peer lock acquired would.
5197                 #[cfg(debug_assertions)]
5198                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5199                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5200                 }
5201
5202                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5203                 //identify whether we sent it or not based on the (I presume) very different runtime
5204                 //between the branches here. We should make this async and move it into the forward HTLCs
5205                 //timer handling.
5206
5207                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5208                 // from block_connected which may run during initialization prior to the chain_monitor
5209                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5210                 match source {
5211                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5212                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5213                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5214                                         &self.pending_events, &self.logger)
5215                                 { self.push_pending_forwards_ev(); }
5216                         },
5217                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint, .. }) => {
5218                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", &payment_hash, onion_error);
5219                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
5220
5221                                 let mut push_forward_ev = false;
5222                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5223                                 if forward_htlcs.is_empty() {
5224                                         push_forward_ev = true;
5225                                 }
5226                                 match forward_htlcs.entry(*short_channel_id) {
5227                                         hash_map::Entry::Occupied(mut entry) => {
5228                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
5229                                         },
5230                                         hash_map::Entry::Vacant(entry) => {
5231                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
5232                                         }
5233                                 }
5234                                 mem::drop(forward_htlcs);
5235                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5236                                 let mut pending_events = self.pending_events.lock().unwrap();
5237                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5238                                         prev_channel_id: outpoint.to_channel_id(),
5239                                         failed_next_destination: destination,
5240                                 }, None));
5241                         },
5242                 }
5243         }
5244
5245         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5246         /// [`MessageSendEvent`]s needed to claim the payment.
5247         ///
5248         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5249         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5250         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5251         /// successful. It will generally be available in the next [`process_pending_events`] call.
5252         ///
5253         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5254         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5255         /// event matches your expectation. If you fail to do so and call this method, you may provide
5256         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5257         ///
5258         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5259         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5260         /// [`claim_funds_with_known_custom_tlvs`].
5261         ///
5262         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5263         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5264         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5265         /// [`process_pending_events`]: EventsProvider::process_pending_events
5266         /// [`create_inbound_payment`]: Self::create_inbound_payment
5267         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5268         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5269         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5270                 self.claim_payment_internal(payment_preimage, false);
5271         }
5272
5273         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5274         /// even type numbers.
5275         ///
5276         /// # Note
5277         ///
5278         /// You MUST check you've understood all even TLVs before using this to
5279         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5280         ///
5281         /// [`claim_funds`]: Self::claim_funds
5282         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5283                 self.claim_payment_internal(payment_preimage, true);
5284         }
5285
5286         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5287                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5288
5289                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5290
5291                 let mut sources = {
5292                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5293                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5294                                 let mut receiver_node_id = self.our_network_pubkey;
5295                                 for htlc in payment.htlcs.iter() {
5296                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5297                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5298                                                         .expect("Failed to get node_id for phantom node recipient");
5299                                                 receiver_node_id = phantom_pubkey;
5300                                                 break;
5301                                         }
5302                                 }
5303
5304                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5305                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5306                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5307                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5308                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5309                                 });
5310                                 if dup_purpose.is_some() {
5311                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5312                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5313                                                 &payment_hash);
5314                                 }
5315
5316                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5317                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5318                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5319                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5320                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5321                                                 mem::drop(claimable_payments);
5322                                                 for htlc in payment.htlcs {
5323                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5324                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5325                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5326                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5327                                                 }
5328                                                 return;
5329                                         }
5330                                 }
5331
5332                                 payment.htlcs
5333                         } else { return; }
5334                 };
5335                 debug_assert!(!sources.is_empty());
5336
5337                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5338                 // and when we got here we need to check that the amount we're about to claim matches the
5339                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5340                 // the MPP parts all have the same `total_msat`.
5341                 let mut claimable_amt_msat = 0;
5342                 let mut prev_total_msat = None;
5343                 let mut expected_amt_msat = None;
5344                 let mut valid_mpp = true;
5345                 let mut errs = Vec::new();
5346                 let per_peer_state = self.per_peer_state.read().unwrap();
5347                 for htlc in sources.iter() {
5348                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5349                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5350                                 debug_assert!(false);
5351                                 valid_mpp = false;
5352                                 break;
5353                         }
5354                         prev_total_msat = Some(htlc.total_msat);
5355
5356                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5357                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5358                                 debug_assert!(false);
5359                                 valid_mpp = false;
5360                                 break;
5361                         }
5362                         expected_amt_msat = htlc.total_value_received;
5363                         claimable_amt_msat += htlc.value;
5364                 }
5365                 mem::drop(per_peer_state);
5366                 if sources.is_empty() || expected_amt_msat.is_none() {
5367                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5368                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5369                         return;
5370                 }
5371                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5372                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5373                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5374                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5375                         return;
5376                 }
5377                 if valid_mpp {
5378                         for htlc in sources.drain(..) {
5379                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5380                                         htlc.prev_hop, payment_preimage,
5381                                         |_| Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash }))
5382                                 {
5383                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5384                                                 // We got a temporary failure updating monitor, but will claim the
5385                                                 // HTLC when the monitor updating is restored (or on chain).
5386                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5387                                         } else { errs.push((pk, err)); }
5388                                 }
5389                         }
5390                 }
5391                 if !valid_mpp {
5392                         for htlc in sources.drain(..) {
5393                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5394                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5395                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5396                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5397                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5398                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5399                         }
5400                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5401                 }
5402
5403                 // Now we can handle any errors which were generated.
5404                 for (counterparty_node_id, err) in errs.drain(..) {
5405                         let res: Result<(), _> = Err(err);
5406                         let _ = handle_error!(self, res, counterparty_node_id);
5407                 }
5408         }
5409
5410         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>) -> Option<MonitorUpdateCompletionAction>>(&self,
5411                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5412         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5413                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5414
5415                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5416                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5417                 // `BackgroundEvent`s.
5418                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5419
5420                 {
5421                         let per_peer_state = self.per_peer_state.read().unwrap();
5422                         let chan_id = prev_hop.outpoint.to_channel_id();
5423                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5424                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5425                                 None => None
5426                         };
5427
5428                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5429                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5430                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5431                         ).unwrap_or(None);
5432
5433                         if peer_state_opt.is_some() {
5434                                 let mut peer_state_lock = peer_state_opt.unwrap();
5435                                 let peer_state = &mut *peer_state_lock;
5436                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5437                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5438                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5439                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5440
5441                                                 if let UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } = fulfill_res {
5442                                                         if let Some(action) = completion_action(Some(htlc_value_msat)) {
5443                                                                 log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5444                                                                         chan_id, action);
5445                                                                 peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5446                                                         }
5447                                                         if !during_init {
5448                                                                 handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5449                                                                         peer_state, per_peer_state, chan);
5450                                                         } else {
5451                                                                 // If we're running during init we cannot update a monitor directly -
5452                                                                 // they probably haven't actually been loaded yet. Instead, push the
5453                                                                 // monitor update as a background event.
5454                                                                 self.pending_background_events.lock().unwrap().push(
5455                                                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5456                                                                                 counterparty_node_id,
5457                                                                                 funding_txo: prev_hop.outpoint,
5458                                                                                 update: monitor_update.clone(),
5459                                                                         });
5460                                                         }
5461                                                 }
5462                                         }
5463                                         return Ok(());
5464                                 }
5465                         }
5466                 }
5467                 let preimage_update = ChannelMonitorUpdate {
5468                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5469                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5470                                 payment_preimage,
5471                         }],
5472                 };
5473
5474                 if !during_init {
5475                         // We update the ChannelMonitor on the backward link, after
5476                         // receiving an `update_fulfill_htlc` from the forward link.
5477                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5478                         if update_res != ChannelMonitorUpdateStatus::Completed {
5479                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5480                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5481                                 // channel, or we must have an ability to receive the same event and try
5482                                 // again on restart.
5483                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5484                                         payment_preimage, update_res);
5485                         }
5486                 } else {
5487                         // If we're running during init we cannot update a monitor directly - they probably
5488                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5489                         // event.
5490                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5491                         // channel is already closed) we need to ultimately handle the monitor update
5492                         // completion action only after we've completed the monitor update. This is the only
5493                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5494                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5495                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5496                         // complete the monitor update completion action from `completion_action`.
5497                         self.pending_background_events.lock().unwrap().push(
5498                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5499                                         prev_hop.outpoint, preimage_update,
5500                                 )));
5501                 }
5502                 // Note that we do process the completion action here. This totally could be a
5503                 // duplicate claim, but we have no way of knowing without interrogating the
5504                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5505                 // generally always allowed to be duplicative (and it's specifically noted in
5506                 // `PaymentForwarded`).
5507                 self.handle_monitor_update_completion_actions(completion_action(None));
5508                 Ok(())
5509         }
5510
5511         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5512                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5513         }
5514
5515         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5516                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool,
5517                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint
5518         ) {
5519                 match source {
5520                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5521                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5522                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5523                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5524                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5525                                 }
5526                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5527                                         channel_funding_outpoint: next_channel_outpoint,
5528                                         counterparty_node_id: path.hops[0].pubkey,
5529                                 };
5530                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5531                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5532                                         &self.logger);
5533                         },
5534                         HTLCSource::PreviousHopData(hop_data) => {
5535                                 let prev_outpoint = hop_data.outpoint;
5536                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5537                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5538                                         |htlc_claim_value_msat| {
5539                                                 if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5540                                                         let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5541                                                                 Some(claimed_htlc_value - forwarded_htlc_value)
5542                                                         } else { None };
5543
5544                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5545                                                                 event: events::Event::PaymentForwarded {
5546                                                                         fee_earned_msat,
5547                                                                         claim_from_onchain_tx: from_onchain,
5548                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5549                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5550                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5551                                                                 },
5552                                                                 downstream_counterparty_and_funding_outpoint:
5553                                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5554                                                                                 Some((node_id, next_channel_outpoint, completed_blocker))
5555                                                                         } else {
5556                                                                                 // We can only get `None` here if we are processing a
5557                                                                                 // `ChannelMonitor`-originated event, in which case we
5558                                                                                 // don't care about ensuring we wake the downstream
5559                                                                                 // channel's monitor updating - the channel is already
5560                                                                                 // closed.
5561                                                                                 None
5562                                                                         },
5563                                                         })
5564                                                 } else { None }
5565                                         });
5566                                 if let Err((pk, err)) = res {
5567                                         let result: Result<(), _> = Err(err);
5568                                         let _ = handle_error!(self, result, pk);
5569                                 }
5570                         },
5571                 }
5572         }
5573
5574         /// Gets the node_id held by this ChannelManager
5575         pub fn get_our_node_id(&self) -> PublicKey {
5576                 self.our_network_pubkey.clone()
5577         }
5578
5579         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5580                 for action in actions.into_iter() {
5581                         match action {
5582                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5583                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5584                                         if let Some(ClaimingPayment {
5585                                                 amount_msat,
5586                                                 payment_purpose: purpose,
5587                                                 receiver_node_id,
5588                                                 htlcs,
5589                                                 sender_intended_value: sender_intended_total_msat,
5590                                         }) = payment {
5591                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5592                                                         payment_hash,
5593                                                         purpose,
5594                                                         amount_msat,
5595                                                         receiver_node_id: Some(receiver_node_id),
5596                                                         htlcs,
5597                                                         sender_intended_total_msat,
5598                                                 }, None));
5599                                         }
5600                                 },
5601                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5602                                         event, downstream_counterparty_and_funding_outpoint
5603                                 } => {
5604                                         self.pending_events.lock().unwrap().push_back((event, None));
5605                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5606                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5607                                         }
5608                                 },
5609                         }
5610                 }
5611         }
5612
5613         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5614         /// update completion.
5615         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5616                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5617                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5618                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5619                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5620         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5621                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5622                         &channel.context.channel_id(),
5623                         if raa.is_some() { "an" } else { "no" },
5624                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5625                         if funding_broadcastable.is_some() { "" } else { "not " },
5626                         if channel_ready.is_some() { "sending" } else { "without" },
5627                         if announcement_sigs.is_some() { "sending" } else { "without" });
5628
5629                 let mut htlc_forwards = None;
5630
5631                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5632                 if !pending_forwards.is_empty() {
5633                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5634                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5635                 }
5636
5637                 if let Some(msg) = channel_ready {
5638                         send_channel_ready!(self, pending_msg_events, channel, msg);
5639                 }
5640                 if let Some(msg) = announcement_sigs {
5641                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5642                                 node_id: counterparty_node_id,
5643                                 msg,
5644                         });
5645                 }
5646
5647                 macro_rules! handle_cs { () => {
5648                         if let Some(update) = commitment_update {
5649                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5650                                         node_id: counterparty_node_id,
5651                                         updates: update,
5652                                 });
5653                         }
5654                 } }
5655                 macro_rules! handle_raa { () => {
5656                         if let Some(revoke_and_ack) = raa {
5657                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5658                                         node_id: counterparty_node_id,
5659                                         msg: revoke_and_ack,
5660                                 });
5661                         }
5662                 } }
5663                 match order {
5664                         RAACommitmentOrder::CommitmentFirst => {
5665                                 handle_cs!();
5666                                 handle_raa!();
5667                         },
5668                         RAACommitmentOrder::RevokeAndACKFirst => {
5669                                 handle_raa!();
5670                                 handle_cs!();
5671                         },
5672                 }
5673
5674                 if let Some(tx) = funding_broadcastable {
5675                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5676                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5677                 }
5678
5679                 {
5680                         let mut pending_events = self.pending_events.lock().unwrap();
5681                         emit_channel_pending_event!(pending_events, channel);
5682                         emit_channel_ready_event!(pending_events, channel);
5683                 }
5684
5685                 htlc_forwards
5686         }
5687
5688         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5689                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5690
5691                 let counterparty_node_id = match counterparty_node_id {
5692                         Some(cp_id) => cp_id.clone(),
5693                         None => {
5694                                 // TODO: Once we can rely on the counterparty_node_id from the
5695                                 // monitor event, this and the id_to_peer map should be removed.
5696                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5697                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5698                                         Some(cp_id) => cp_id.clone(),
5699                                         None => return,
5700                                 }
5701                         }
5702                 };
5703                 let per_peer_state = self.per_peer_state.read().unwrap();
5704                 let mut peer_state_lock;
5705                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5706                 if peer_state_mutex_opt.is_none() { return }
5707                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5708                 let peer_state = &mut *peer_state_lock;
5709                 let channel =
5710                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5711                                 chan
5712                         } else {
5713                                 let update_actions = peer_state.monitor_update_blocked_actions
5714                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5715                                 mem::drop(peer_state_lock);
5716                                 mem::drop(per_peer_state);
5717                                 self.handle_monitor_update_completion_actions(update_actions);
5718                                 return;
5719                         };
5720                 let remaining_in_flight =
5721                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5722                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5723                                 pending.len()
5724                         } else { 0 };
5725                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5726                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5727                         remaining_in_flight);
5728                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5729                         return;
5730                 }
5731                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5732         }
5733
5734         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5735         ///
5736         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5737         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5738         /// the channel.
5739         ///
5740         /// The `user_channel_id` parameter will be provided back in
5741         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5742         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5743         ///
5744         /// Note that this method will return an error and reject the channel, if it requires support
5745         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5746         /// used to accept such channels.
5747         ///
5748         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5749         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5750         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5751                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5752         }
5753
5754         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5755         /// it as confirmed immediately.
5756         ///
5757         /// The `user_channel_id` parameter will be provided back in
5758         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5759         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5760         ///
5761         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5762         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5763         ///
5764         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5765         /// transaction and blindly assumes that it will eventually confirm.
5766         ///
5767         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5768         /// does not pay to the correct script the correct amount, *you will lose funds*.
5769         ///
5770         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5771         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5772         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5773                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5774         }
5775
5776         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5777                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5778
5779                 let peers_without_funded_channels =
5780                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5781                 let per_peer_state = self.per_peer_state.read().unwrap();
5782                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5783                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5784                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5785                 let peer_state = &mut *peer_state_lock;
5786                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5787
5788                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5789                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5790                 // that we can delay allocating the SCID until after we're sure that the checks below will
5791                 // succeed.
5792                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5793                         Some(unaccepted_channel) => {
5794                                 let best_block_height = self.best_block.read().unwrap().height();
5795                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5796                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5797                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5798                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5799                         }
5800                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5801                 }?;
5802
5803                 if accept_0conf {
5804                         // This should have been correctly configured by the call to InboundV1Channel::new.
5805                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5806                 } else if channel.context.get_channel_type().requires_zero_conf() {
5807                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5808                                 node_id: channel.context.get_counterparty_node_id(),
5809                                 action: msgs::ErrorAction::SendErrorMessage{
5810                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5811                                 }
5812                         };
5813                         peer_state.pending_msg_events.push(send_msg_err_event);
5814                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5815                 } else {
5816                         // If this peer already has some channels, a new channel won't increase our number of peers
5817                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5818                         // channels per-peer we can accept channels from a peer with existing ones.
5819                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5820                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5821                                         node_id: channel.context.get_counterparty_node_id(),
5822                                         action: msgs::ErrorAction::SendErrorMessage{
5823                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5824                                         }
5825                                 };
5826                                 peer_state.pending_msg_events.push(send_msg_err_event);
5827                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5828                         }
5829                 }
5830
5831                 // Now that we know we have a channel, assign an outbound SCID alias.
5832                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5833                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5834
5835                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5836                         node_id: channel.context.get_counterparty_node_id(),
5837                         msg: channel.accept_inbound_channel(),
5838                 });
5839
5840                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
5841
5842                 Ok(())
5843         }
5844
5845         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5846         /// or 0-conf channels.
5847         ///
5848         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
5849         /// non-0-conf channels we have with the peer.
5850         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
5851         where Filter: Fn(&PeerState<SP>) -> bool {
5852                 let mut peers_without_funded_channels = 0;
5853                 let best_block_height = self.best_block.read().unwrap().height();
5854                 {
5855                         let peer_state_lock = self.per_peer_state.read().unwrap();
5856                         for (_, peer_mtx) in peer_state_lock.iter() {
5857                                 let peer = peer_mtx.lock().unwrap();
5858                                 if !maybe_count_peer(&*peer) { continue; }
5859                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
5860                                 if num_unfunded_channels == peer.total_channel_count() {
5861                                         peers_without_funded_channels += 1;
5862                                 }
5863                         }
5864                 }
5865                 return peers_without_funded_channels;
5866         }
5867
5868         fn unfunded_channel_count(
5869                 peer: &PeerState<SP>, best_block_height: u32
5870         ) -> usize {
5871                 let mut num_unfunded_channels = 0;
5872                 for (_, phase) in peer.channel_by_id.iter() {
5873                         match phase {
5874                                 ChannelPhase::Funded(chan) => {
5875                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
5876                                         // which have not yet had any confirmations on-chain.
5877                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
5878                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
5879                                         {
5880                                                 num_unfunded_channels += 1;
5881                                         }
5882                                 },
5883                                 ChannelPhase::UnfundedInboundV1(chan) => {
5884                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
5885                                                 num_unfunded_channels += 1;
5886                                         }
5887                                 },
5888                                 ChannelPhase::UnfundedOutboundV1(_) => {
5889                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
5890                                         continue;
5891                                 }
5892                         }
5893                 }
5894                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
5895         }
5896
5897         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
5898                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
5899                 // likely to be lost on restart!
5900                 if msg.chain_hash != self.chain_hash {
5901                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
5902                 }
5903
5904                 if !self.default_configuration.accept_inbound_channels {
5905                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5906                 }
5907
5908                 // Get the number of peers with channels, but without funded ones. We don't care too much
5909                 // about peers that never open a channel, so we filter by peers that have at least one
5910                 // channel, and then limit the number of those with unfunded channels.
5911                 let channeled_peers_without_funding =
5912                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
5913
5914                 let per_peer_state = self.per_peer_state.read().unwrap();
5915                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5916                     .ok_or_else(|| {
5917                                 debug_assert!(false);
5918                                 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())
5919                         })?;
5920                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5921                 let peer_state = &mut *peer_state_lock;
5922
5923                 // If this peer already has some channels, a new channel won't increase our number of peers
5924                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5925                 // channels per-peer we can accept channels from a peer with existing ones.
5926                 if peer_state.total_channel_count() == 0 &&
5927                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
5928                         !self.default_configuration.manually_accept_inbound_channels
5929                 {
5930                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5931                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
5932                                 msg.temporary_channel_id.clone()));
5933                 }
5934
5935                 let best_block_height = self.best_block.read().unwrap().height();
5936                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
5937                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5938                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
5939                                 msg.temporary_channel_id.clone()));
5940                 }
5941
5942                 let channel_id = msg.temporary_channel_id;
5943                 let channel_exists = peer_state.has_channel(&channel_id);
5944                 if channel_exists {
5945                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
5946                 }
5947
5948                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
5949                 if self.default_configuration.manually_accept_inbound_channels {
5950                         let mut pending_events = self.pending_events.lock().unwrap();
5951                         pending_events.push_back((events::Event::OpenChannelRequest {
5952                                 temporary_channel_id: msg.temporary_channel_id.clone(),
5953                                 counterparty_node_id: counterparty_node_id.clone(),
5954                                 funding_satoshis: msg.funding_satoshis,
5955                                 push_msat: msg.push_msat,
5956                                 channel_type: msg.channel_type.clone().unwrap(),
5957                         }, None));
5958                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
5959                                 open_channel_msg: msg.clone(),
5960                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
5961                         });
5962                         return Ok(());
5963                 }
5964
5965                 // Otherwise create the channel right now.
5966                 let mut random_bytes = [0u8; 16];
5967                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
5968                 let user_channel_id = u128::from_be_bytes(random_bytes);
5969                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5970                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
5971                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
5972                 {
5973                         Err(e) => {
5974                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
5975                         },
5976                         Ok(res) => res
5977                 };
5978
5979                 let channel_type = channel.context.get_channel_type();
5980                 if channel_type.requires_zero_conf() {
5981                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5982                 }
5983                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
5984                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
5985                 }
5986
5987                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5988                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5989
5990                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5991                         node_id: counterparty_node_id.clone(),
5992                         msg: channel.accept_inbound_channel(),
5993                 });
5994                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
5995                 Ok(())
5996         }
5997
5998         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
5999                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6000                 // likely to be lost on restart!
6001                 let (value, output_script, user_id) = {
6002                         let per_peer_state = self.per_peer_state.read().unwrap();
6003                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6004                                 .ok_or_else(|| {
6005                                         debug_assert!(false);
6006                                         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)
6007                                 })?;
6008                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6009                         let peer_state = &mut *peer_state_lock;
6010                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6011                                 hash_map::Entry::Occupied(mut phase) => {
6012                                         match phase.get_mut() {
6013                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6014                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6015                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6016                                                 },
6017                                                 _ => {
6018                                                         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));
6019                                                 }
6020                                         }
6021                                 },
6022                                 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))
6023                         }
6024                 };
6025                 let mut pending_events = self.pending_events.lock().unwrap();
6026                 pending_events.push_back((events::Event::FundingGenerationReady {
6027                         temporary_channel_id: msg.temporary_channel_id,
6028                         counterparty_node_id: *counterparty_node_id,
6029                         channel_value_satoshis: value,
6030                         output_script,
6031                         user_channel_id: user_id,
6032                 }, None));
6033                 Ok(())
6034         }
6035
6036         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6037                 let best_block = *self.best_block.read().unwrap();
6038
6039                 let per_peer_state = self.per_peer_state.read().unwrap();
6040                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6041                         .ok_or_else(|| {
6042                                 debug_assert!(false);
6043                                 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)
6044                         })?;
6045
6046                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6047                 let peer_state = &mut *peer_state_lock;
6048                 let (chan, funding_msg, monitor) =
6049                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6050                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6051                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
6052                                                 Ok(res) => res,
6053                                                 Err((mut inbound_chan, err)) => {
6054                                                         // We've already removed this inbound channel from the map in `PeerState`
6055                                                         // above so at this point we just need to clean up any lingering entries
6056                                                         // concerning this channel as it is safe to do so.
6057                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
6058                                                         let user_id = inbound_chan.context.get_user_id();
6059                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
6060                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
6061                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
6062                                                 },
6063                                         }
6064                                 },
6065                                 Some(ChannelPhase::Funded(_)) | Some(ChannelPhase::UnfundedOutboundV1(_)) => {
6066                                         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));
6067                                 },
6068                                 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))
6069                         };
6070
6071                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
6072                         hash_map::Entry::Occupied(_) => {
6073                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
6074                         },
6075                         hash_map::Entry::Vacant(e) => {
6076                                 let mut id_to_peer_lock = self.id_to_peer.lock().unwrap();
6077                                 match id_to_peer_lock.entry(chan.context.channel_id()) {
6078                                         hash_map::Entry::Occupied(_) => {
6079                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
6080                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6081                                                         funding_msg.channel_id))
6082                                         },
6083                                         hash_map::Entry::Vacant(i_e) => {
6084                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6085                                                 if let Ok(persist_state) = monitor_res {
6086                                                         i_e.insert(chan.context.get_counterparty_node_id());
6087                                                         mem::drop(id_to_peer_lock);
6088
6089                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6090                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6091                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6092                                                         // until we have persisted our monitor.
6093                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6094                                                                 node_id: counterparty_node_id.clone(),
6095                                                                 msg: funding_msg,
6096                                                         });
6097
6098                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6099                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6100                                                                         per_peer_state, chan, INITIAL_MONITOR);
6101                                                         } else {
6102                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6103                                                         }
6104                                                         Ok(())
6105                                                 } else {
6106                                                         log_error!(self.logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6107                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6108                                                                 "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
6109                                                                 funding_msg.channel_id));
6110                                                 }
6111                                         }
6112                                 }
6113                         }
6114                 }
6115         }
6116
6117         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6118                 let best_block = *self.best_block.read().unwrap();
6119                 let per_peer_state = self.per_peer_state.read().unwrap();
6120                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6121                         .ok_or_else(|| {
6122                                 debug_assert!(false);
6123                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6124                         })?;
6125
6126                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6127                 let peer_state = &mut *peer_state_lock;
6128                 match peer_state.channel_by_id.entry(msg.channel_id) {
6129                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6130                                 match chan_phase_entry.get_mut() {
6131                                         ChannelPhase::Funded(ref mut chan) => {
6132                                                 let monitor = try_chan_phase_entry!(self,
6133                                                         chan.funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan_phase_entry);
6134                                                 if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6135                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6136                                                         Ok(())
6137                                                 } else {
6138                                                         try_chan_phase_entry!(self, Err(ChannelError::Close("Channel funding outpoint was a duplicate".to_owned())), chan_phase_entry)
6139                                                 }
6140                                         },
6141                                         _ => {
6142                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6143                                         },
6144                                 }
6145                         },
6146                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6147                 }
6148         }
6149
6150         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6151                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6152                 // closing a channel), so any changes are likely to be lost on restart!
6153                 let per_peer_state = self.per_peer_state.read().unwrap();
6154                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6155                         .ok_or_else(|| {
6156                                 debug_assert!(false);
6157                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6158                         })?;
6159                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6160                 let peer_state = &mut *peer_state_lock;
6161                 match peer_state.channel_by_id.entry(msg.channel_id) {
6162                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6163                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6164                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6165                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
6166                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6167                                                 log_trace!(self.logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6168                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6169                                                         node_id: counterparty_node_id.clone(),
6170                                                         msg: announcement_sigs,
6171                                                 });
6172                                         } else if chan.context.is_usable() {
6173                                                 // If we're sending an announcement_signatures, we'll send the (public)
6174                                                 // channel_update after sending a channel_announcement when we receive our
6175                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6176                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6177                                                 // announcement_signatures.
6178                                                 log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6179                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6180                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6181                                                                 node_id: counterparty_node_id.clone(),
6182                                                                 msg,
6183                                                         });
6184                                                 }
6185                                         }
6186
6187                                         {
6188                                                 let mut pending_events = self.pending_events.lock().unwrap();
6189                                                 emit_channel_ready_event!(pending_events, chan);
6190                                         }
6191
6192                                         Ok(())
6193                                 } else {
6194                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6195                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6196                                 }
6197                         },
6198                         hash_map::Entry::Vacant(_) => {
6199                                 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))
6200                         }
6201                 }
6202         }
6203
6204         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6205                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6206                 let mut finish_shutdown = None;
6207                 {
6208                         let per_peer_state = self.per_peer_state.read().unwrap();
6209                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6210                                 .ok_or_else(|| {
6211                                         debug_assert!(false);
6212                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6213                                 })?;
6214                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6215                         let peer_state = &mut *peer_state_lock;
6216                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6217                                 let phase = chan_phase_entry.get_mut();
6218                                 match phase {
6219                                         ChannelPhase::Funded(chan) => {
6220                                                 if !chan.received_shutdown() {
6221                                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
6222                                                                 msg.channel_id,
6223                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6224                                                 }
6225
6226                                                 let funding_txo_opt = chan.context.get_funding_txo();
6227                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6228                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6229                                                 dropped_htlcs = htlcs;
6230
6231                                                 if let Some(msg) = shutdown {
6232                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6233                                                         // here as we don't need the monitor update to complete until we send a
6234                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6235                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6236                                                                 node_id: *counterparty_node_id,
6237                                                                 msg,
6238                                                         });
6239                                                 }
6240                                                 // Update the monitor with the shutdown script if necessary.
6241                                                 if let Some(monitor_update) = monitor_update_opt {
6242                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6243                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6244                                                 }
6245                                         },
6246                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6247                                                 let context = phase.context_mut();
6248                                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6249                                                 self.issue_channel_close_events(&context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
6250                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6251                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false));
6252                                         },
6253                                 }
6254                         } else {
6255                                 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))
6256                         }
6257                 }
6258                 for htlc_source in dropped_htlcs.drain(..) {
6259                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6260                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6261                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6262                 }
6263                 if let Some(shutdown_res) = finish_shutdown {
6264                         self.finish_close_channel(shutdown_res);
6265                 }
6266
6267                 Ok(())
6268         }
6269
6270         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6271                 let mut shutdown_result = None;
6272                 let unbroadcasted_batch_funding_txid;
6273                 let per_peer_state = self.per_peer_state.read().unwrap();
6274                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6275                         .ok_or_else(|| {
6276                                 debug_assert!(false);
6277                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6278                         })?;
6279                 let (tx, chan_option) = {
6280                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6281                         let peer_state = &mut *peer_state_lock;
6282                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6283                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6284                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6285                                                 unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
6286                                                 let (closing_signed, tx) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6287                                                 if let Some(msg) = closing_signed {
6288                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6289                                                                 node_id: counterparty_node_id.clone(),
6290                                                                 msg,
6291                                                         });
6292                                                 }
6293                                                 if tx.is_some() {
6294                                                         // We're done with this channel, we've got a signed closing transaction and
6295                                                         // will send the closing_signed back to the remote peer upon return. This
6296                                                         // also implies there are no pending HTLCs left on the channel, so we can
6297                                                         // fully delete it from tracking (the channel monitor is still around to
6298                                                         // watch for old state broadcasts)!
6299                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)))
6300                                                 } else { (tx, None) }
6301                                         } else {
6302                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6303                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6304                                         }
6305                                 },
6306                                 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))
6307                         }
6308                 };
6309                 if let Some(broadcast_tx) = tx {
6310                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
6311                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6312                 }
6313                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6314                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6315                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6316                                 let peer_state = &mut *peer_state_lock;
6317                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6318                                         msg: update
6319                                 });
6320                         }
6321                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6322                         shutdown_result = Some((None, Vec::new(), unbroadcasted_batch_funding_txid));
6323                 }
6324                 mem::drop(per_peer_state);
6325                 if let Some(shutdown_result) = shutdown_result {
6326                         self.finish_close_channel(shutdown_result);
6327                 }
6328                 Ok(())
6329         }
6330
6331         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6332                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6333                 //determine the state of the payment based on our response/if we forward anything/the time
6334                 //we take to respond. We should take care to avoid allowing such an attack.
6335                 //
6336                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6337                 //us repeatedly garbled in different ways, and compare our error messages, which are
6338                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6339                 //but we should prevent it anyway.
6340
6341                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6342                 // closing a channel), so any changes are likely to be lost on restart!
6343
6344                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
6345                 let per_peer_state = self.per_peer_state.read().unwrap();
6346                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6347                         .ok_or_else(|| {
6348                                 debug_assert!(false);
6349                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6350                         })?;
6351                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6352                 let peer_state = &mut *peer_state_lock;
6353                 match peer_state.channel_by_id.entry(msg.channel_id) {
6354                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6355                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6356                                         let pending_forward_info = match decoded_hop_res {
6357                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6358                                                         self.construct_pending_htlc_status(msg, shared_secret, next_hop,
6359                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt),
6360                                                 Err(e) => PendingHTLCStatus::Fail(e)
6361                                         };
6362                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6363                                                 // If the update_add is completely bogus, the call will Err and we will close,
6364                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6365                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6366                                                 match pending_forward_info {
6367                                                         PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
6368                                                                 let reason = if (error_code & 0x1000) != 0 {
6369                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6370                                                                         HTLCFailReason::reason(real_code, error_data)
6371                                                                 } else {
6372                                                                         HTLCFailReason::from_failure_code(error_code)
6373                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6374                                                                 let msg = msgs::UpdateFailHTLC {
6375                                                                         channel_id: msg.channel_id,
6376                                                                         htlc_id: msg.htlc_id,
6377                                                                         reason
6378                                                                 };
6379                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6380                                                         },
6381                                                         _ => pending_forward_info
6382                                                 }
6383                                         };
6384                                         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);
6385                                 } else {
6386                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6387                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6388                                 }
6389                         },
6390                         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))
6391                 }
6392                 Ok(())
6393         }
6394
6395         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6396                 let funding_txo;
6397                 let (htlc_source, forwarded_htlc_value) = {
6398                         let per_peer_state = self.per_peer_state.read().unwrap();
6399                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6400                                 .ok_or_else(|| {
6401                                         debug_assert!(false);
6402                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6403                                 })?;
6404                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6405                         let peer_state = &mut *peer_state_lock;
6406                         match peer_state.channel_by_id.entry(msg.channel_id) {
6407                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6408                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6409                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6410                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6411                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6412                                                                 .or_insert_with(Vec::new)
6413                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6414                                                 }
6415                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6416                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6417                                                 // We do this instead in the `claim_funds_internal` by attaching a
6418                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6419                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6420                                                 // process the RAA as messages are processed from single peers serially.
6421                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6422                                                 res
6423                                         } else {
6424                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6425                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6426                                         }
6427                                 },
6428                                 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))
6429                         }
6430                 };
6431                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, Some(*counterparty_node_id), funding_txo);
6432                 Ok(())
6433         }
6434
6435         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6436                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6437                 // closing a channel), so any changes are likely to be lost on restart!
6438                 let per_peer_state = self.per_peer_state.read().unwrap();
6439                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6440                         .ok_or_else(|| {
6441                                 debug_assert!(false);
6442                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6443                         })?;
6444                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6445                 let peer_state = &mut *peer_state_lock;
6446                 match peer_state.channel_by_id.entry(msg.channel_id) {
6447                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6448                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6449                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6450                                 } else {
6451                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6452                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6453                                 }
6454                         },
6455                         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))
6456                 }
6457                 Ok(())
6458         }
6459
6460         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6461                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6462                 // closing a channel), so any changes are likely to be lost on restart!
6463                 let per_peer_state = self.per_peer_state.read().unwrap();
6464                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6465                         .ok_or_else(|| {
6466                                 debug_assert!(false);
6467                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6468                         })?;
6469                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6470                 let peer_state = &mut *peer_state_lock;
6471                 match peer_state.channel_by_id.entry(msg.channel_id) {
6472                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6473                                 if (msg.failure_code & 0x8000) == 0 {
6474                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6475                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6476                                 }
6477                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6478                                         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);
6479                                 } else {
6480                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6481                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6482                                 }
6483                                 Ok(())
6484                         },
6485                         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))
6486                 }
6487         }
6488
6489         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6490                 let per_peer_state = self.per_peer_state.read().unwrap();
6491                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6492                         .ok_or_else(|| {
6493                                 debug_assert!(false);
6494                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6495                         })?;
6496                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6497                 let peer_state = &mut *peer_state_lock;
6498                 match peer_state.channel_by_id.entry(msg.channel_id) {
6499                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6500                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6501                                         let funding_txo = chan.context.get_funding_txo();
6502                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &self.logger), chan_phase_entry);
6503                                         if let Some(monitor_update) = monitor_update_opt {
6504                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6505                                                         peer_state, per_peer_state, chan);
6506                                         }
6507                                         Ok(())
6508                                 } else {
6509                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6510                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6511                                 }
6512                         },
6513                         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))
6514                 }
6515         }
6516
6517         #[inline]
6518         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6519                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6520                         let mut push_forward_event = false;
6521                         let mut new_intercept_events = VecDeque::new();
6522                         let mut failed_intercept_forwards = Vec::new();
6523                         if !pending_forwards.is_empty() {
6524                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6525                                         let scid = match forward_info.routing {
6526                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6527                                                 PendingHTLCRouting::Receive { .. } => 0,
6528                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6529                                         };
6530                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6531                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6532
6533                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6534                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6535                                         match forward_htlcs.entry(scid) {
6536                                                 hash_map::Entry::Occupied(mut entry) => {
6537                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6538                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6539                                                 },
6540                                                 hash_map::Entry::Vacant(entry) => {
6541                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6542                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6543                                                         {
6544                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6545                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6546                                                                 match pending_intercepts.entry(intercept_id) {
6547                                                                         hash_map::Entry::Vacant(entry) => {
6548                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6549                                                                                         requested_next_hop_scid: scid,
6550                                                                                         payment_hash: forward_info.payment_hash,
6551                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6552                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6553                                                                                         intercept_id
6554                                                                                 }, None));
6555                                                                                 entry.insert(PendingAddHTLCInfo {
6556                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6557                                                                         },
6558                                                                         hash_map::Entry::Occupied(_) => {
6559                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6560                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6561                                                                                         short_channel_id: prev_short_channel_id,
6562                                                                                         user_channel_id: Some(prev_user_channel_id),
6563                                                                                         outpoint: prev_funding_outpoint,
6564                                                                                         htlc_id: prev_htlc_id,
6565                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6566                                                                                         phantom_shared_secret: None,
6567                                                                                 });
6568
6569                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6570                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6571                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6572                                                                                 ));
6573                                                                         }
6574                                                                 }
6575                                                         } else {
6576                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6577                                                                 // payments are being processed.
6578                                                                 if forward_htlcs_empty {
6579                                                                         push_forward_event = true;
6580                                                                 }
6581                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6582                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6583                                                         }
6584                                                 }
6585                                         }
6586                                 }
6587                         }
6588
6589                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6590                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6591                         }
6592
6593                         if !new_intercept_events.is_empty() {
6594                                 let mut events = self.pending_events.lock().unwrap();
6595                                 events.append(&mut new_intercept_events);
6596                         }
6597                         if push_forward_event { self.push_pending_forwards_ev() }
6598                 }
6599         }
6600
6601         fn push_pending_forwards_ev(&self) {
6602                 let mut pending_events = self.pending_events.lock().unwrap();
6603                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6604                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6605                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6606                 ).count();
6607                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6608                 // events is done in batches and they are not removed until we're done processing each
6609                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6610                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6611                 // payments will need an additional forwarding event before being claimed to make them look
6612                 // real by taking more time.
6613                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6614                         pending_events.push_back((Event::PendingHTLCsForwardable {
6615                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6616                         }, None));
6617                 }
6618         }
6619
6620         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6621         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6622         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6623         /// the [`ChannelMonitorUpdate`] in question.
6624         fn raa_monitor_updates_held(&self,
6625                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6626                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6627         ) -> bool {
6628                 actions_blocking_raa_monitor_updates
6629                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6630                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6631                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6632                                 channel_funding_outpoint,
6633                                 counterparty_node_id,
6634                         })
6635                 })
6636         }
6637
6638         #[cfg(any(test, feature = "_test_utils"))]
6639         pub(crate) fn test_raa_monitor_updates_held(&self,
6640                 counterparty_node_id: PublicKey, channel_id: ChannelId
6641         ) -> bool {
6642                 let per_peer_state = self.per_peer_state.read().unwrap();
6643                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6644                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6645                         let peer_state = &mut *peer_state_lck;
6646
6647                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
6648                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6649                                         chan.context().get_funding_txo().unwrap(), counterparty_node_id);
6650                         }
6651                 }
6652                 false
6653         }
6654
6655         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6656                 let htlcs_to_fail = {
6657                         let per_peer_state = self.per_peer_state.read().unwrap();
6658                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6659                                 .ok_or_else(|| {
6660                                         debug_assert!(false);
6661                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6662                                 }).map(|mtx| mtx.lock().unwrap())?;
6663                         let peer_state = &mut *peer_state_lock;
6664                         match peer_state.channel_by_id.entry(msg.channel_id) {
6665                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6666                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6667                                                 let funding_txo_opt = chan.context.get_funding_txo();
6668                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6669                                                         self.raa_monitor_updates_held(
6670                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6671                                                                 *counterparty_node_id)
6672                                                 } else { false };
6673                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
6674                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &self.logger, mon_update_blocked), chan_phase_entry);
6675                                                 if let Some(monitor_update) = monitor_update_opt {
6676                                                         let funding_txo = funding_txo_opt
6677                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
6678                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
6679                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6680                                                 }
6681                                                 htlcs_to_fail
6682                                         } else {
6683                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6684                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
6685                                         }
6686                                 },
6687                                 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))
6688                         }
6689                 };
6690                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6691                 Ok(())
6692         }
6693
6694         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6695                 let per_peer_state = self.per_peer_state.read().unwrap();
6696                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6697                         .ok_or_else(|| {
6698                                 debug_assert!(false);
6699                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6700                         })?;
6701                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6702                 let peer_state = &mut *peer_state_lock;
6703                 match peer_state.channel_by_id.entry(msg.channel_id) {
6704                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6705                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6706                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &self.logger), chan_phase_entry);
6707                                 } else {
6708                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6709                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
6710                                 }
6711                         },
6712                         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))
6713                 }
6714                 Ok(())
6715         }
6716
6717         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6718                 let per_peer_state = self.per_peer_state.read().unwrap();
6719                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6720                         .ok_or_else(|| {
6721                                 debug_assert!(false);
6722                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6723                         })?;
6724                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6725                 let peer_state = &mut *peer_state_lock;
6726                 match peer_state.channel_by_id.entry(msg.channel_id) {
6727                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6728                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6729                                         if !chan.context.is_usable() {
6730                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6731                                         }
6732
6733                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6734                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6735                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
6736                                                         msg, &self.default_configuration
6737                                                 ), chan_phase_entry),
6738                                                 // Note that announcement_signatures fails if the channel cannot be announced,
6739                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
6740                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
6741                                         });
6742                                 } else {
6743                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6744                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
6745                                 }
6746                         },
6747                         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))
6748                 }
6749                 Ok(())
6750         }
6751
6752         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
6753         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6754                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6755                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6756                         None => {
6757                                 // It's not a local channel
6758                                 return Ok(NotifyOption::SkipPersistNoEvents)
6759                         }
6760                 };
6761                 let per_peer_state = self.per_peer_state.read().unwrap();
6762                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6763                 if peer_state_mutex_opt.is_none() {
6764                         return Ok(NotifyOption::SkipPersistNoEvents)
6765                 }
6766                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6767                 let peer_state = &mut *peer_state_lock;
6768                 match peer_state.channel_by_id.entry(chan_id) {
6769                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6770                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6771                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
6772                                                 if chan.context.should_announce() {
6773                                                         // If the announcement is about a channel of ours which is public, some
6774                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
6775                                                         // a scary-looking error message and return Ok instead.
6776                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6777                                                 }
6778                                                 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));
6779                                         }
6780                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
6781                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
6782                                         if were_node_one == msg_from_node_one {
6783                                                 return Ok(NotifyOption::SkipPersistNoEvents);
6784                                         } else {
6785                                                 log_debug!(self.logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
6786                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
6787                                                 // If nothing changed after applying their update, we don't need to bother
6788                                                 // persisting.
6789                                                 if !did_change {
6790                                                         return Ok(NotifyOption::SkipPersistNoEvents);
6791                                                 }
6792                                         }
6793                                 } else {
6794                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6795                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
6796                                 }
6797                         },
6798                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
6799                 }
6800                 Ok(NotifyOption::DoPersist)
6801         }
6802
6803         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
6804                 let htlc_forwards;
6805                 let need_lnd_workaround = {
6806                         let per_peer_state = self.per_peer_state.read().unwrap();
6807
6808                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6809                                 .ok_or_else(|| {
6810                                         debug_assert!(false);
6811                                         MsgHandleErrInternal::send_err_msg_no_close(
6812                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6813                                                 msg.channel_id
6814                                         )
6815                                 })?;
6816                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6817                         let peer_state = &mut *peer_state_lock;
6818                         match peer_state.channel_by_id.entry(msg.channel_id) {
6819                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6820                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6821                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
6822                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
6823                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
6824                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6825                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
6826                                                         msg, &self.logger, &self.node_signer, self.chain_hash,
6827                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
6828                                                 let mut channel_update = None;
6829                                                 if let Some(msg) = responses.shutdown_msg {
6830                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6831                                                                 node_id: counterparty_node_id.clone(),
6832                                                                 msg,
6833                                                         });
6834                                                 } else if chan.context.is_usable() {
6835                                                         // If the channel is in a usable state (ie the channel is not being shut
6836                                                         // down), send a unicast channel_update to our counterparty to make sure
6837                                                         // they have the latest channel parameters.
6838                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6839                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
6840                                                                         node_id: chan.context.get_counterparty_node_id(),
6841                                                                         msg,
6842                                                                 });
6843                                                         }
6844                                                 }
6845                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
6846                                                 htlc_forwards = self.handle_channel_resumption(
6847                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
6848                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
6849                                                 if let Some(upd) = channel_update {
6850                                                         peer_state.pending_msg_events.push(upd);
6851                                                 }
6852                                                 need_lnd_workaround
6853                                         } else {
6854                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6855                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
6856                                         }
6857                                 },
6858                                 hash_map::Entry::Vacant(_) => {
6859                                         log_debug!(self.logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
6860                                                 log_bytes!(msg.channel_id.0));
6861                                         // Unfortunately, lnd doesn't force close on errors
6862                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
6863                                         // One of the few ways to get an lnd counterparty to force close is by
6864                                         // replicating what they do when restoring static channel backups (SCBs). They
6865                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
6866                                         // invalid `your_last_per_commitment_secret`.
6867                                         //
6868                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
6869                                         // can assume it's likely the channel closed from our point of view, but it
6870                                         // remains open on the counterparty's side. By sending this bogus
6871                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
6872                                         // force close broadcasting their latest state. If the closing transaction from
6873                                         // our point of view remains unconfirmed, it'll enter a race with the
6874                                         // counterparty's to-be-broadcast latest commitment transaction.
6875                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
6876                                                 node_id: *counterparty_node_id,
6877                                                 msg: msgs::ChannelReestablish {
6878                                                         channel_id: msg.channel_id,
6879                                                         next_local_commitment_number: 0,
6880                                                         next_remote_commitment_number: 0,
6881                                                         your_last_per_commitment_secret: [1u8; 32],
6882                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
6883                                                         next_funding_txid: None,
6884                                                 },
6885                                         });
6886                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6887                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
6888                                                         counterparty_node_id), msg.channel_id)
6889                                         )
6890                                 }
6891                         }
6892                 };
6893
6894                 let mut persist = NotifyOption::SkipPersistHandleEvents;
6895                 if let Some(forwards) = htlc_forwards {
6896                         self.forward_htlcs(&mut [forwards][..]);
6897                         persist = NotifyOption::DoPersist;
6898                 }
6899
6900                 if let Some(channel_ready_msg) = need_lnd_workaround {
6901                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
6902                 }
6903                 Ok(persist)
6904         }
6905
6906         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
6907         fn process_pending_monitor_events(&self) -> bool {
6908                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
6909
6910                 let mut failed_channels = Vec::new();
6911                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
6912                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
6913                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
6914                         for monitor_event in monitor_events.drain(..) {
6915                                 match monitor_event {
6916                                         MonitorEvent::HTLCEvent(htlc_update) => {
6917                                                 if let Some(preimage) = htlc_update.payment_preimage {
6918                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", preimage);
6919                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, counterparty_node_id, funding_outpoint);
6920                                                 } else {
6921                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
6922                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
6923                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6924                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
6925                                                 }
6926                                         },
6927                                         MonitorEvent::HolderForceClosed(funding_outpoint) => {
6928                                                 let counterparty_node_id_opt = match counterparty_node_id {
6929                                                         Some(cp_id) => Some(cp_id),
6930                                                         None => {
6931                                                                 // TODO: Once we can rely on the counterparty_node_id from the
6932                                                                 // monitor event, this and the id_to_peer map should be removed.
6933                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
6934                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
6935                                                         }
6936                                                 };
6937                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
6938                                                         let per_peer_state = self.per_peer_state.read().unwrap();
6939                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
6940                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6941                                                                 let peer_state = &mut *peer_state_lock;
6942                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6943                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
6944                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
6945                                                                                 failed_channels.push(chan.context.force_shutdown(false));
6946                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6947                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6948                                                                                                 msg: update
6949                                                                                         });
6950                                                                                 }
6951                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::HolderForceClosed);
6952                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
6953                                                                                         node_id: chan.context.get_counterparty_node_id(),
6954                                                                                         action: msgs::ErrorAction::DisconnectPeer {
6955                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
6956                                                                                         },
6957                                                                                 });
6958                                                                         }
6959                                                                 }
6960                                                         }
6961                                                 }
6962                                         },
6963                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
6964                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
6965                                         },
6966                                 }
6967                         }
6968                 }
6969
6970                 for failure in failed_channels.drain(..) {
6971                         self.finish_close_channel(failure);
6972                 }
6973
6974                 has_pending_monitor_events
6975         }
6976
6977         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
6978         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
6979         /// update events as a separate process method here.
6980         #[cfg(fuzzing)]
6981         pub fn process_monitor_events(&self) {
6982                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6983                 self.process_pending_monitor_events();
6984         }
6985
6986         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
6987         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
6988         /// update was applied.
6989         fn check_free_holding_cells(&self) -> bool {
6990                 let mut has_monitor_update = false;
6991                 let mut failed_htlcs = Vec::new();
6992
6993                 // Walk our list of channels and find any that need to update. Note that when we do find an
6994                 // update, if it includes actions that must be taken afterwards, we have to drop the
6995                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
6996                 // manage to go through all our peers without finding a single channel to update.
6997                 'peer_loop: loop {
6998                         let per_peer_state = self.per_peer_state.read().unwrap();
6999                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7000                                 'chan_loop: loop {
7001                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7002                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7003                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7004                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7005                                         ) {
7006                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7007                                                 let funding_txo = chan.context.get_funding_txo();
7008                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7009                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
7010                                                 if !holding_cell_failed_htlcs.is_empty() {
7011                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7012                                                 }
7013                                                 if let Some(monitor_update) = monitor_opt {
7014                                                         has_monitor_update = true;
7015
7016                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7017                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7018                                                         continue 'peer_loop;
7019                                                 }
7020                                         }
7021                                         break 'chan_loop;
7022                                 }
7023                         }
7024                         break 'peer_loop;
7025                 }
7026
7027                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7028                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7029                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7030                 }
7031
7032                 has_update
7033         }
7034
7035         /// Check whether any channels have finished removing all pending updates after a shutdown
7036         /// exchange and can now send a closing_signed.
7037         /// Returns whether any closing_signed messages were generated.
7038         fn maybe_generate_initial_closing_signed(&self) -> bool {
7039                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7040                 let mut has_update = false;
7041                 let mut shutdown_results = Vec::new();
7042                 {
7043                         let per_peer_state = self.per_peer_state.read().unwrap();
7044
7045                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7046                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7047                                 let peer_state = &mut *peer_state_lock;
7048                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7049                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7050                                         match phase {
7051                                                 ChannelPhase::Funded(chan) => {
7052                                                         let unbroadcasted_batch_funding_txid = chan.context.unbroadcasted_batch_funding_txid();
7053                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
7054                                                                 Ok((msg_opt, tx_opt)) => {
7055                                                                         if let Some(msg) = msg_opt {
7056                                                                                 has_update = true;
7057                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7058                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7059                                                                                 });
7060                                                                         }
7061                                                                         if let Some(tx) = tx_opt {
7062                                                                                 // We're done with this channel. We got a closing_signed and sent back
7063                                                                                 // a closing_signed with a closing transaction to broadcast.
7064                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7065                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7066                                                                                                 msg: update
7067                                                                                         });
7068                                                                                 }
7069
7070                                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
7071
7072                                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
7073                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7074                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7075                                                                                 shutdown_results.push((None, Vec::new(), unbroadcasted_batch_funding_txid));
7076                                                                                 false
7077                                                                         } else { true }
7078                                                                 },
7079                                                                 Err(e) => {
7080                                                                         has_update = true;
7081                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7082                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7083                                                                         !close_channel
7084                                                                 }
7085                                                         }
7086                                                 },
7087                                                 _ => true, // Retain unfunded channels if present.
7088                                         }
7089                                 });
7090                         }
7091                 }
7092
7093                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7094                         let _ = handle_error!(self, err, counterparty_node_id);
7095                 }
7096
7097                 for shutdown_result in shutdown_results.drain(..) {
7098                         self.finish_close_channel(shutdown_result);
7099                 }
7100
7101                 has_update
7102         }
7103
7104         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7105         /// pushing the channel monitor update (if any) to the background events queue and removing the
7106         /// Channel object.
7107         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7108                 for mut failure in failed_channels.drain(..) {
7109                         // Either a commitment transactions has been confirmed on-chain or
7110                         // Channel::block_disconnected detected that the funding transaction has been
7111                         // reorganized out of the main chain.
7112                         // We cannot broadcast our latest local state via monitor update (as
7113                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7114                         // so we track the update internally and handle it when the user next calls
7115                         // timer_tick_occurred, guaranteeing we're running normally.
7116                         if let Some((counterparty_node_id, funding_txo, update)) = failure.0.take() {
7117                                 assert_eq!(update.updates.len(), 1);
7118                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7119                                         assert!(should_broadcast);
7120                                 } else { unreachable!(); }
7121                                 self.pending_background_events.lock().unwrap().push(
7122                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7123                                                 counterparty_node_id, funding_txo, update
7124                                         });
7125                         }
7126                         self.finish_close_channel(failure);
7127                 }
7128         }
7129
7130         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7131         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7132         /// not have an expiration unless otherwise set on the builder.
7133         ///
7134         /// Uses a one-hop [`BlindedPath`] for the offer with [`ChannelManager::get_our_node_id`] as the
7135         /// introduction node and a derived signing pubkey for recipient privacy. As such, currently,
7136         /// the node must be announced. Otherwise, there is no way to find a path to the introduction
7137         /// node in order to send the [`InvoiceRequest`].
7138         ///
7139         /// [`Offer`]: crate::offers::offer::Offer
7140         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7141         pub fn create_offer_builder(
7142                 &self, description: String
7143         ) -> OfferBuilder<DerivedMetadata, secp256k1::All> {
7144                 let node_id = self.get_our_node_id();
7145                 let expanded_key = &self.inbound_payment_key;
7146                 let entropy = &*self.entropy_source;
7147                 let secp_ctx = &self.secp_ctx;
7148                 let path = self.create_one_hop_blinded_path();
7149
7150                 OfferBuilder::deriving_signing_pubkey(description, node_id, expanded_key, entropy, secp_ctx)
7151                         .chain_hash(self.chain_hash)
7152                         .path(path)
7153         }
7154
7155         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7156         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund. The builder will
7157         /// have the provided expiration set. Any changes to the expiration on the returned builder will
7158         /// not be honored by [`ChannelManager`].
7159         ///
7160         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7161         ///
7162         /// Uses a one-hop [`BlindedPath`] for the refund with [`ChannelManager::get_our_node_id`] as
7163         /// the introduction node and a derived payer id for sender privacy. As such, currently, the
7164         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7165         /// in order to send the [`Bolt12Invoice`].
7166         ///
7167         /// [`Refund`]: crate::offers::refund::Refund
7168         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7169         pub fn create_refund_builder(
7170                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7171                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7172         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7173                 let node_id = self.get_our_node_id();
7174                 let expanded_key = &self.inbound_payment_key;
7175                 let entropy = &*self.entropy_source;
7176                 let secp_ctx = &self.secp_ctx;
7177                 let path = self.create_one_hop_blinded_path();
7178
7179                 let builder = RefundBuilder::deriving_payer_id(
7180                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7181                 )?
7182                         .chain_hash(self.chain_hash)
7183                         .absolute_expiry(absolute_expiry)
7184                         .path(path);
7185
7186                 self.pending_outbound_payments
7187                         .add_new_awaiting_invoice(
7188                                 payment_id, absolute_expiry, retry_strategy, max_total_routing_fee_msat,
7189                         )
7190                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7191
7192                 Ok(builder)
7193         }
7194
7195         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7196         /// to pay us.
7197         ///
7198         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7199         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7200         ///
7201         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7202         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7203         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7204         /// passed directly to [`claim_funds`].
7205         ///
7206         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7207         ///
7208         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7209         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7210         ///
7211         /// # Note
7212         ///
7213         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7214         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7215         ///
7216         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7217         ///
7218         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7219         /// on versions of LDK prior to 0.0.114.
7220         ///
7221         /// [`claim_funds`]: Self::claim_funds
7222         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7223         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7224         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7225         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7226         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7227         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7228                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7229                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7230                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7231                         min_final_cltv_expiry_delta)
7232         }
7233
7234         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7235         /// stored external to LDK.
7236         ///
7237         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7238         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7239         /// the `min_value_msat` provided here, if one is provided.
7240         ///
7241         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7242         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7243         /// payments.
7244         ///
7245         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7246         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7247         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7248         /// sender "proof-of-payment" unless they have paid the required amount.
7249         ///
7250         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7251         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7252         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7253         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7254         /// invoices when no timeout is set.
7255         ///
7256         /// Note that we use block header time to time-out pending inbound payments (with some margin
7257         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7258         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7259         /// If you need exact expiry semantics, you should enforce them upon receipt of
7260         /// [`PaymentClaimable`].
7261         ///
7262         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7263         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7264         ///
7265         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7266         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7267         ///
7268         /// # Note
7269         ///
7270         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7271         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7272         ///
7273         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7274         ///
7275         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7276         /// on versions of LDK prior to 0.0.114.
7277         ///
7278         /// [`create_inbound_payment`]: Self::create_inbound_payment
7279         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7280         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7281                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7282                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7283                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7284                         min_final_cltv_expiry)
7285         }
7286
7287         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7288         /// previously returned from [`create_inbound_payment`].
7289         ///
7290         /// [`create_inbound_payment`]: Self::create_inbound_payment
7291         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7292                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7293         }
7294
7295         /// Creates a one-hop blinded path with [`ChannelManager::get_our_node_id`] as the introduction
7296         /// node.
7297         fn create_one_hop_blinded_path(&self) -> BlindedPath {
7298                 let entropy_source = self.entropy_source.deref();
7299                 let secp_ctx = &self.secp_ctx;
7300                 BlindedPath::one_hop_for_message(self.get_our_node_id(), entropy_source, secp_ctx).unwrap()
7301         }
7302
7303         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
7304         /// are used when constructing the phantom invoice's route hints.
7305         ///
7306         /// [phantom node payments]: crate::sign::PhantomKeysManager
7307         pub fn get_phantom_scid(&self) -> u64 {
7308                 let best_block_height = self.best_block.read().unwrap().height();
7309                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7310                 loop {
7311                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7312                         // Ensure the generated scid doesn't conflict with a real channel.
7313                         match short_to_chan_info.get(&scid_candidate) {
7314                                 Some(_) => continue,
7315                                 None => return scid_candidate
7316                         }
7317                 }
7318         }
7319
7320         /// Gets route hints for use in receiving [phantom node payments].
7321         ///
7322         /// [phantom node payments]: crate::sign::PhantomKeysManager
7323         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
7324                 PhantomRouteHints {
7325                         channels: self.list_usable_channels(),
7326                         phantom_scid: self.get_phantom_scid(),
7327                         real_node_pubkey: self.get_our_node_id(),
7328                 }
7329         }
7330
7331         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
7332         /// used when constructing the route hints for HTLCs intended to be intercepted. See
7333         /// [`ChannelManager::forward_intercepted_htlc`].
7334         ///
7335         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
7336         /// times to get a unique scid.
7337         pub fn get_intercept_scid(&self) -> u64 {
7338                 let best_block_height = self.best_block.read().unwrap().height();
7339                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
7340                 loop {
7341                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7342                         // Ensure the generated scid doesn't conflict with a real channel.
7343                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
7344                         return scid_candidate
7345                 }
7346         }
7347
7348         /// Gets inflight HTLC information by processing pending outbound payments that are in
7349         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
7350         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
7351                 let mut inflight_htlcs = InFlightHtlcs::new();
7352
7353                 let per_peer_state = self.per_peer_state.read().unwrap();
7354                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7355                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7356                         let peer_state = &mut *peer_state_lock;
7357                         for chan in peer_state.channel_by_id.values().filter_map(
7358                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7359                         ) {
7360                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
7361                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
7362                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
7363                                         }
7364                                 }
7365                         }
7366                 }
7367
7368                 inflight_htlcs
7369         }
7370
7371         #[cfg(any(test, feature = "_test_utils"))]
7372         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
7373                 let events = core::cell::RefCell::new(Vec::new());
7374                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
7375                 self.process_pending_events(&event_handler);
7376                 events.into_inner()
7377         }
7378
7379         #[cfg(feature = "_test_utils")]
7380         pub fn push_pending_event(&self, event: events::Event) {
7381                 let mut events = self.pending_events.lock().unwrap();
7382                 events.push_back((event, None));
7383         }
7384
7385         #[cfg(test)]
7386         pub fn pop_pending_event(&self) -> Option<events::Event> {
7387                 let mut events = self.pending_events.lock().unwrap();
7388                 events.pop_front().map(|(e, _)| e)
7389         }
7390
7391         #[cfg(test)]
7392         pub fn has_pending_payments(&self) -> bool {
7393                 self.pending_outbound_payments.has_pending_payments()
7394         }
7395
7396         #[cfg(test)]
7397         pub fn clear_pending_payments(&self) {
7398                 self.pending_outbound_payments.clear_pending_payments()
7399         }
7400
7401         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
7402         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
7403         /// operation. It will double-check that nothing *else* is also blocking the same channel from
7404         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
7405         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
7406                 loop {
7407                         let per_peer_state = self.per_peer_state.read().unwrap();
7408                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7409                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7410                                 let peer_state = &mut *peer_state_lck;
7411
7412                                 if let Some(blocker) = completed_blocker.take() {
7413                                         // Only do this on the first iteration of the loop.
7414                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
7415                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
7416                                         {
7417                                                 blockers.retain(|iter| iter != &blocker);
7418                                         }
7419                                 }
7420
7421                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7422                                         channel_funding_outpoint, counterparty_node_id) {
7423                                         // Check that, while holding the peer lock, we don't have anything else
7424                                         // blocking monitor updates for this channel. If we do, release the monitor
7425                                         // update(s) when those blockers complete.
7426                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
7427                                                 &channel_funding_outpoint.to_channel_id());
7428                                         break;
7429                                 }
7430
7431                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
7432                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7433                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
7434                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
7435                                                         log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
7436                                                                 channel_funding_outpoint.to_channel_id());
7437                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
7438                                                                 peer_state_lck, peer_state, per_peer_state, chan);
7439                                                         if further_update_exists {
7440                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
7441                                                                 // top of the loop.
7442                                                                 continue;
7443                                                         }
7444                                                 } else {
7445                                                         log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
7446                                                                 channel_funding_outpoint.to_channel_id());
7447                                                 }
7448                                         }
7449                                 }
7450                         } else {
7451                                 log_debug!(self.logger,
7452                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
7453                                         log_pubkey!(counterparty_node_id));
7454                         }
7455                         break;
7456                 }
7457         }
7458
7459         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
7460                 for action in actions {
7461                         match action {
7462                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7463                                         channel_funding_outpoint, counterparty_node_id
7464                                 } => {
7465                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
7466                                 }
7467                         }
7468                 }
7469         }
7470
7471         /// Processes any events asynchronously in the order they were generated since the last call
7472         /// using the given event handler.
7473         ///
7474         /// See the trait-level documentation of [`EventsProvider`] for requirements.
7475         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
7476                 &self, handler: H
7477         ) {
7478                 let mut ev;
7479                 process_events_body!(self, ev, { handler(ev).await });
7480         }
7481 }
7482
7483 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>
7484 where
7485         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7486         T::Target: BroadcasterInterface,
7487         ES::Target: EntropySource,
7488         NS::Target: NodeSigner,
7489         SP::Target: SignerProvider,
7490         F::Target: FeeEstimator,
7491         R::Target: Router,
7492         L::Target: Logger,
7493 {
7494         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
7495         /// The returned array will contain `MessageSendEvent`s for different peers if
7496         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
7497         /// is always placed next to each other.
7498         ///
7499         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
7500         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
7501         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
7502         /// will randomly be placed first or last in the returned array.
7503         ///
7504         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
7505         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
7506         /// the `MessageSendEvent`s to the specific peer they were generated under.
7507         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
7508                 let events = RefCell::new(Vec::new());
7509                 PersistenceNotifierGuard::optionally_notify(self, || {
7510                         let mut result = NotifyOption::SkipPersistNoEvents;
7511
7512                         // TODO: This behavior should be documented. It's unintuitive that we query
7513                         // ChannelMonitors when clearing other events.
7514                         if self.process_pending_monitor_events() {
7515                                 result = NotifyOption::DoPersist;
7516                         }
7517
7518                         if self.check_free_holding_cells() {
7519                                 result = NotifyOption::DoPersist;
7520                         }
7521                         if self.maybe_generate_initial_closing_signed() {
7522                                 result = NotifyOption::DoPersist;
7523                         }
7524
7525                         let mut pending_events = Vec::new();
7526                         let per_peer_state = self.per_peer_state.read().unwrap();
7527                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7528                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7529                                 let peer_state = &mut *peer_state_lock;
7530                                 if peer_state.pending_msg_events.len() > 0 {
7531                                         pending_events.append(&mut peer_state.pending_msg_events);
7532                                 }
7533                         }
7534
7535                         if !pending_events.is_empty() {
7536                                 events.replace(pending_events);
7537                         }
7538
7539                         result
7540                 });
7541                 events.into_inner()
7542         }
7543 }
7544
7545 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>
7546 where
7547         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7548         T::Target: BroadcasterInterface,
7549         ES::Target: EntropySource,
7550         NS::Target: NodeSigner,
7551         SP::Target: SignerProvider,
7552         F::Target: FeeEstimator,
7553         R::Target: Router,
7554         L::Target: Logger,
7555 {
7556         /// Processes events that must be periodically handled.
7557         ///
7558         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
7559         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
7560         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
7561                 let mut ev;
7562                 process_events_body!(self, ev, handler.handle_event(ev));
7563         }
7564 }
7565
7566 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>
7567 where
7568         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7569         T::Target: BroadcasterInterface,
7570         ES::Target: EntropySource,
7571         NS::Target: NodeSigner,
7572         SP::Target: SignerProvider,
7573         F::Target: FeeEstimator,
7574         R::Target: Router,
7575         L::Target: Logger,
7576 {
7577         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7578                 {
7579                         let best_block = self.best_block.read().unwrap();
7580                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
7581                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
7582                         assert_eq!(best_block.height(), height - 1,
7583                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
7584                 }
7585
7586                 self.transactions_confirmed(header, txdata, height);
7587                 self.best_block_updated(header, height);
7588         }
7589
7590         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
7591                 let _persistence_guard =
7592                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7593                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7594                 let new_height = height - 1;
7595                 {
7596                         let mut best_block = self.best_block.write().unwrap();
7597                         assert_eq!(best_block.block_hash(), header.block_hash(),
7598                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
7599                         assert_eq!(best_block.height(), height,
7600                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
7601                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
7602                 }
7603
7604                 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));
7605         }
7606 }
7607
7608 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>
7609 where
7610         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7611         T::Target: BroadcasterInterface,
7612         ES::Target: EntropySource,
7613         NS::Target: NodeSigner,
7614         SP::Target: SignerProvider,
7615         F::Target: FeeEstimator,
7616         R::Target: Router,
7617         L::Target: Logger,
7618 {
7619         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
7620                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7621                 // during initialization prior to the chain_monitor being fully configured in some cases.
7622                 // See the docs for `ChannelManagerReadArgs` for more.
7623
7624                 let block_hash = header.block_hash();
7625                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
7626
7627                 let _persistence_guard =
7628                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7629                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7630                 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)
7631                         .map(|(a, b)| (a, Vec::new(), b)));
7632
7633                 let last_best_block_height = self.best_block.read().unwrap().height();
7634                 if height < last_best_block_height {
7635                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
7636                         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));
7637                 }
7638         }
7639
7640         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
7641                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7642                 // during initialization prior to the chain_monitor being fully configured in some cases.
7643                 // See the docs for `ChannelManagerReadArgs` for more.
7644
7645                 let block_hash = header.block_hash();
7646                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
7647
7648                 let _persistence_guard =
7649                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7650                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7651                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
7652
7653                 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));
7654
7655                 macro_rules! max_time {
7656                         ($timestamp: expr) => {
7657                                 loop {
7658                                         // Update $timestamp to be the max of its current value and the block
7659                                         // timestamp. This should keep us close to the current time without relying on
7660                                         // having an explicit local time source.
7661                                         // Just in case we end up in a race, we loop until we either successfully
7662                                         // update $timestamp or decide we don't need to.
7663                                         let old_serial = $timestamp.load(Ordering::Acquire);
7664                                         if old_serial >= header.time as usize { break; }
7665                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
7666                                                 break;
7667                                         }
7668                                 }
7669                         }
7670                 }
7671                 max_time!(self.highest_seen_timestamp);
7672                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
7673                 payment_secrets.retain(|_, inbound_payment| {
7674                         inbound_payment.expiry_time > header.time as u64
7675                 });
7676         }
7677
7678         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
7679                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
7680                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
7681                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7682                         let peer_state = &mut *peer_state_lock;
7683                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
7684                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
7685                                         res.push((funding_txo.txid, Some(block_hash)));
7686                                 }
7687                         }
7688                 }
7689                 res
7690         }
7691
7692         fn transaction_unconfirmed(&self, txid: &Txid) {
7693                 let _persistence_guard =
7694                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
7695                                 self, || -> NotifyOption { NotifyOption::DoPersist });
7696                 self.do_chain_event(None, |channel| {
7697                         if let Some(funding_txo) = channel.context.get_funding_txo() {
7698                                 if funding_txo.txid == *txid {
7699                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
7700                                 } else { Ok((None, Vec::new(), None)) }
7701                         } else { Ok((None, Vec::new(), None)) }
7702                 });
7703         }
7704 }
7705
7706 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>
7707 where
7708         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7709         T::Target: BroadcasterInterface,
7710         ES::Target: EntropySource,
7711         NS::Target: NodeSigner,
7712         SP::Target: SignerProvider,
7713         F::Target: FeeEstimator,
7714         R::Target: Router,
7715         L::Target: Logger,
7716 {
7717         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
7718         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
7719         /// the function.
7720         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
7721                         (&self, height_opt: Option<u32>, f: FN) {
7722                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7723                 // during initialization prior to the chain_monitor being fully configured in some cases.
7724                 // See the docs for `ChannelManagerReadArgs` for more.
7725
7726                 let mut failed_channels = Vec::new();
7727                 let mut timed_out_htlcs = Vec::new();
7728                 {
7729                         let per_peer_state = self.per_peer_state.read().unwrap();
7730                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7731                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7732                                 let peer_state = &mut *peer_state_lock;
7733                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7734                                 peer_state.channel_by_id.retain(|_, phase| {
7735                                         match phase {
7736                                                 // Retain unfunded channels.
7737                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
7738                                                 ChannelPhase::Funded(channel) => {
7739                                                         let res = f(channel);
7740                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
7741                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
7742                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
7743                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
7744                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
7745                                                                 }
7746                                                                 if let Some(channel_ready) = channel_ready_opt {
7747                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
7748                                                                         if channel.context.is_usable() {
7749                                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
7750                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
7751                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
7752                                                                                                 node_id: channel.context.get_counterparty_node_id(),
7753                                                                                                 msg,
7754                                                                                         });
7755                                                                                 }
7756                                                                         } else {
7757                                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
7758                                                                         }
7759                                                                 }
7760
7761                                                                 {
7762                                                                         let mut pending_events = self.pending_events.lock().unwrap();
7763                                                                         emit_channel_ready_event!(pending_events, channel);
7764                                                                 }
7765
7766                                                                 if let Some(announcement_sigs) = announcement_sigs {
7767                                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
7768                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
7769                                                                                 node_id: channel.context.get_counterparty_node_id(),
7770                                                                                 msg: announcement_sigs,
7771                                                                         });
7772                                                                         if let Some(height) = height_opt {
7773                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
7774                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7775                                                                                                 msg: announcement,
7776                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7777                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7778                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
7779                                                                                         });
7780                                                                                 }
7781                                                                         }
7782                                                                 }
7783                                                                 if channel.is_our_channel_ready() {
7784                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
7785                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
7786                                                                                 // to the short_to_chan_info map here. Note that we check whether we
7787                                                                                 // can relay using the real SCID at relay-time (i.e.
7788                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
7789                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
7790                                                                                 // is always consistent.
7791                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
7792                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
7793                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
7794                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
7795                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
7796                                                                         }
7797                                                                 }
7798                                                         } else if let Err(reason) = res {
7799                                                                 update_maps_on_chan_removal!(self, &channel.context);
7800                                                                 // It looks like our counterparty went on-chain or funding transaction was
7801                                                                 // reorged out of the main chain. Close the channel.
7802                                                                 failed_channels.push(channel.context.force_shutdown(true));
7803                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
7804                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7805                                                                                 msg: update
7806                                                                         });
7807                                                                 }
7808                                                                 let reason_message = format!("{}", reason);
7809                                                                 self.issue_channel_close_events(&channel.context, reason);
7810                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7811                                                                         node_id: channel.context.get_counterparty_node_id(),
7812                                                                         action: msgs::ErrorAction::DisconnectPeer {
7813                                                                                 msg: Some(msgs::ErrorMessage {
7814                                                                                         channel_id: channel.context.channel_id(),
7815                                                                                         data: reason_message,
7816                                                                                 })
7817                                                                         },
7818                                                                 });
7819                                                                 return false;
7820                                                         }
7821                                                         true
7822                                                 }
7823                                         }
7824                                 });
7825                         }
7826                 }
7827
7828                 if let Some(height) = height_opt {
7829                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
7830                                 payment.htlcs.retain(|htlc| {
7831                                         // If height is approaching the number of blocks we think it takes us to get
7832                                         // our commitment transaction confirmed before the HTLC expires, plus the
7833                                         // number of blocks we generally consider it to take to do a commitment update,
7834                                         // just give up on it and fail the HTLC.
7835                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
7836                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
7837                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
7838
7839                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
7840                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
7841                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
7842                                                 false
7843                                         } else { true }
7844                                 });
7845                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
7846                         });
7847
7848                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
7849                         intercepted_htlcs.retain(|_, htlc| {
7850                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
7851                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
7852                                                 short_channel_id: htlc.prev_short_channel_id,
7853                                                 user_channel_id: Some(htlc.prev_user_channel_id),
7854                                                 htlc_id: htlc.prev_htlc_id,
7855                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
7856                                                 phantom_shared_secret: None,
7857                                                 outpoint: htlc.prev_funding_outpoint,
7858                                         });
7859
7860                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
7861                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
7862                                                 _ => unreachable!(),
7863                                         };
7864                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
7865                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
7866                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
7867                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
7868                                         false
7869                                 } else { true }
7870                         });
7871                 }
7872
7873                 self.handle_init_event_channel_failures(failed_channels);
7874
7875                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
7876                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
7877                 }
7878         }
7879
7880         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
7881         /// may have events that need processing.
7882         ///
7883         /// In order to check if this [`ChannelManager`] needs persisting, call
7884         /// [`Self::get_and_clear_needs_persistence`].
7885         ///
7886         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
7887         /// [`ChannelManager`] and should instead register actions to be taken later.
7888         pub fn get_event_or_persistence_needed_future(&self) -> Future {
7889                 self.event_persist_notifier.get_future()
7890         }
7891
7892         /// Returns true if this [`ChannelManager`] needs to be persisted.
7893         pub fn get_and_clear_needs_persistence(&self) -> bool {
7894                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
7895         }
7896
7897         #[cfg(any(test, feature = "_test_utils"))]
7898         pub fn get_event_or_persist_condvar_value(&self) -> bool {
7899                 self.event_persist_notifier.notify_pending()
7900         }
7901
7902         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
7903         /// [`chain::Confirm`] interfaces.
7904         pub fn current_best_block(&self) -> BestBlock {
7905                 self.best_block.read().unwrap().clone()
7906         }
7907
7908         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
7909         /// [`ChannelManager`].
7910         pub fn node_features(&self) -> NodeFeatures {
7911                 provided_node_features(&self.default_configuration)
7912         }
7913
7914         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
7915         /// [`ChannelManager`].
7916         ///
7917         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
7918         /// or not. Thus, this method is not public.
7919         #[cfg(any(feature = "_test_utils", test))]
7920         pub fn invoice_features(&self) -> Bolt11InvoiceFeatures {
7921                 provided_invoice_features(&self.default_configuration)
7922         }
7923
7924         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
7925         /// [`ChannelManager`].
7926         pub fn channel_features(&self) -> ChannelFeatures {
7927                 provided_channel_features(&self.default_configuration)
7928         }
7929
7930         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
7931         /// [`ChannelManager`].
7932         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
7933                 provided_channel_type_features(&self.default_configuration)
7934         }
7935
7936         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
7937         /// [`ChannelManager`].
7938         pub fn init_features(&self) -> InitFeatures {
7939                 provided_init_features(&self.default_configuration)
7940         }
7941 }
7942
7943 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7944         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
7945 where
7946         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7947         T::Target: BroadcasterInterface,
7948         ES::Target: EntropySource,
7949         NS::Target: NodeSigner,
7950         SP::Target: SignerProvider,
7951         F::Target: FeeEstimator,
7952         R::Target: Router,
7953         L::Target: Logger,
7954 {
7955         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
7956                 // Note that we never need to persist the updated ChannelManager for an inbound
7957                 // open_channel message - pre-funded channels are never written so there should be no
7958                 // change to the contents.
7959                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
7960                         let res = self.internal_open_channel(counterparty_node_id, msg);
7961                         let persist = match &res {
7962                                 Err(e) if e.closes_channel() => {
7963                                         debug_assert!(false, "We shouldn't close a new channel");
7964                                         NotifyOption::DoPersist
7965                                 },
7966                                 _ => NotifyOption::SkipPersistHandleEvents,
7967                         };
7968                         let _ = handle_error!(self, res, *counterparty_node_id);
7969                         persist
7970                 });
7971         }
7972
7973         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
7974                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7975                         "Dual-funded channels not supported".to_owned(),
7976                          msg.temporary_channel_id.clone())), *counterparty_node_id);
7977         }
7978
7979         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
7980                 // Note that we never need to persist the updated ChannelManager for an inbound
7981                 // accept_channel message - pre-funded channels are never written so there should be no
7982                 // change to the contents.
7983                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
7984                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
7985                         NotifyOption::SkipPersistHandleEvents
7986                 });
7987         }
7988
7989         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
7990                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7991                         "Dual-funded channels not supported".to_owned(),
7992                          msg.temporary_channel_id.clone())), *counterparty_node_id);
7993         }
7994
7995         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
7996                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7997                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
7998         }
7999
8000         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8001                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8002                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8003         }
8004
8005         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8006                 // Note that we never need to persist the updated ChannelManager for an inbound
8007                 // channel_ready message - while the channel's state will change, any channel_ready message
8008                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8009                 // will not force-close the channel on startup.
8010                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8011                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8012                         let persist = match &res {
8013                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8014                                 _ => NotifyOption::SkipPersistHandleEvents,
8015                         };
8016                         let _ = handle_error!(self, res, *counterparty_node_id);
8017                         persist
8018                 });
8019         }
8020
8021         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8022                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8023                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8024         }
8025
8026         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8027                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8028                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8029         }
8030
8031         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8032                 // Note that we never need to persist the updated ChannelManager for an inbound
8033                 // update_add_htlc message - the message itself doesn't change our channel state only the
8034                 // `commitment_signed` message afterwards will.
8035                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8036                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8037                         let persist = match &res {
8038                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8039                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8040                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8041                         };
8042                         let _ = handle_error!(self, res, *counterparty_node_id);
8043                         persist
8044                 });
8045         }
8046
8047         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8048                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8049                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8050         }
8051
8052         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8053                 // Note that we never need to persist the updated ChannelManager for an inbound
8054                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8055                 // `commitment_signed` message afterwards will.
8056                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8057                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8058                         let persist = match &res {
8059                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8060                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8061                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8062                         };
8063                         let _ = handle_error!(self, res, *counterparty_node_id);
8064                         persist
8065                 });
8066         }
8067
8068         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8069                 // Note that we never need to persist the updated ChannelManager for an inbound
8070                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8071                 // only the `commitment_signed` message afterwards will.
8072                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8073                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8074                         let persist = match &res {
8075                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8076                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8077                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8078                         };
8079                         let _ = handle_error!(self, res, *counterparty_node_id);
8080                         persist
8081                 });
8082         }
8083
8084         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8085                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8086                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8087         }
8088
8089         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8090                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8091                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8092         }
8093
8094         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8095                 // Note that we never need to persist the updated ChannelManager for an inbound
8096                 // update_fee message - the message itself doesn't change our channel state only the
8097                 // `commitment_signed` message afterwards will.
8098                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8099                         let res = self.internal_update_fee(counterparty_node_id, msg);
8100                         let persist = match &res {
8101                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8102                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8103                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8104                         };
8105                         let _ = handle_error!(self, res, *counterparty_node_id);
8106                         persist
8107                 });
8108         }
8109
8110         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8111                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8112                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8113         }
8114
8115         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8116                 PersistenceNotifierGuard::optionally_notify(self, || {
8117                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8118                                 persist
8119                         } else {
8120                                 NotifyOption::DoPersist
8121                         }
8122                 });
8123         }
8124
8125         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8126                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8127                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8128                         let persist = match &res {
8129                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8130                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8131                                 Ok(persist) => *persist,
8132                         };
8133                         let _ = handle_error!(self, res, *counterparty_node_id);
8134                         persist
8135                 });
8136         }
8137
8138         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8139                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8140                         self, || NotifyOption::SkipPersistHandleEvents);
8141                 let mut failed_channels = Vec::new();
8142                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8143                 let remove_peer = {
8144                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
8145                                 log_pubkey!(counterparty_node_id));
8146                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8147                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8148                                 let peer_state = &mut *peer_state_lock;
8149                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8150                                 peer_state.channel_by_id.retain(|_, phase| {
8151                                         let context = match phase {
8152                                                 ChannelPhase::Funded(chan) => {
8153                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger).is_ok() {
8154                                                                 // We only retain funded channels that are not shutdown.
8155                                                                 return true;
8156                                                         }
8157                                                         &mut chan.context
8158                                                 },
8159                                                 // Unfunded channels will always be removed.
8160                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8161                                                         &mut chan.context
8162                                                 },
8163                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8164                                                         &mut chan.context
8165                                                 },
8166                                         };
8167                                         // Clean up for removal.
8168                                         update_maps_on_chan_removal!(self, &context);
8169                                         self.issue_channel_close_events(&context, ClosureReason::DisconnectedPeer);
8170                                         failed_channels.push(context.force_shutdown(false));
8171                                         false
8172                                 });
8173                                 // Note that we don't bother generating any events for pre-accept channels -
8174                                 // they're not considered "channels" yet from the PoV of our events interface.
8175                                 peer_state.inbound_channel_request_by_id.clear();
8176                                 pending_msg_events.retain(|msg| {
8177                                         match msg {
8178                                                 // V1 Channel Establishment
8179                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8180                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8181                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8182                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8183                                                 // V2 Channel Establishment
8184                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8185                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8186                                                 // Common Channel Establishment
8187                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8188                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8189                                                 // Interactive Transaction Construction
8190                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8191                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8192                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8193                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8194                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8195                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8196                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8197                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8198                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8199                                                 // Channel Operations
8200                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8201                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8202                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8203                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8204                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8205                                                 &events::MessageSendEvent::HandleError { .. } => false,
8206                                                 // Gossip
8207                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8208                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8209                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
8210                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8211                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8212                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8213                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8214                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8215                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8216                                         }
8217                                 });
8218                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8219                                 peer_state.is_connected = false;
8220                                 peer_state.ok_to_remove(true)
8221                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8222                 };
8223                 if remove_peer {
8224                         per_peer_state.remove(counterparty_node_id);
8225                 }
8226                 mem::drop(per_peer_state);
8227
8228                 for failure in failed_channels.drain(..) {
8229                         self.finish_close_channel(failure);
8230                 }
8231         }
8232
8233         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
8234                 if !init_msg.features.supports_static_remote_key() {
8235                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
8236                         return Err(());
8237                 }
8238
8239                 let mut res = Ok(());
8240
8241                 PersistenceNotifierGuard::optionally_notify(self, || {
8242                         // If we have too many peers connected which don't have funded channels, disconnect the
8243                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
8244                         // unfunded channels taking up space in memory for disconnected peers, we still let new
8245                         // peers connect, but we'll reject new channels from them.
8246                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
8247                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
8248
8249                         {
8250                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
8251                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
8252                                         hash_map::Entry::Vacant(e) => {
8253                                                 if inbound_peer_limited {
8254                                                         res = Err(());
8255                                                         return NotifyOption::SkipPersistNoEvents;
8256                                                 }
8257                                                 e.insert(Mutex::new(PeerState {
8258                                                         channel_by_id: HashMap::new(),
8259                                                         inbound_channel_request_by_id: HashMap::new(),
8260                                                         latest_features: init_msg.features.clone(),
8261                                                         pending_msg_events: Vec::new(),
8262                                                         in_flight_monitor_updates: BTreeMap::new(),
8263                                                         monitor_update_blocked_actions: BTreeMap::new(),
8264                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
8265                                                         is_connected: true,
8266                                                 }));
8267                                         },
8268                                         hash_map::Entry::Occupied(e) => {
8269                                                 let mut peer_state = e.get().lock().unwrap();
8270                                                 peer_state.latest_features = init_msg.features.clone();
8271
8272                                                 let best_block_height = self.best_block.read().unwrap().height();
8273                                                 if inbound_peer_limited &&
8274                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
8275                                                         peer_state.channel_by_id.len()
8276                                                 {
8277                                                         res = Err(());
8278                                                         return NotifyOption::SkipPersistNoEvents;
8279                                                 }
8280
8281                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
8282                                                 peer_state.is_connected = true;
8283                                         },
8284                                 }
8285                         }
8286
8287                         log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
8288
8289                         let per_peer_state = self.per_peer_state.read().unwrap();
8290                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8291                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8292                                 let peer_state = &mut *peer_state_lock;
8293                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8294
8295                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
8296                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else {
8297                                                 // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
8298                                                 // (so won't be recovered after a crash), they shouldn't exist here and we would never need to
8299                                                 // worry about closing and removing them.
8300                                                 debug_assert!(false);
8301                                                 None
8302                                         }
8303                                 ).for_each(|chan| {
8304                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
8305                                                 node_id: chan.context.get_counterparty_node_id(),
8306                                                 msg: chan.get_channel_reestablish(&self.logger),
8307                                         });
8308                                 });
8309                         }
8310
8311                         return NotifyOption::SkipPersistHandleEvents;
8312                         //TODO: Also re-broadcast announcement_signatures
8313                 });
8314                 res
8315         }
8316
8317         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
8318                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8319
8320                 match &msg.data as &str {
8321                         "cannot co-op close channel w/ active htlcs"|
8322                         "link failed to shutdown" =>
8323                         {
8324                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
8325                                 // send one while HTLCs are still present. The issue is tracked at
8326                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
8327                                 // to fix it but none so far have managed to land upstream. The issue appears to be
8328                                 // very low priority for the LND team despite being marked "P1".
8329                                 // We're not going to bother handling this in a sensible way, instead simply
8330                                 // repeating the Shutdown message on repeat until morale improves.
8331                                 if !msg.channel_id.is_zero() {
8332                                         let per_peer_state = self.per_peer_state.read().unwrap();
8333                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8334                                         if peer_state_mutex_opt.is_none() { return; }
8335                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
8336                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
8337                                                 if let Some(msg) = chan.get_outbound_shutdown() {
8338                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
8339                                                                 node_id: *counterparty_node_id,
8340                                                                 msg,
8341                                                         });
8342                                                 }
8343                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
8344                                                         node_id: *counterparty_node_id,
8345                                                         action: msgs::ErrorAction::SendWarningMessage {
8346                                                                 msg: msgs::WarningMessage {
8347                                                                         channel_id: msg.channel_id,
8348                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
8349                                                                 },
8350                                                                 log_level: Level::Trace,
8351                                                         }
8352                                                 });
8353                                         }
8354                                 }
8355                                 return;
8356                         }
8357                         _ => {}
8358                 }
8359
8360                 if msg.channel_id.is_zero() {
8361                         let channel_ids: Vec<ChannelId> = {
8362                                 let per_peer_state = self.per_peer_state.read().unwrap();
8363                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8364                                 if peer_state_mutex_opt.is_none() { return; }
8365                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8366                                 let peer_state = &mut *peer_state_lock;
8367                                 // Note that we don't bother generating any events for pre-accept channels -
8368                                 // they're not considered "channels" yet from the PoV of our events interface.
8369                                 peer_state.inbound_channel_request_by_id.clear();
8370                                 peer_state.channel_by_id.keys().cloned().collect()
8371                         };
8372                         for channel_id in channel_ids {
8373                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8374                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
8375                         }
8376                 } else {
8377                         {
8378                                 // First check if we can advance the channel type and try again.
8379                                 let per_peer_state = self.per_peer_state.read().unwrap();
8380                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
8381                                 if peer_state_mutex_opt.is_none() { return; }
8382                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
8383                                 let peer_state = &mut *peer_state_lock;
8384                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8385                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
8386                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
8387                                                         node_id: *counterparty_node_id,
8388                                                         msg,
8389                                                 });
8390                                                 return;
8391                                         }
8392                                 }
8393                         }
8394
8395                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
8396                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
8397                 }
8398         }
8399
8400         fn provided_node_features(&self) -> NodeFeatures {
8401                 provided_node_features(&self.default_configuration)
8402         }
8403
8404         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
8405                 provided_init_features(&self.default_configuration)
8406         }
8407
8408         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8409                 Some(vec![self.chain_hash])
8410         }
8411
8412         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
8413                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8414                         "Dual-funded channels not supported".to_owned(),
8415                          msg.channel_id.clone())), *counterparty_node_id);
8416         }
8417
8418         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
8419                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8420                         "Dual-funded channels not supported".to_owned(),
8421                          msg.channel_id.clone())), *counterparty_node_id);
8422         }
8423
8424         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
8425                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8426                         "Dual-funded channels not supported".to_owned(),
8427                          msg.channel_id.clone())), *counterparty_node_id);
8428         }
8429
8430         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
8431                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8432                         "Dual-funded channels not supported".to_owned(),
8433                          msg.channel_id.clone())), *counterparty_node_id);
8434         }
8435
8436         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
8437                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8438                         "Dual-funded channels not supported".to_owned(),
8439                          msg.channel_id.clone())), *counterparty_node_id);
8440         }
8441
8442         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
8443                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8444                         "Dual-funded channels not supported".to_owned(),
8445                          msg.channel_id.clone())), *counterparty_node_id);
8446         }
8447
8448         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
8449                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8450                         "Dual-funded channels not supported".to_owned(),
8451                          msg.channel_id.clone())), *counterparty_node_id);
8452         }
8453
8454         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
8455                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8456                         "Dual-funded channels not supported".to_owned(),
8457                          msg.channel_id.clone())), *counterparty_node_id);
8458         }
8459
8460         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
8461                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8462                         "Dual-funded channels not supported".to_owned(),
8463                          msg.channel_id.clone())), *counterparty_node_id);
8464         }
8465 }
8466
8467 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
8468 /// [`ChannelManager`].
8469 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
8470         let mut node_features = provided_init_features(config).to_context();
8471         node_features.set_keysend_optional();
8472         node_features
8473 }
8474
8475 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
8476 /// [`ChannelManager`].
8477 ///
8478 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8479 /// or not. Thus, this method is not public.
8480 #[cfg(any(feature = "_test_utils", test))]
8481 pub(crate) fn provided_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
8482         provided_init_features(config).to_context()
8483 }
8484
8485 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
8486 /// [`ChannelManager`].
8487 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
8488         provided_init_features(config).to_context()
8489 }
8490
8491 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
8492 /// [`ChannelManager`].
8493 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
8494         ChannelTypeFeatures::from_init(&provided_init_features(config))
8495 }
8496
8497 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
8498 /// [`ChannelManager`].
8499 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
8500         // Note that if new features are added here which other peers may (eventually) require, we
8501         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
8502         // [`ErroringMessageHandler`].
8503         let mut features = InitFeatures::empty();
8504         features.set_data_loss_protect_required();
8505         features.set_upfront_shutdown_script_optional();
8506         features.set_variable_length_onion_required();
8507         features.set_static_remote_key_required();
8508         features.set_payment_secret_required();
8509         features.set_basic_mpp_optional();
8510         features.set_wumbo_optional();
8511         features.set_shutdown_any_segwit_optional();
8512         features.set_channel_type_optional();
8513         features.set_scid_privacy_optional();
8514         features.set_zero_conf_optional();
8515         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
8516                 features.set_anchors_zero_fee_htlc_tx_optional();
8517         }
8518         features
8519 }
8520
8521 const SERIALIZATION_VERSION: u8 = 1;
8522 const MIN_SERIALIZATION_VERSION: u8 = 1;
8523
8524 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
8525         (2, fee_base_msat, required),
8526         (4, fee_proportional_millionths, required),
8527         (6, cltv_expiry_delta, required),
8528 });
8529
8530 impl_writeable_tlv_based!(ChannelCounterparty, {
8531         (2, node_id, required),
8532         (4, features, required),
8533         (6, unspendable_punishment_reserve, required),
8534         (8, forwarding_info, option),
8535         (9, outbound_htlc_minimum_msat, option),
8536         (11, outbound_htlc_maximum_msat, option),
8537 });
8538
8539 impl Writeable for ChannelDetails {
8540         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8541                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8542                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8543                 let user_channel_id_low = self.user_channel_id as u64;
8544                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
8545                 write_tlv_fields!(writer, {
8546                         (1, self.inbound_scid_alias, option),
8547                         (2, self.channel_id, required),
8548                         (3, self.channel_type, option),
8549                         (4, self.counterparty, required),
8550                         (5, self.outbound_scid_alias, option),
8551                         (6, self.funding_txo, option),
8552                         (7, self.config, option),
8553                         (8, self.short_channel_id, option),
8554                         (9, self.confirmations, option),
8555                         (10, self.channel_value_satoshis, required),
8556                         (12, self.unspendable_punishment_reserve, option),
8557                         (14, user_channel_id_low, required),
8558                         (16, self.balance_msat, required),
8559                         (18, self.outbound_capacity_msat, required),
8560                         (19, self.next_outbound_htlc_limit_msat, required),
8561                         (20, self.inbound_capacity_msat, required),
8562                         (21, self.next_outbound_htlc_minimum_msat, required),
8563                         (22, self.confirmations_required, option),
8564                         (24, self.force_close_spend_delay, option),
8565                         (26, self.is_outbound, required),
8566                         (28, self.is_channel_ready, required),
8567                         (30, self.is_usable, required),
8568                         (32, self.is_public, required),
8569                         (33, self.inbound_htlc_minimum_msat, option),
8570                         (35, self.inbound_htlc_maximum_msat, option),
8571                         (37, user_channel_id_high_opt, option),
8572                         (39, self.feerate_sat_per_1000_weight, option),
8573                         (41, self.channel_shutdown_state, option),
8574                 });
8575                 Ok(())
8576         }
8577 }
8578
8579 impl Readable for ChannelDetails {
8580         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8581                 _init_and_read_len_prefixed_tlv_fields!(reader, {
8582                         (1, inbound_scid_alias, option),
8583                         (2, channel_id, required),
8584                         (3, channel_type, option),
8585                         (4, counterparty, required),
8586                         (5, outbound_scid_alias, option),
8587                         (6, funding_txo, option),
8588                         (7, config, option),
8589                         (8, short_channel_id, option),
8590                         (9, confirmations, option),
8591                         (10, channel_value_satoshis, required),
8592                         (12, unspendable_punishment_reserve, option),
8593                         (14, user_channel_id_low, required),
8594                         (16, balance_msat, required),
8595                         (18, outbound_capacity_msat, required),
8596                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
8597                         // filled in, so we can safely unwrap it here.
8598                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
8599                         (20, inbound_capacity_msat, required),
8600                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
8601                         (22, confirmations_required, option),
8602                         (24, force_close_spend_delay, option),
8603                         (26, is_outbound, required),
8604                         (28, is_channel_ready, required),
8605                         (30, is_usable, required),
8606                         (32, is_public, required),
8607                         (33, inbound_htlc_minimum_msat, option),
8608                         (35, inbound_htlc_maximum_msat, option),
8609                         (37, user_channel_id_high_opt, option),
8610                         (39, feerate_sat_per_1000_weight, option),
8611                         (41, channel_shutdown_state, option),
8612                 });
8613
8614                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
8615                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
8616                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
8617                 let user_channel_id = user_channel_id_low as u128 +
8618                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
8619
8620                 Ok(Self {
8621                         inbound_scid_alias,
8622                         channel_id: channel_id.0.unwrap(),
8623                         channel_type,
8624                         counterparty: counterparty.0.unwrap(),
8625                         outbound_scid_alias,
8626                         funding_txo,
8627                         config,
8628                         short_channel_id,
8629                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
8630                         unspendable_punishment_reserve,
8631                         user_channel_id,
8632                         balance_msat: balance_msat.0.unwrap(),
8633                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
8634                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
8635                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
8636                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
8637                         confirmations_required,
8638                         confirmations,
8639                         force_close_spend_delay,
8640                         is_outbound: is_outbound.0.unwrap(),
8641                         is_channel_ready: is_channel_ready.0.unwrap(),
8642                         is_usable: is_usable.0.unwrap(),
8643                         is_public: is_public.0.unwrap(),
8644                         inbound_htlc_minimum_msat,
8645                         inbound_htlc_maximum_msat,
8646                         feerate_sat_per_1000_weight,
8647                         channel_shutdown_state,
8648                 })
8649         }
8650 }
8651
8652 impl_writeable_tlv_based!(PhantomRouteHints, {
8653         (2, channels, required_vec),
8654         (4, phantom_scid, required),
8655         (6, real_node_pubkey, required),
8656 });
8657
8658 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
8659         (0, Forward) => {
8660                 (0, onion_packet, required),
8661                 (2, short_channel_id, required),
8662         },
8663         (1, Receive) => {
8664                 (0, payment_data, required),
8665                 (1, phantom_shared_secret, option),
8666                 (2, incoming_cltv_expiry, required),
8667                 (3, payment_metadata, option),
8668                 (5, custom_tlvs, optional_vec),
8669         },
8670         (2, ReceiveKeysend) => {
8671                 (0, payment_preimage, required),
8672                 (2, incoming_cltv_expiry, required),
8673                 (3, payment_metadata, option),
8674                 (4, payment_data, option), // Added in 0.0.116
8675                 (5, custom_tlvs, optional_vec),
8676         },
8677 ;);
8678
8679 impl_writeable_tlv_based!(PendingHTLCInfo, {
8680         (0, routing, required),
8681         (2, incoming_shared_secret, required),
8682         (4, payment_hash, required),
8683         (6, outgoing_amt_msat, required),
8684         (8, outgoing_cltv_value, required),
8685         (9, incoming_amt_msat, option),
8686         (10, skimmed_fee_msat, option),
8687 });
8688
8689
8690 impl Writeable for HTLCFailureMsg {
8691         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8692                 match self {
8693                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
8694                                 0u8.write(writer)?;
8695                                 channel_id.write(writer)?;
8696                                 htlc_id.write(writer)?;
8697                                 reason.write(writer)?;
8698                         },
8699                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
8700                                 channel_id, htlc_id, sha256_of_onion, failure_code
8701                         }) => {
8702                                 1u8.write(writer)?;
8703                                 channel_id.write(writer)?;
8704                                 htlc_id.write(writer)?;
8705                                 sha256_of_onion.write(writer)?;
8706                                 failure_code.write(writer)?;
8707                         },
8708                 }
8709                 Ok(())
8710         }
8711 }
8712
8713 impl Readable for HTLCFailureMsg {
8714         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8715                 let id: u8 = Readable::read(reader)?;
8716                 match id {
8717                         0 => {
8718                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
8719                                         channel_id: Readable::read(reader)?,
8720                                         htlc_id: Readable::read(reader)?,
8721                                         reason: Readable::read(reader)?,
8722                                 }))
8723                         },
8724                         1 => {
8725                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
8726                                         channel_id: Readable::read(reader)?,
8727                                         htlc_id: Readable::read(reader)?,
8728                                         sha256_of_onion: Readable::read(reader)?,
8729                                         failure_code: Readable::read(reader)?,
8730                                 }))
8731                         },
8732                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
8733                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
8734                         // messages contained in the variants.
8735                         // In version 0.0.101, support for reading the variants with these types was added, and
8736                         // we should migrate to writing these variants when UpdateFailHTLC or
8737                         // UpdateFailMalformedHTLC get TLV fields.
8738                         2 => {
8739                                 let length: BigSize = Readable::read(reader)?;
8740                                 let mut s = FixedLengthReader::new(reader, length.0);
8741                                 let res = Readable::read(&mut s)?;
8742                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
8743                                 Ok(HTLCFailureMsg::Relay(res))
8744                         },
8745                         3 => {
8746                                 let length: BigSize = Readable::read(reader)?;
8747                                 let mut s = FixedLengthReader::new(reader, length.0);
8748                                 let res = Readable::read(&mut s)?;
8749                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
8750                                 Ok(HTLCFailureMsg::Malformed(res))
8751                         },
8752                         _ => Err(DecodeError::UnknownRequiredFeature),
8753                 }
8754         }
8755 }
8756
8757 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
8758         (0, Forward),
8759         (1, Fail),
8760 );
8761
8762 impl_writeable_tlv_based!(HTLCPreviousHopData, {
8763         (0, short_channel_id, required),
8764         (1, phantom_shared_secret, option),
8765         (2, outpoint, required),
8766         (4, htlc_id, required),
8767         (6, incoming_packet_shared_secret, required),
8768         (7, user_channel_id, option),
8769 });
8770
8771 impl Writeable for ClaimableHTLC {
8772         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8773                 let (payment_data, keysend_preimage) = match &self.onion_payload {
8774                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
8775                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
8776                 };
8777                 write_tlv_fields!(writer, {
8778                         (0, self.prev_hop, required),
8779                         (1, self.total_msat, required),
8780                         (2, self.value, required),
8781                         (3, self.sender_intended_value, required),
8782                         (4, payment_data, option),
8783                         (5, self.total_value_received, option),
8784                         (6, self.cltv_expiry, required),
8785                         (8, keysend_preimage, option),
8786                         (10, self.counterparty_skimmed_fee_msat, option),
8787                 });
8788                 Ok(())
8789         }
8790 }
8791
8792 impl Readable for ClaimableHTLC {
8793         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8794                 _init_and_read_len_prefixed_tlv_fields!(reader, {
8795                         (0, prev_hop, required),
8796                         (1, total_msat, option),
8797                         (2, value_ser, required),
8798                         (3, sender_intended_value, option),
8799                         (4, payment_data_opt, option),
8800                         (5, total_value_received, option),
8801                         (6, cltv_expiry, required),
8802                         (8, keysend_preimage, option),
8803                         (10, counterparty_skimmed_fee_msat, option),
8804                 });
8805                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
8806                 let value = value_ser.0.unwrap();
8807                 let onion_payload = match keysend_preimage {
8808                         Some(p) => {
8809                                 if payment_data.is_some() {
8810                                         return Err(DecodeError::InvalidValue)
8811                                 }
8812                                 if total_msat.is_none() {
8813                                         total_msat = Some(value);
8814                                 }
8815                                 OnionPayload::Spontaneous(p)
8816                         },
8817                         None => {
8818                                 if total_msat.is_none() {
8819                                         if payment_data.is_none() {
8820                                                 return Err(DecodeError::InvalidValue)
8821                                         }
8822                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
8823                                 }
8824                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
8825                         },
8826                 };
8827                 Ok(Self {
8828                         prev_hop: prev_hop.0.unwrap(),
8829                         timer_ticks: 0,
8830                         value,
8831                         sender_intended_value: sender_intended_value.unwrap_or(value),
8832                         total_value_received,
8833                         total_msat: total_msat.unwrap(),
8834                         onion_payload,
8835                         cltv_expiry: cltv_expiry.0.unwrap(),
8836                         counterparty_skimmed_fee_msat,
8837                 })
8838         }
8839 }
8840
8841 impl Readable for HTLCSource {
8842         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8843                 let id: u8 = Readable::read(reader)?;
8844                 match id {
8845                         0 => {
8846                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
8847                                 let mut first_hop_htlc_msat: u64 = 0;
8848                                 let mut path_hops = Vec::new();
8849                                 let mut payment_id = None;
8850                                 let mut payment_params: Option<PaymentParameters> = None;
8851                                 let mut blinded_tail: Option<BlindedTail> = None;
8852                                 read_tlv_fields!(reader, {
8853                                         (0, session_priv, required),
8854                                         (1, payment_id, option),
8855                                         (2, first_hop_htlc_msat, required),
8856                                         (4, path_hops, required_vec),
8857                                         (5, payment_params, (option: ReadableArgs, 0)),
8858                                         (6, blinded_tail, option),
8859                                 });
8860                                 if payment_id.is_none() {
8861                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
8862                                         // instead.
8863                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
8864                                 }
8865                                 let path = Path { hops: path_hops, blinded_tail };
8866                                 if path.hops.len() == 0 {
8867                                         return Err(DecodeError::InvalidValue);
8868                                 }
8869                                 if let Some(params) = payment_params.as_mut() {
8870                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
8871                                                 if final_cltv_expiry_delta == &0 {
8872                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
8873                                                 }
8874                                         }
8875                                 }
8876                                 Ok(HTLCSource::OutboundRoute {
8877                                         session_priv: session_priv.0.unwrap(),
8878                                         first_hop_htlc_msat,
8879                                         path,
8880                                         payment_id: payment_id.unwrap(),
8881                                 })
8882                         }
8883                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
8884                         _ => Err(DecodeError::UnknownRequiredFeature),
8885                 }
8886         }
8887 }
8888
8889 impl Writeable for HTLCSource {
8890         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
8891                 match self {
8892                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
8893                                 0u8.write(writer)?;
8894                                 let payment_id_opt = Some(payment_id);
8895                                 write_tlv_fields!(writer, {
8896                                         (0, session_priv, required),
8897                                         (1, payment_id_opt, option),
8898                                         (2, first_hop_htlc_msat, required),
8899                                         // 3 was previously used to write a PaymentSecret for the payment.
8900                                         (4, path.hops, required_vec),
8901                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
8902                                         (6, path.blinded_tail, option),
8903                                  });
8904                         }
8905                         HTLCSource::PreviousHopData(ref field) => {
8906                                 1u8.write(writer)?;
8907                                 field.write(writer)?;
8908                         }
8909                 }
8910                 Ok(())
8911         }
8912 }
8913
8914 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
8915         (0, forward_info, required),
8916         (1, prev_user_channel_id, (default_value, 0)),
8917         (2, prev_short_channel_id, required),
8918         (4, prev_htlc_id, required),
8919         (6, prev_funding_outpoint, required),
8920 });
8921
8922 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
8923         (1, FailHTLC) => {
8924                 (0, htlc_id, required),
8925                 (2, err_packet, required),
8926         };
8927         (0, AddHTLC)
8928 );
8929
8930 impl_writeable_tlv_based!(PendingInboundPayment, {
8931         (0, payment_secret, required),
8932         (2, expiry_time, required),
8933         (4, user_payment_id, required),
8934         (6, payment_preimage, required),
8935         (8, min_value_msat, required),
8936 });
8937
8938 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>
8939 where
8940         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8941         T::Target: BroadcasterInterface,
8942         ES::Target: EntropySource,
8943         NS::Target: NodeSigner,
8944         SP::Target: SignerProvider,
8945         F::Target: FeeEstimator,
8946         R::Target: Router,
8947         L::Target: Logger,
8948 {
8949         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8950                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
8951
8952                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
8953
8954                 self.chain_hash.write(writer)?;
8955                 {
8956                         let best_block = self.best_block.read().unwrap();
8957                         best_block.height().write(writer)?;
8958                         best_block.block_hash().write(writer)?;
8959                 }
8960
8961                 let mut serializable_peer_count: u64 = 0;
8962                 {
8963                         let per_peer_state = self.per_peer_state.read().unwrap();
8964                         let mut number_of_funded_channels = 0;
8965                         for (_, peer_state_mutex) in per_peer_state.iter() {
8966                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8967                                 let peer_state = &mut *peer_state_lock;
8968                                 if !peer_state.ok_to_remove(false) {
8969                                         serializable_peer_count += 1;
8970                                 }
8971
8972                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
8973                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
8974                                 ).count();
8975                         }
8976
8977                         (number_of_funded_channels as u64).write(writer)?;
8978
8979                         for (_, peer_state_mutex) in per_peer_state.iter() {
8980                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8981                                 let peer_state = &mut *peer_state_lock;
8982                                 for channel in peer_state.channel_by_id.iter().filter_map(
8983                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
8984                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
8985                                         } else { None }
8986                                 ) {
8987                                         channel.write(writer)?;
8988                                 }
8989                         }
8990                 }
8991
8992                 {
8993                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
8994                         (forward_htlcs.len() as u64).write(writer)?;
8995                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
8996                                 short_channel_id.write(writer)?;
8997                                 (pending_forwards.len() as u64).write(writer)?;
8998                                 for forward in pending_forwards {
8999                                         forward.write(writer)?;
9000                                 }
9001                         }
9002                 }
9003
9004                 let per_peer_state = self.per_peer_state.write().unwrap();
9005
9006                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9007                 let claimable_payments = self.claimable_payments.lock().unwrap();
9008                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9009
9010                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9011                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9012                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9013                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9014                         payment_hash.write(writer)?;
9015                         (payment.htlcs.len() as u64).write(writer)?;
9016                         for htlc in payment.htlcs.iter() {
9017                                 htlc.write(writer)?;
9018                         }
9019                         htlc_purposes.push(&payment.purpose);
9020                         htlc_onion_fields.push(&payment.onion_fields);
9021                 }
9022
9023                 let mut monitor_update_blocked_actions_per_peer = None;
9024                 let mut peer_states = Vec::new();
9025                 for (_, peer_state_mutex) in per_peer_state.iter() {
9026                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
9027                         // of a lockorder violation deadlock - no other thread can be holding any
9028                         // per_peer_state lock at all.
9029                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
9030                 }
9031
9032                 (serializable_peer_count).write(writer)?;
9033                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9034                         // Peers which we have no channels to should be dropped once disconnected. As we
9035                         // disconnect all peers when shutting down and serializing the ChannelManager, we
9036                         // consider all peers as disconnected here. There's therefore no need write peers with
9037                         // no channels.
9038                         if !peer_state.ok_to_remove(false) {
9039                                 peer_pubkey.write(writer)?;
9040                                 peer_state.latest_features.write(writer)?;
9041                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
9042                                         monitor_update_blocked_actions_per_peer
9043                                                 .get_or_insert_with(Vec::new)
9044                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
9045                                 }
9046                         }
9047                 }
9048
9049                 let events = self.pending_events.lock().unwrap();
9050                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
9051                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
9052                 // refuse to read the new ChannelManager.
9053                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
9054                 if events_not_backwards_compatible {
9055                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
9056                         // well save the space and not write any events here.
9057                         0u64.write(writer)?;
9058                 } else {
9059                         (events.len() as u64).write(writer)?;
9060                         for (event, _) in events.iter() {
9061                                 event.write(writer)?;
9062                         }
9063                 }
9064
9065                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
9066                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
9067                 // the closing monitor updates were always effectively replayed on startup (either directly
9068                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
9069                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
9070                 0u64.write(writer)?;
9071
9072                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
9073                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
9074                 // likely to be identical.
9075                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9076                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
9077
9078                 (pending_inbound_payments.len() as u64).write(writer)?;
9079                 for (hash, pending_payment) in pending_inbound_payments.iter() {
9080                         hash.write(writer)?;
9081                         pending_payment.write(writer)?;
9082                 }
9083
9084                 // For backwards compat, write the session privs and their total length.
9085                 let mut num_pending_outbounds_compat: u64 = 0;
9086                 for (_, outbound) in pending_outbound_payments.iter() {
9087                         if !outbound.is_fulfilled() && !outbound.abandoned() {
9088                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
9089                         }
9090                 }
9091                 num_pending_outbounds_compat.write(writer)?;
9092                 for (_, outbound) in pending_outbound_payments.iter() {
9093                         match outbound {
9094                                 PendingOutboundPayment::Legacy { session_privs } |
9095                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9096                                         for session_priv in session_privs.iter() {
9097                                                 session_priv.write(writer)?;
9098                                         }
9099                                 }
9100                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
9101                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
9102                                 PendingOutboundPayment::Fulfilled { .. } => {},
9103                                 PendingOutboundPayment::Abandoned { .. } => {},
9104                         }
9105                 }
9106
9107                 // Encode without retry info for 0.0.101 compatibility.
9108                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
9109                 for (id, outbound) in pending_outbound_payments.iter() {
9110                         match outbound {
9111                                 PendingOutboundPayment::Legacy { session_privs } |
9112                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
9113                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
9114                                 },
9115                                 _ => {},
9116                         }
9117                 }
9118
9119                 let mut pending_intercepted_htlcs = None;
9120                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
9121                 if our_pending_intercepts.len() != 0 {
9122                         pending_intercepted_htlcs = Some(our_pending_intercepts);
9123                 }
9124
9125                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
9126                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
9127                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
9128                         // map. Thus, if there are no entries we skip writing a TLV for it.
9129                         pending_claiming_payments = None;
9130                 }
9131
9132                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
9133                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
9134                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
9135                                 if !updates.is_empty() {
9136                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
9137                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
9138                                 }
9139                         }
9140                 }
9141
9142                 write_tlv_fields!(writer, {
9143                         (1, pending_outbound_payments_no_retry, required),
9144                         (2, pending_intercepted_htlcs, option),
9145                         (3, pending_outbound_payments, required),
9146                         (4, pending_claiming_payments, option),
9147                         (5, self.our_network_pubkey, required),
9148                         (6, monitor_update_blocked_actions_per_peer, option),
9149                         (7, self.fake_scid_rand_bytes, required),
9150                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
9151                         (9, htlc_purposes, required_vec),
9152                         (10, in_flight_monitor_updates, option),
9153                         (11, self.probing_cookie_secret, required),
9154                         (13, htlc_onion_fields, optional_vec),
9155                 });
9156
9157                 Ok(())
9158         }
9159 }
9160
9161 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
9162         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9163                 (self.len() as u64).write(w)?;
9164                 for (event, action) in self.iter() {
9165                         event.write(w)?;
9166                         action.write(w)?;
9167                         #[cfg(debug_assertions)] {
9168                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
9169                                 // be persisted and are regenerated on restart. However, if such an event has a
9170                                 // post-event-handling action we'll write nothing for the event and would have to
9171                                 // either forget the action or fail on deserialization (which we do below). Thus,
9172                                 // check that the event is sane here.
9173                                 let event_encoded = event.encode();
9174                                 let event_read: Option<Event> =
9175                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
9176                                 if action.is_some() { assert!(event_read.is_some()); }
9177                         }
9178                 }
9179                 Ok(())
9180         }
9181 }
9182 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
9183         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9184                 let len: u64 = Readable::read(reader)?;
9185                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
9186                 let mut events: Self = VecDeque::with_capacity(cmp::min(
9187                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
9188                         len) as usize);
9189                 for _ in 0..len {
9190                         let ev_opt = MaybeReadable::read(reader)?;
9191                         let action = Readable::read(reader)?;
9192                         if let Some(ev) = ev_opt {
9193                                 events.push_back((ev, action));
9194                         } else if action.is_some() {
9195                                 return Err(DecodeError::InvalidValue);
9196                         }
9197                 }
9198                 Ok(events)
9199         }
9200 }
9201
9202 impl_writeable_tlv_based_enum!(ChannelShutdownState,
9203         (0, NotShuttingDown) => {},
9204         (2, ShutdownInitiated) => {},
9205         (4, ResolvingHTLCs) => {},
9206         (6, NegotiatingClosingFee) => {},
9207         (8, ShutdownComplete) => {}, ;
9208 );
9209
9210 /// Arguments for the creation of a ChannelManager that are not deserialized.
9211 ///
9212 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
9213 /// is:
9214 /// 1) Deserialize all stored [`ChannelMonitor`]s.
9215 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
9216 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
9217 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
9218 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
9219 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
9220 ///    same way you would handle a [`chain::Filter`] call using
9221 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
9222 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
9223 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
9224 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
9225 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
9226 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
9227 ///    the next step.
9228 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
9229 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
9230 ///
9231 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
9232 /// call any other methods on the newly-deserialized [`ChannelManager`].
9233 ///
9234 /// Note that because some channels may be closed during deserialization, it is critical that you
9235 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
9236 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
9237 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
9238 /// not force-close the same channels but consider them live), you may end up revoking a state for
9239 /// which you've already broadcasted the transaction.
9240 ///
9241 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
9242 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9243 where
9244         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9245         T::Target: BroadcasterInterface,
9246         ES::Target: EntropySource,
9247         NS::Target: NodeSigner,
9248         SP::Target: SignerProvider,
9249         F::Target: FeeEstimator,
9250         R::Target: Router,
9251         L::Target: Logger,
9252 {
9253         /// A cryptographically secure source of entropy.
9254         pub entropy_source: ES,
9255
9256         /// A signer that is able to perform node-scoped cryptographic operations.
9257         pub node_signer: NS,
9258
9259         /// The keys provider which will give us relevant keys. Some keys will be loaded during
9260         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
9261         /// signing data.
9262         pub signer_provider: SP,
9263
9264         /// The fee_estimator for use in the ChannelManager in the future.
9265         ///
9266         /// No calls to the FeeEstimator will be made during deserialization.
9267         pub fee_estimator: F,
9268         /// The chain::Watch for use in the ChannelManager in the future.
9269         ///
9270         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
9271         /// you have deserialized ChannelMonitors separately and will add them to your
9272         /// chain::Watch after deserializing this ChannelManager.
9273         pub chain_monitor: M,
9274
9275         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
9276         /// used to broadcast the latest local commitment transactions of channels which must be
9277         /// force-closed during deserialization.
9278         pub tx_broadcaster: T,
9279         /// The router which will be used in the ChannelManager in the future for finding routes
9280         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
9281         ///
9282         /// No calls to the router will be made during deserialization.
9283         pub router: R,
9284         /// The Logger for use in the ChannelManager and which may be used to log information during
9285         /// deserialization.
9286         pub logger: L,
9287         /// Default settings used for new channels. Any existing channels will continue to use the
9288         /// runtime settings which were stored when the ChannelManager was serialized.
9289         pub default_config: UserConfig,
9290
9291         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
9292         /// value.context.get_funding_txo() should be the key).
9293         ///
9294         /// If a monitor is inconsistent with the channel state during deserialization the channel will
9295         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
9296         /// is true for missing channels as well. If there is a monitor missing for which we find
9297         /// channel data Err(DecodeError::InvalidValue) will be returned.
9298         ///
9299         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
9300         /// this struct.
9301         ///
9302         /// This is not exported to bindings users because we have no HashMap bindings
9303         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
9304 }
9305
9306 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9307                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
9308 where
9309         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9310         T::Target: BroadcasterInterface,
9311         ES::Target: EntropySource,
9312         NS::Target: NodeSigner,
9313         SP::Target: SignerProvider,
9314         F::Target: FeeEstimator,
9315         R::Target: Router,
9316         L::Target: Logger,
9317 {
9318         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
9319         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
9320         /// populate a HashMap directly from C.
9321         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,
9322                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
9323                 Self {
9324                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
9325                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
9326                 }
9327         }
9328 }
9329
9330 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
9331 // SipmleArcChannelManager type:
9332 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9333         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
9334 where
9335         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9336         T::Target: BroadcasterInterface,
9337         ES::Target: EntropySource,
9338         NS::Target: NodeSigner,
9339         SP::Target: SignerProvider,
9340         F::Target: FeeEstimator,
9341         R::Target: Router,
9342         L::Target: Logger,
9343 {
9344         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9345                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
9346                 Ok((blockhash, Arc::new(chan_manager)))
9347         }
9348 }
9349
9350 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9351         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
9352 where
9353         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
9354         T::Target: BroadcasterInterface,
9355         ES::Target: EntropySource,
9356         NS::Target: NodeSigner,
9357         SP::Target: SignerProvider,
9358         F::Target: FeeEstimator,
9359         R::Target: Router,
9360         L::Target: Logger,
9361 {
9362         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
9363                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
9364
9365                 let chain_hash: ChainHash = Readable::read(reader)?;
9366                 let best_block_height: u32 = Readable::read(reader)?;
9367                 let best_block_hash: BlockHash = Readable::read(reader)?;
9368
9369                 let mut failed_htlcs = Vec::new();
9370
9371                 let channel_count: u64 = Readable::read(reader)?;
9372                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
9373                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9374                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9375                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
9376                 let mut channel_closures = VecDeque::new();
9377                 let mut close_background_events = Vec::new();
9378                 for _ in 0..channel_count {
9379                         let mut channel: Channel<SP> = Channel::read(reader, (
9380                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
9381                         ))?;
9382                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
9383                         funding_txo_set.insert(funding_txo.clone());
9384                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
9385                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
9386                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
9387                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
9388                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9389                                         // But if the channel is behind of the monitor, close the channel:
9390                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
9391                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
9392                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
9393                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
9394                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
9395                                         }
9396                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
9397                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
9398                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
9399                                         }
9400                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
9401                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
9402                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
9403                                         }
9404                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
9405                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
9406                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
9407                                         }
9408                                         let (monitor_update, mut new_failed_htlcs, batch_funding_txid) = channel.context.force_shutdown(true);
9409                                         if batch_funding_txid.is_some() {
9410                                                 return Err(DecodeError::InvalidValue);
9411                                         }
9412                                         if let Some((counterparty_node_id, funding_txo, update)) = monitor_update {
9413                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
9414                                                         counterparty_node_id, funding_txo, update
9415                                                 });
9416                                         }
9417                                         failed_htlcs.append(&mut new_failed_htlcs);
9418                                         channel_closures.push_back((events::Event::ChannelClosed {
9419                                                 channel_id: channel.context.channel_id(),
9420                                                 user_channel_id: channel.context.get_user_id(),
9421                                                 reason: ClosureReason::OutdatedChannelManager,
9422                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9423                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9424                                         }, None));
9425                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
9426                                                 let mut found_htlc = false;
9427                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
9428                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
9429                                                 }
9430                                                 if !found_htlc {
9431                                                         // If we have some HTLCs in the channel which are not present in the newer
9432                                                         // ChannelMonitor, they have been removed and should be failed back to
9433                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
9434                                                         // were actually claimed we'd have generated and ensured the previous-hop
9435                                                         // claim update ChannelMonitor updates were persisted prior to persising
9436                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
9437                                                         // backwards leg of the HTLC will simply be rejected.
9438                                                         log_info!(args.logger,
9439                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
9440                                                                 &channel.context.channel_id(), &payment_hash);
9441                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9442                                                 }
9443                                         }
9444                                 } else {
9445                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
9446                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
9447                                                 monitor.get_latest_update_id());
9448                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
9449                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
9450                                         }
9451                                         if channel.context.is_funding_broadcast() {
9452                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
9453                                         }
9454                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
9455                                                 hash_map::Entry::Occupied(mut entry) => {
9456                                                         let by_id_map = entry.get_mut();
9457                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9458                                                 },
9459                                                 hash_map::Entry::Vacant(entry) => {
9460                                                         let mut by_id_map = HashMap::new();
9461                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
9462                                                         entry.insert(by_id_map);
9463                                                 }
9464                                         }
9465                                 }
9466                         } else if channel.is_awaiting_initial_mon_persist() {
9467                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
9468                                 // was in-progress, we never broadcasted the funding transaction and can still
9469                                 // safely discard the channel.
9470                                 let _ = channel.context.force_shutdown(false);
9471                                 channel_closures.push_back((events::Event::ChannelClosed {
9472                                         channel_id: channel.context.channel_id(),
9473                                         user_channel_id: channel.context.get_user_id(),
9474                                         reason: ClosureReason::DisconnectedPeer,
9475                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
9476                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
9477                                 }, None));
9478                         } else {
9479                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
9480                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9481                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9482                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
9483                                 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");
9484                                 return Err(DecodeError::InvalidValue);
9485                         }
9486                 }
9487
9488                 for (funding_txo, _) in args.channel_monitors.iter() {
9489                         if !funding_txo_set.contains(funding_txo) {
9490                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
9491                                         &funding_txo.to_channel_id());
9492                                 let monitor_update = ChannelMonitorUpdate {
9493                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
9494                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
9495                                 };
9496                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
9497                         }
9498                 }
9499
9500                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
9501                 let forward_htlcs_count: u64 = Readable::read(reader)?;
9502                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
9503                 for _ in 0..forward_htlcs_count {
9504                         let short_channel_id = Readable::read(reader)?;
9505                         let pending_forwards_count: u64 = Readable::read(reader)?;
9506                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
9507                         for _ in 0..pending_forwards_count {
9508                                 pending_forwards.push(Readable::read(reader)?);
9509                         }
9510                         forward_htlcs.insert(short_channel_id, pending_forwards);
9511                 }
9512
9513                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
9514                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
9515                 for _ in 0..claimable_htlcs_count {
9516                         let payment_hash = Readable::read(reader)?;
9517                         let previous_hops_len: u64 = Readable::read(reader)?;
9518                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
9519                         for _ in 0..previous_hops_len {
9520                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
9521                         }
9522                         claimable_htlcs_list.push((payment_hash, previous_hops));
9523                 }
9524
9525                 let peer_state_from_chans = |channel_by_id| {
9526                         PeerState {
9527                                 channel_by_id,
9528                                 inbound_channel_request_by_id: HashMap::new(),
9529                                 latest_features: InitFeatures::empty(),
9530                                 pending_msg_events: Vec::new(),
9531                                 in_flight_monitor_updates: BTreeMap::new(),
9532                                 monitor_update_blocked_actions: BTreeMap::new(),
9533                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
9534                                 is_connected: false,
9535                         }
9536                 };
9537
9538                 let peer_count: u64 = Readable::read(reader)?;
9539                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
9540                 for _ in 0..peer_count {
9541                         let peer_pubkey = Readable::read(reader)?;
9542                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
9543                         let mut peer_state = peer_state_from_chans(peer_chans);
9544                         peer_state.latest_features = Readable::read(reader)?;
9545                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
9546                 }
9547
9548                 let event_count: u64 = Readable::read(reader)?;
9549                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
9550                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
9551                 for _ in 0..event_count {
9552                         match MaybeReadable::read(reader)? {
9553                                 Some(event) => pending_events_read.push_back((event, None)),
9554                                 None => continue,
9555                         }
9556                 }
9557
9558                 let background_event_count: u64 = Readable::read(reader)?;
9559                 for _ in 0..background_event_count {
9560                         match <u8 as Readable>::read(reader)? {
9561                                 0 => {
9562                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
9563                                         // however we really don't (and never did) need them - we regenerate all
9564                                         // on-startup monitor updates.
9565                                         let _: OutPoint = Readable::read(reader)?;
9566                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
9567                                 }
9568                                 _ => return Err(DecodeError::InvalidValue),
9569                         }
9570                 }
9571
9572                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
9573                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
9574
9575                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
9576                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
9577                 for _ in 0..pending_inbound_payment_count {
9578                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
9579                                 return Err(DecodeError::InvalidValue);
9580                         }
9581                 }
9582
9583                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
9584                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
9585                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
9586                 for _ in 0..pending_outbound_payments_count_compat {
9587                         let session_priv = Readable::read(reader)?;
9588                         let payment = PendingOutboundPayment::Legacy {
9589                                 session_privs: [session_priv].iter().cloned().collect()
9590                         };
9591                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
9592                                 return Err(DecodeError::InvalidValue)
9593                         };
9594                 }
9595
9596                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
9597                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
9598                 let mut pending_outbound_payments = None;
9599                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
9600                 let mut received_network_pubkey: Option<PublicKey> = None;
9601                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
9602                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
9603                 let mut claimable_htlc_purposes = None;
9604                 let mut claimable_htlc_onion_fields = None;
9605                 let mut pending_claiming_payments = Some(HashMap::new());
9606                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
9607                 let mut events_override = None;
9608                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
9609                 read_tlv_fields!(reader, {
9610                         (1, pending_outbound_payments_no_retry, option),
9611                         (2, pending_intercepted_htlcs, option),
9612                         (3, pending_outbound_payments, option),
9613                         (4, pending_claiming_payments, option),
9614                         (5, received_network_pubkey, option),
9615                         (6, monitor_update_blocked_actions_per_peer, option),
9616                         (7, fake_scid_rand_bytes, option),
9617                         (8, events_override, option),
9618                         (9, claimable_htlc_purposes, optional_vec),
9619                         (10, in_flight_monitor_updates, option),
9620                         (11, probing_cookie_secret, option),
9621                         (13, claimable_htlc_onion_fields, optional_vec),
9622                 });
9623                 if fake_scid_rand_bytes.is_none() {
9624                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
9625                 }
9626
9627                 if probing_cookie_secret.is_none() {
9628                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
9629                 }
9630
9631                 if let Some(events) = events_override {
9632                         pending_events_read = events;
9633                 }
9634
9635                 if !channel_closures.is_empty() {
9636                         pending_events_read.append(&mut channel_closures);
9637                 }
9638
9639                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
9640                         pending_outbound_payments = Some(pending_outbound_payments_compat);
9641                 } else if pending_outbound_payments.is_none() {
9642                         let mut outbounds = HashMap::new();
9643                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
9644                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
9645                         }
9646                         pending_outbound_payments = Some(outbounds);
9647                 }
9648                 let pending_outbounds = OutboundPayments {
9649                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
9650                         retry_lock: Mutex::new(())
9651                 };
9652
9653                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
9654                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
9655                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
9656                 // replayed, and for each monitor update we have to replay we have to ensure there's a
9657                 // `ChannelMonitor` for it.
9658                 //
9659                 // In order to do so we first walk all of our live channels (so that we can check their
9660                 // state immediately after doing the update replays, when we have the `update_id`s
9661                 // available) and then walk any remaining in-flight updates.
9662                 //
9663                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
9664                 let mut pending_background_events = Vec::new();
9665                 macro_rules! handle_in_flight_updates {
9666                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
9667                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
9668                         ) => { {
9669                                 let mut max_in_flight_update_id = 0;
9670                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
9671                                 for update in $chan_in_flight_upds.iter() {
9672                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
9673                                                 update.update_id, $channel_info_log, &$funding_txo.to_channel_id());
9674                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
9675                                         pending_background_events.push(
9676                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
9677                                                         counterparty_node_id: $counterparty_node_id,
9678                                                         funding_txo: $funding_txo,
9679                                                         update: update.clone(),
9680                                                 });
9681                                 }
9682                                 if $chan_in_flight_upds.is_empty() {
9683                                         // We had some updates to apply, but it turns out they had completed before we
9684                                         // were serialized, we just weren't notified of that. Thus, we may have to run
9685                                         // the completion actions for any monitor updates, but otherwise are done.
9686                                         pending_background_events.push(
9687                                                 BackgroundEvent::MonitorUpdatesComplete {
9688                                                         counterparty_node_id: $counterparty_node_id,
9689                                                         channel_id: $funding_txo.to_channel_id(),
9690                                                 });
9691                                 }
9692                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
9693                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
9694                                         return Err(DecodeError::InvalidValue);
9695                                 }
9696                                 max_in_flight_update_id
9697                         } }
9698                 }
9699
9700                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
9701                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
9702                         let peer_state = &mut *peer_state_lock;
9703                         for phase in peer_state.channel_by_id.values() {
9704                                 if let ChannelPhase::Funded(chan) = phase {
9705                                         // Channels that were persisted have to be funded, otherwise they should have been
9706                                         // discarded.
9707                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
9708                                         let monitor = args.channel_monitors.get(&funding_txo)
9709                                                 .expect("We already checked for monitor presence when loading channels");
9710                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
9711                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
9712                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
9713                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
9714                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
9715                                                                         funding_txo, monitor, peer_state, ""));
9716                                                 }
9717                                         }
9718                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
9719                                                 // If the channel is ahead of the monitor, return InvalidValue:
9720                                                 log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
9721                                                 log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
9722                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
9723                                                 log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
9724                                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9725                                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9726                                                 log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
9727                                                 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");
9728                                                 return Err(DecodeError::InvalidValue);
9729                                         }
9730                                 } else {
9731                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
9732                                         // created in this `channel_by_id` map.
9733                                         debug_assert!(false);
9734                                         return Err(DecodeError::InvalidValue);
9735                                 }
9736                         }
9737                 }
9738
9739                 if let Some(in_flight_upds) = in_flight_monitor_updates {
9740                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
9741                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
9742                                         // Now that we've removed all the in-flight monitor updates for channels that are
9743                                         // still open, we need to replay any monitor updates that are for closed channels,
9744                                         // creating the neccessary peer_state entries as we go.
9745                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
9746                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
9747                                         });
9748                                         let mut peer_state = peer_state_mutex.lock().unwrap();
9749                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
9750                                                 funding_txo, monitor, peer_state, "closed ");
9751                                 } else {
9752                                         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!");
9753                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
9754                                                 &funding_txo.to_channel_id());
9755                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
9756                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
9757                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
9758                                         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");
9759                                         return Err(DecodeError::InvalidValue);
9760                                 }
9761                         }
9762                 }
9763
9764                 // Note that we have to do the above replays before we push new monitor updates.
9765                 pending_background_events.append(&mut close_background_events);
9766
9767                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
9768                 // should ensure we try them again on the inbound edge. We put them here and do so after we
9769                 // have a fully-constructed `ChannelManager` at the end.
9770                 let mut pending_claims_to_replay = Vec::new();
9771
9772                 {
9773                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
9774                         // ChannelMonitor data for any channels for which we do not have authorative state
9775                         // (i.e. those for which we just force-closed above or we otherwise don't have a
9776                         // corresponding `Channel` at all).
9777                         // This avoids several edge-cases where we would otherwise "forget" about pending
9778                         // payments which are still in-flight via their on-chain state.
9779                         // We only rebuild the pending payments map if we were most recently serialized by
9780                         // 0.0.102+
9781                         for (_, monitor) in args.channel_monitors.iter() {
9782                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
9783                                 if counterparty_opt.is_none() {
9784                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
9785                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
9786                                                         if path.hops.is_empty() {
9787                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
9788                                                                 return Err(DecodeError::InvalidValue);
9789                                                         }
9790
9791                                                         let path_amt = path.final_value_msat();
9792                                                         let mut session_priv_bytes = [0; 32];
9793                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
9794                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
9795                                                                 hash_map::Entry::Occupied(mut entry) => {
9796                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
9797                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
9798                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), &htlc.payment_hash);
9799                                                                 },
9800                                                                 hash_map::Entry::Vacant(entry) => {
9801                                                                         let path_fee = path.fee_msat();
9802                                                                         entry.insert(PendingOutboundPayment::Retryable {
9803                                                                                 retry_strategy: None,
9804                                                                                 attempts: PaymentAttempts::new(),
9805                                                                                 payment_params: None,
9806                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
9807                                                                                 payment_hash: htlc.payment_hash,
9808                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
9809                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
9810                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
9811                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
9812                                                                                 pending_amt_msat: path_amt,
9813                                                                                 pending_fee_msat: Some(path_fee),
9814                                                                                 total_msat: path_amt,
9815                                                                                 starting_block_height: best_block_height,
9816                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
9817                                                                         });
9818                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
9819                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
9820                                                                 }
9821                                                         }
9822                                                 }
9823                                         }
9824                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
9825                                                 match htlc_source {
9826                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
9827                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
9828                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
9829                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
9830                                                                 };
9831                                                                 // The ChannelMonitor is now responsible for this HTLC's
9832                                                                 // failure/success and will let us know what its outcome is. If we
9833                                                                 // still have an entry for this HTLC in `forward_htlcs` or
9834                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
9835                                                                 // the monitor was when forwarding the payment.
9836                                                                 forward_htlcs.retain(|_, forwards| {
9837                                                                         forwards.retain(|forward| {
9838                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
9839                                                                                         if pending_forward_matches_htlc(&htlc_info) {
9840                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
9841                                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
9842                                                                                                 false
9843                                                                                         } else { true }
9844                                                                                 } else { true }
9845                                                                         });
9846                                                                         !forwards.is_empty()
9847                                                                 });
9848                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
9849                                                                         if pending_forward_matches_htlc(&htlc_info) {
9850                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
9851                                                                                         &htlc.payment_hash, &monitor.get_funding_txo().0.to_channel_id());
9852                                                                                 pending_events_read.retain(|(event, _)| {
9853                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
9854                                                                                                 intercepted_id != ev_id
9855                                                                                         } else { true }
9856                                                                                 });
9857                                                                                 false
9858                                                                         } else { true }
9859                                                                 });
9860                                                         },
9861                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
9862                                                                 if let Some(preimage) = preimage_opt {
9863                                                                         let pending_events = Mutex::new(pending_events_read);
9864                                                                         // Note that we set `from_onchain` to "false" here,
9865                                                                         // deliberately keeping the pending payment around forever.
9866                                                                         // Given it should only occur when we have a channel we're
9867                                                                         // force-closing for being stale that's okay.
9868                                                                         // The alternative would be to wipe the state when claiming,
9869                                                                         // generating a `PaymentPathSuccessful` event but regenerating
9870                                                                         // it and the `PaymentSent` on every restart until the
9871                                                                         // `ChannelMonitor` is removed.
9872                                                                         let compl_action =
9873                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
9874                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
9875                                                                                         counterparty_node_id: path.hops[0].pubkey,
9876                                                                                 };
9877                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
9878                                                                                 path, false, compl_action, &pending_events, &args.logger);
9879                                                                         pending_events_read = pending_events.into_inner().unwrap();
9880                                                                 }
9881                                                         },
9882                                                 }
9883                                         }
9884                                 }
9885
9886                                 // Whether the downstream channel was closed or not, try to re-apply any payment
9887                                 // preimages from it which may be needed in upstream channels for forwarded
9888                                 // payments.
9889                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
9890                                         .into_iter()
9891                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
9892                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
9893                                                         if let Some(payment_preimage) = preimage_opt {
9894                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
9895                                                                         // Check if `counterparty_opt.is_none()` to see if the
9896                                                                         // downstream chan is closed (because we don't have a
9897                                                                         // channel_id -> peer map entry).
9898                                                                         counterparty_opt.is_none(),
9899                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
9900                                                                         monitor.get_funding_txo().0))
9901                                                         } else { None }
9902                                                 } else {
9903                                                         // If it was an outbound payment, we've handled it above - if a preimage
9904                                                         // came in and we persisted the `ChannelManager` we either handled it and
9905                                                         // are good to go or the channel force-closed - we don't have to handle the
9906                                                         // channel still live case here.
9907                                                         None
9908                                                 }
9909                                         });
9910                                 for tuple in outbound_claimed_htlcs_iter {
9911                                         pending_claims_to_replay.push(tuple);
9912                                 }
9913                         }
9914                 }
9915
9916                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
9917                         // If we have pending HTLCs to forward, assume we either dropped a
9918                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
9919                         // shut down before the timer hit. Either way, set the time_forwardable to a small
9920                         // constant as enough time has likely passed that we should simply handle the forwards
9921                         // now, or at least after the user gets a chance to reconnect to our peers.
9922                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
9923                                 time_forwardable: Duration::from_secs(2),
9924                         }, None));
9925                 }
9926
9927                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
9928                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
9929
9930                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
9931                 if let Some(purposes) = claimable_htlc_purposes {
9932                         if purposes.len() != claimable_htlcs_list.len() {
9933                                 return Err(DecodeError::InvalidValue);
9934                         }
9935                         if let Some(onion_fields) = claimable_htlc_onion_fields {
9936                                 if onion_fields.len() != claimable_htlcs_list.len() {
9937                                         return Err(DecodeError::InvalidValue);
9938                                 }
9939                                 for (purpose, (onion, (payment_hash, htlcs))) in
9940                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
9941                                 {
9942                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
9943                                                 purpose, htlcs, onion_fields: onion,
9944                                         });
9945                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
9946                                 }
9947                         } else {
9948                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
9949                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
9950                                                 purpose, htlcs, onion_fields: None,
9951                                         });
9952                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
9953                                 }
9954                         }
9955                 } else {
9956                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
9957                         // include a `_legacy_hop_data` in the `OnionPayload`.
9958                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
9959                                 if htlcs.is_empty() {
9960                                         return Err(DecodeError::InvalidValue);
9961                                 }
9962                                 let purpose = match &htlcs[0].onion_payload {
9963                                         OnionPayload::Invoice { _legacy_hop_data } => {
9964                                                 if let Some(hop_data) = _legacy_hop_data {
9965                                                         events::PaymentPurpose::InvoicePayment {
9966                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
9967                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
9968                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
9969                                                                                 Ok((payment_preimage, _)) => payment_preimage,
9970                                                                                 Err(()) => {
9971                                                                                         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);
9972                                                                                         return Err(DecodeError::InvalidValue);
9973                                                                                 }
9974                                                                         }
9975                                                                 },
9976                                                                 payment_secret: hop_data.payment_secret,
9977                                                         }
9978                                                 } else { return Err(DecodeError::InvalidValue); }
9979                                         },
9980                                         OnionPayload::Spontaneous(payment_preimage) =>
9981                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
9982                                 };
9983                                 claimable_payments.insert(payment_hash, ClaimablePayment {
9984                                         purpose, htlcs, onion_fields: None,
9985                                 });
9986                         }
9987                 }
9988
9989                 let mut secp_ctx = Secp256k1::new();
9990                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
9991
9992                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
9993                         Ok(key) => key,
9994                         Err(()) => return Err(DecodeError::InvalidValue)
9995                 };
9996                 if let Some(network_pubkey) = received_network_pubkey {
9997                         if network_pubkey != our_network_pubkey {
9998                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
9999                                 return Err(DecodeError::InvalidValue);
10000                         }
10001                 }
10002
10003                 let mut outbound_scid_aliases = HashSet::new();
10004                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10005                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10006                         let peer_state = &mut *peer_state_lock;
10007                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
10008                                 if let ChannelPhase::Funded(chan) = phase {
10009                                         if chan.context.outbound_scid_alias() == 0 {
10010                                                 let mut outbound_scid_alias;
10011                                                 loop {
10012                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
10013                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
10014                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
10015                                                 }
10016                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
10017                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
10018                                                 // Note that in rare cases its possible to hit this while reading an older
10019                                                 // channel if we just happened to pick a colliding outbound alias above.
10020                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10021                                                 return Err(DecodeError::InvalidValue);
10022                                         }
10023                                         if chan.context.is_usable() {
10024                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
10025                                                         // Note that in rare cases its possible to hit this while reading an older
10026                                                         // channel if we just happened to pick a colliding outbound alias above.
10027                                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
10028                                                         return Err(DecodeError::InvalidValue);
10029                                                 }
10030                                         }
10031                                 } else {
10032                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10033                                         // created in this `channel_by_id` map.
10034                                         debug_assert!(false);
10035                                         return Err(DecodeError::InvalidValue);
10036                                 }
10037                         }
10038                 }
10039
10040                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
10041
10042                 for (_, monitor) in args.channel_monitors.iter() {
10043                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
10044                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
10045                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
10046                                         let mut claimable_amt_msat = 0;
10047                                         let mut receiver_node_id = Some(our_network_pubkey);
10048                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
10049                                         if phantom_shared_secret.is_some() {
10050                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
10051                                                         .expect("Failed to get node_id for phantom node recipient");
10052                                                 receiver_node_id = Some(phantom_pubkey)
10053                                         }
10054                                         for claimable_htlc in &payment.htlcs {
10055                                                 claimable_amt_msat += claimable_htlc.value;
10056
10057                                                 // Add a holding-cell claim of the payment to the Channel, which should be
10058                                                 // applied ~immediately on peer reconnection. Because it won't generate a
10059                                                 // new commitment transaction we can just provide the payment preimage to
10060                                                 // the corresponding ChannelMonitor and nothing else.
10061                                                 //
10062                                                 // We do so directly instead of via the normal ChannelMonitor update
10063                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
10064                                                 // we're not allowed to call it directly yet. Further, we do the update
10065                                                 // without incrementing the ChannelMonitor update ID as there isn't any
10066                                                 // reason to.
10067                                                 // If we were to generate a new ChannelMonitor update ID here and then
10068                                                 // crash before the user finishes block connect we'd end up force-closing
10069                                                 // this channel as well. On the flip side, there's no harm in restarting
10070                                                 // without the new monitor persisted - we'll end up right back here on
10071                                                 // restart.
10072                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
10073                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
10074                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
10075                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10076                                                         let peer_state = &mut *peer_state_lock;
10077                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
10078                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
10079                                                         }
10080                                                 }
10081                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
10082                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
10083                                                 }
10084                                         }
10085                                         pending_events_read.push_back((events::Event::PaymentClaimed {
10086                                                 receiver_node_id,
10087                                                 payment_hash,
10088                                                 purpose: payment.purpose,
10089                                                 amount_msat: claimable_amt_msat,
10090                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
10091                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
10092                                         }, None));
10093                                 }
10094                         }
10095                 }
10096
10097                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
10098                         if let Some(peer_state) = per_peer_state.get(&node_id) {
10099                                 for (_, actions) in monitor_update_blocked_actions.iter() {
10100                                         for action in actions.iter() {
10101                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
10102                                                         downstream_counterparty_and_funding_outpoint:
10103                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
10104                                                 } = action {
10105                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
10106                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
10107                                                                         .entry(blocked_channel_outpoint.to_channel_id())
10108                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
10109                                                         } else {
10110                                                                 // If the channel we were blocking has closed, we don't need to
10111                                                                 // worry about it - the blocked monitor update should never have
10112                                                                 // been released from the `Channel` object so it can't have
10113                                                                 // completed, and if the channel closed there's no reason to bother
10114                                                                 // anymore.
10115                                                         }
10116                                                 }
10117                                         }
10118                                 }
10119                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
10120                         } else {
10121                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
10122                                 return Err(DecodeError::InvalidValue);
10123                         }
10124                 }
10125
10126                 let channel_manager = ChannelManager {
10127                         chain_hash,
10128                         fee_estimator: bounded_fee_estimator,
10129                         chain_monitor: args.chain_monitor,
10130                         tx_broadcaster: args.tx_broadcaster,
10131                         router: args.router,
10132
10133                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
10134
10135                         inbound_payment_key: expanded_inbound_key,
10136                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
10137                         pending_outbound_payments: pending_outbounds,
10138                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
10139
10140                         forward_htlcs: Mutex::new(forward_htlcs),
10141                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
10142                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
10143                         id_to_peer: Mutex::new(id_to_peer),
10144                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
10145                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
10146
10147                         probing_cookie_secret: probing_cookie_secret.unwrap(),
10148
10149                         our_network_pubkey,
10150                         secp_ctx,
10151
10152                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
10153
10154                         per_peer_state: FairRwLock::new(per_peer_state),
10155
10156                         pending_events: Mutex::new(pending_events_read),
10157                         pending_events_processor: AtomicBool::new(false),
10158                         pending_background_events: Mutex::new(pending_background_events),
10159                         total_consistency_lock: RwLock::new(()),
10160                         background_events_processed_since_startup: AtomicBool::new(false),
10161
10162                         event_persist_notifier: Notifier::new(),
10163                         needs_persist_flag: AtomicBool::new(false),
10164
10165                         funding_batch_states: Mutex::new(BTreeMap::new()),
10166
10167                         entropy_source: args.entropy_source,
10168                         node_signer: args.node_signer,
10169                         signer_provider: args.signer_provider,
10170
10171                         logger: args.logger,
10172                         default_configuration: args.default_config,
10173                 };
10174
10175                 for htlc_source in failed_htlcs.drain(..) {
10176                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
10177                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
10178                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
10179                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
10180                 }
10181
10182                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding) in pending_claims_to_replay {
10183                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
10184                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
10185                         // channel is closed we just assume that it probably came from an on-chain claim.
10186                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
10187                                 downstream_closed, downstream_node_id, downstream_funding);
10188                 }
10189
10190                 //TODO: Broadcast channel update for closed channels, but only after we've made a
10191                 //connection or two.
10192
10193                 Ok((best_block_hash.clone(), channel_manager))
10194         }
10195 }
10196
10197 #[cfg(test)]
10198 mod tests {
10199         use bitcoin::hashes::Hash;
10200         use bitcoin::hashes::sha256::Hash as Sha256;
10201         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10202         use core::sync::atomic::Ordering;
10203         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
10204         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
10205         use crate::ln::ChannelId;
10206         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
10207         use crate::ln::functional_test_utils::*;
10208         use crate::ln::msgs::{self, ErrorAction};
10209         use crate::ln::msgs::ChannelMessageHandler;
10210         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
10211         use crate::util::errors::APIError;
10212         use crate::util::test_utils;
10213         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
10214         use crate::sign::EntropySource;
10215
10216         #[test]
10217         fn test_notify_limits() {
10218                 // Check that a few cases which don't require the persistence of a new ChannelManager,
10219                 // indeed, do not cause the persistence of a new ChannelManager.
10220                 let chanmon_cfgs = create_chanmon_cfgs(3);
10221                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10222                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10223                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10224
10225                 // All nodes start with a persistable update pending as `create_network` connects each node
10226                 // with all other nodes to make most tests simpler.
10227                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10228                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10229                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10230
10231                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10232
10233                 // We check that the channel info nodes have doesn't change too early, even though we try
10234                 // to connect messages with new values
10235                 chan.0.contents.fee_base_msat *= 2;
10236                 chan.1.contents.fee_base_msat *= 2;
10237                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
10238                         &nodes[1].node.get_our_node_id()).pop().unwrap();
10239                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
10240                         &nodes[0].node.get_our_node_id()).pop().unwrap();
10241
10242                 // The first two nodes (which opened a channel) should now require fresh persistence
10243                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10244                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10245                 // ... but the last node should not.
10246                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10247                 // After persisting the first two nodes they should no longer need fresh persistence.
10248                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10249                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10250
10251                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
10252                 // about the channel.
10253                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
10254                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
10255                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
10256
10257                 // The nodes which are a party to the channel should also ignore messages from unrelated
10258                 // parties.
10259                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10260                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10261                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
10262                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
10263                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10264                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10265
10266                 // At this point the channel info given by peers should still be the same.
10267                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10268                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10269
10270                 // An earlier version of handle_channel_update didn't check the directionality of the
10271                 // update message and would always update the local fee info, even if our peer was
10272                 // (spuriously) forwarding us our own channel_update.
10273                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
10274                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
10275                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
10276
10277                 // First deliver each peers' own message, checking that the node doesn't need to be
10278                 // persisted and that its channel info remains the same.
10279                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
10280                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
10281                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10282                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10283                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
10284                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
10285
10286                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
10287                 // the channel info has updated.
10288                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
10289                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
10290                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
10291                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
10292                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
10293                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
10294         }
10295
10296         #[test]
10297         fn test_keysend_dup_hash_partial_mpp() {
10298                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
10299                 // expected.
10300                 let chanmon_cfgs = create_chanmon_cfgs(2);
10301                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10302                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10303                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10304                 create_announced_chan_between_nodes(&nodes, 0, 1);
10305
10306                 // First, send a partial MPP payment.
10307                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
10308                 let mut mpp_route = route.clone();
10309                 mpp_route.paths.push(mpp_route.paths[0].clone());
10310
10311                 let payment_id = PaymentId([42; 32]);
10312                 // Use the utility function send_payment_along_path to send the payment with MPP data which
10313                 // indicates there are more HTLCs coming.
10314                 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.
10315                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
10316                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
10317                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
10318                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
10319                 check_added_monitors!(nodes[0], 1);
10320                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10321                 assert_eq!(events.len(), 1);
10322                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10323
10324                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
10325                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10326                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10327                 check_added_monitors!(nodes[0], 1);
10328                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10329                 assert_eq!(events.len(), 1);
10330                 let ev = events.drain(..).next().unwrap();
10331                 let payment_event = SendEvent::from_event(ev);
10332                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10333                 check_added_monitors!(nodes[1], 0);
10334                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10335                 expect_pending_htlcs_forwardable!(nodes[1]);
10336                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
10337                 check_added_monitors!(nodes[1], 1);
10338                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10339                 assert!(updates.update_add_htlcs.is_empty());
10340                 assert!(updates.update_fulfill_htlcs.is_empty());
10341                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10342                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10343                 assert!(updates.update_fee.is_none());
10344                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10345                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10346                 expect_payment_failed!(nodes[0], our_payment_hash, true);
10347
10348                 // Send the second half of the original MPP payment.
10349                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
10350                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
10351                 check_added_monitors!(nodes[0], 1);
10352                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10353                 assert_eq!(events.len(), 1);
10354                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
10355
10356                 // Claim the full MPP payment. Note that we can't use a test utility like
10357                 // claim_funds_along_route because the ordering of the messages causes the second half of the
10358                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
10359                 // lightning messages manually.
10360                 nodes[1].node.claim_funds(payment_preimage);
10361                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
10362                 check_added_monitors!(nodes[1], 2);
10363
10364                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10365                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
10366                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
10367                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
10368                 check_added_monitors!(nodes[0], 1);
10369                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10370                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
10371                 check_added_monitors!(nodes[1], 1);
10372                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10373                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
10374                 check_added_monitors!(nodes[1], 1);
10375                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10376                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
10377                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
10378                 check_added_monitors!(nodes[0], 1);
10379                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10380                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
10381                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10382                 check_added_monitors!(nodes[0], 1);
10383                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
10384                 check_added_monitors!(nodes[1], 1);
10385                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
10386                 check_added_monitors!(nodes[1], 1);
10387                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
10388                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
10389                 check_added_monitors!(nodes[0], 1);
10390
10391                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
10392                 // path's success and a PaymentPathSuccessful event for each path's success.
10393                 let events = nodes[0].node.get_and_clear_pending_events();
10394                 assert_eq!(events.len(), 2);
10395                 match events[0] {
10396                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10397                                 assert_eq!(payment_id, *actual_payment_id);
10398                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10399                                 assert_eq!(route.paths[0], *path);
10400                         },
10401                         _ => panic!("Unexpected event"),
10402                 }
10403                 match events[1] {
10404                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
10405                                 assert_eq!(payment_id, *actual_payment_id);
10406                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
10407                                 assert_eq!(route.paths[0], *path);
10408                         },
10409                         _ => panic!("Unexpected event"),
10410                 }
10411         }
10412
10413         #[test]
10414         fn test_keysend_dup_payment_hash() {
10415                 do_test_keysend_dup_payment_hash(false);
10416                 do_test_keysend_dup_payment_hash(true);
10417         }
10418
10419         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
10420                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
10421                 //      outbound regular payment fails as expected.
10422                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
10423                 //      fails as expected.
10424                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
10425                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
10426                 //      reject MPP keysend payments, since in this case where the payment has no payment
10427                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
10428                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
10429                 //      payment secrets and reject otherwise.
10430                 let chanmon_cfgs = create_chanmon_cfgs(2);
10431                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10432                 let mut mpp_keysend_cfg = test_default_channel_config();
10433                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
10434                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
10435                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10436                 create_announced_chan_between_nodes(&nodes, 0, 1);
10437                 let scorer = test_utils::TestScorer::new();
10438                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10439
10440                 // To start (1), send a regular payment but don't claim it.
10441                 let expected_route = [&nodes[1]];
10442                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
10443
10444                 // Next, attempt a keysend payment and make sure it fails.
10445                 let route_params = RouteParameters::from_payment_params_and_value(
10446                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
10447                         TEST_FINAL_CLTV, false), 100_000);
10448                 let route = find_route(
10449                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10450                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10451                 ).unwrap();
10452                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10453                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
10454                 check_added_monitors!(nodes[0], 1);
10455                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10456                 assert_eq!(events.len(), 1);
10457                 let ev = events.drain(..).next().unwrap();
10458                 let payment_event = SendEvent::from_event(ev);
10459                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10460                 check_added_monitors!(nodes[1], 0);
10461                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10462                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
10463                 // fails), the second will process the resulting failure and fail the HTLC backward
10464                 expect_pending_htlcs_forwardable!(nodes[1]);
10465                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10466                 check_added_monitors!(nodes[1], 1);
10467                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10468                 assert!(updates.update_add_htlcs.is_empty());
10469                 assert!(updates.update_fulfill_htlcs.is_empty());
10470                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10471                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10472                 assert!(updates.update_fee.is_none());
10473                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10474                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10475                 expect_payment_failed!(nodes[0], payment_hash, true);
10476
10477                 // Finally, claim the original payment.
10478                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10479
10480                 // To start (2), send a keysend payment but don't claim it.
10481                 let payment_preimage = PaymentPreimage([42; 32]);
10482                 let route = find_route(
10483                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10484                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10485                 ).unwrap();
10486                 let payment_hash = 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 event = events.pop().unwrap();
10492                 let path = vec![&nodes[1]];
10493                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10494
10495                 // Next, attempt a regular payment and make sure it fails.
10496                 let payment_secret = PaymentSecret([43; 32]);
10497                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10498                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10499                 check_added_monitors!(nodes[0], 1);
10500                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10501                 assert_eq!(events.len(), 1);
10502                 let ev = events.drain(..).next().unwrap();
10503                 let payment_event = SendEvent::from_event(ev);
10504                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10505                 check_added_monitors!(nodes[1], 0);
10506                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10507                 expect_pending_htlcs_forwardable!(nodes[1]);
10508                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10509                 check_added_monitors!(nodes[1], 1);
10510                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10511                 assert!(updates.update_add_htlcs.is_empty());
10512                 assert!(updates.update_fulfill_htlcs.is_empty());
10513                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10514                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10515                 assert!(updates.update_fee.is_none());
10516                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10517                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10518                 expect_payment_failed!(nodes[0], payment_hash, true);
10519
10520                 // Finally, succeed the keysend payment.
10521                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10522
10523                 // To start (3), send a keysend payment but don't claim it.
10524                 let payment_id_1 = PaymentId([44; 32]);
10525                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10526                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
10527                 check_added_monitors!(nodes[0], 1);
10528                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10529                 assert_eq!(events.len(), 1);
10530                 let event = events.pop().unwrap();
10531                 let path = vec![&nodes[1]];
10532                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
10533
10534                 // Next, attempt a keysend payment and make sure it fails.
10535                 let route_params = RouteParameters::from_payment_params_and_value(
10536                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
10537                         100_000
10538                 );
10539                 let route = find_route(
10540                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
10541                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10542                 ).unwrap();
10543                 let payment_id_2 = PaymentId([45; 32]);
10544                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
10545                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
10546                 check_added_monitors!(nodes[0], 1);
10547                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10548                 assert_eq!(events.len(), 1);
10549                 let ev = events.drain(..).next().unwrap();
10550                 let payment_event = SendEvent::from_event(ev);
10551                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10552                 check_added_monitors!(nodes[1], 0);
10553                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10554                 expect_pending_htlcs_forwardable!(nodes[1]);
10555                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10556                 check_added_monitors!(nodes[1], 1);
10557                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10558                 assert!(updates.update_add_htlcs.is_empty());
10559                 assert!(updates.update_fulfill_htlcs.is_empty());
10560                 assert_eq!(updates.update_fail_htlcs.len(), 1);
10561                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10562                 assert!(updates.update_fee.is_none());
10563                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
10564                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
10565                 expect_payment_failed!(nodes[0], payment_hash, true);
10566
10567                 // Finally, claim the original payment.
10568                 claim_payment(&nodes[0], &expected_route, payment_preimage);
10569         }
10570
10571         #[test]
10572         fn test_keysend_hash_mismatch() {
10573                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
10574                 // preimage doesn't match the msg's payment hash.
10575                 let chanmon_cfgs = create_chanmon_cfgs(2);
10576                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10577                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10578                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10579
10580                 let payer_pubkey = nodes[0].node.get_our_node_id();
10581                 let payee_pubkey = nodes[1].node.get_our_node_id();
10582
10583                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10584                 let route_params = RouteParameters::from_payment_params_and_value(
10585                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10586                 let network_graph = nodes[0].network_graph.clone();
10587                 let first_hops = nodes[0].node.list_usable_channels();
10588                 let scorer = test_utils::TestScorer::new();
10589                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10590                 let route = find_route(
10591                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10592                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10593                 ).unwrap();
10594
10595                 let test_preimage = PaymentPreimage([42; 32]);
10596                 let mismatch_payment_hash = PaymentHash([43; 32]);
10597                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
10598                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
10599                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
10600                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
10601                 check_added_monitors!(nodes[0], 1);
10602
10603                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10604                 assert_eq!(updates.update_add_htlcs.len(), 1);
10605                 assert!(updates.update_fulfill_htlcs.is_empty());
10606                 assert!(updates.update_fail_htlcs.is_empty());
10607                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10608                 assert!(updates.update_fee.is_none());
10609                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
10610
10611                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
10612         }
10613
10614         #[test]
10615         fn test_keysend_msg_with_secret_err() {
10616                 // Test that we error as expected if we receive a keysend payment that includes a payment
10617                 // secret when we don't support MPP keysend.
10618                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
10619                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
10620                 let chanmon_cfgs = create_chanmon_cfgs(2);
10621                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10622                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
10623                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10624
10625                 let payer_pubkey = nodes[0].node.get_our_node_id();
10626                 let payee_pubkey = nodes[1].node.get_our_node_id();
10627
10628                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
10629                 let route_params = RouteParameters::from_payment_params_and_value(
10630                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
10631                 let network_graph = nodes[0].network_graph.clone();
10632                 let first_hops = nodes[0].node.list_usable_channels();
10633                 let scorer = test_utils::TestScorer::new();
10634                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
10635                 let route = find_route(
10636                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
10637                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
10638                 ).unwrap();
10639
10640                 let test_preimage = PaymentPreimage([42; 32]);
10641                 let test_secret = PaymentSecret([43; 32]);
10642                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
10643                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
10644                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
10645                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
10646                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
10647                         PaymentId(payment_hash.0), None, session_privs).unwrap();
10648                 check_added_monitors!(nodes[0], 1);
10649
10650                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
10651                 assert_eq!(updates.update_add_htlcs.len(), 1);
10652                 assert!(updates.update_fulfill_htlcs.is_empty());
10653                 assert!(updates.update_fail_htlcs.is_empty());
10654                 assert!(updates.update_fail_malformed_htlcs.is_empty());
10655                 assert!(updates.update_fee.is_none());
10656                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
10657
10658                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
10659         }
10660
10661         #[test]
10662         fn test_multi_hop_missing_secret() {
10663                 let chanmon_cfgs = create_chanmon_cfgs(4);
10664                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10665                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10666                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10667
10668                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
10669                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
10670                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
10671                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
10672
10673                 // Marshall an MPP route.
10674                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
10675                 let path = route.paths[0].clone();
10676                 route.paths.push(path);
10677                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
10678                 route.paths[0].hops[0].short_channel_id = chan_1_id;
10679                 route.paths[0].hops[1].short_channel_id = chan_3_id;
10680                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
10681                 route.paths[1].hops[0].short_channel_id = chan_2_id;
10682                 route.paths[1].hops[1].short_channel_id = chan_4_id;
10683
10684                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
10685                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
10686                 .unwrap_err() {
10687                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
10688                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
10689                         },
10690                         _ => panic!("unexpected error")
10691                 }
10692         }
10693
10694         #[test]
10695         fn test_drop_disconnected_peers_when_removing_channels() {
10696                 let chanmon_cfgs = create_chanmon_cfgs(2);
10697                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10698                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10699                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10700
10701                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
10702
10703                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10704                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10705
10706                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
10707                 check_closed_broadcast!(nodes[0], true);
10708                 check_added_monitors!(nodes[0], 1);
10709                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
10710
10711                 {
10712                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
10713                         // disconnected and the channel between has been force closed.
10714                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10715                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
10716                         assert_eq!(nodes_0_per_peer_state.len(), 1);
10717                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
10718                 }
10719
10720                 nodes[0].node.timer_tick_occurred();
10721
10722                 {
10723                         // Assert that nodes[1] has now been removed.
10724                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
10725                 }
10726         }
10727
10728         #[test]
10729         fn bad_inbound_payment_hash() {
10730                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
10731                 let chanmon_cfgs = create_chanmon_cfgs(2);
10732                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10733                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10734                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10735
10736                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
10737                 let payment_data = msgs::FinalOnionHopData {
10738                         payment_secret,
10739                         total_msat: 100_000,
10740                 };
10741
10742                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
10743                 // payment verification fails as expected.
10744                 let mut bad_payment_hash = payment_hash.clone();
10745                 bad_payment_hash.0[0] += 1;
10746                 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) {
10747                         Ok(_) => panic!("Unexpected ok"),
10748                         Err(()) => {
10749                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
10750                         }
10751                 }
10752
10753                 // Check that using the original payment hash succeeds.
10754                 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());
10755         }
10756
10757         #[test]
10758         fn test_id_to_peer_coverage() {
10759                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
10760                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
10761                 // the channel is successfully closed.
10762                 let chanmon_cfgs = create_chanmon_cfgs(2);
10763                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10764                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10765                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10766
10767                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10768                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10769                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
10770                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10771                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
10772
10773                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10774                 let channel_id = ChannelId::from_bytes(tx.txid().into_inner());
10775                 {
10776                         // Ensure that the `id_to_peer` map is empty until either party has received the
10777                         // funding transaction, and have the real `channel_id`.
10778                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
10779                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10780                 }
10781
10782                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10783                 {
10784                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
10785                         // as it has the funding transaction.
10786                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10787                         assert_eq!(nodes_0_lock.len(), 1);
10788                         assert!(nodes_0_lock.contains_key(&channel_id));
10789                 }
10790
10791                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10792
10793                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10794
10795                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
10796                 {
10797                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10798                         assert_eq!(nodes_0_lock.len(), 1);
10799                         assert!(nodes_0_lock.contains_key(&channel_id));
10800                 }
10801                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10802
10803                 {
10804                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
10805                         // as it has the funding transaction.
10806                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
10807                         assert_eq!(nodes_1_lock.len(), 1);
10808                         assert!(nodes_1_lock.contains_key(&channel_id));
10809                 }
10810                 check_added_monitors!(nodes[1], 1);
10811                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10812                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
10813                 check_added_monitors!(nodes[0], 1);
10814                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
10815                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10816                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10817                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
10818
10819                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
10820                 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()));
10821                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
10822                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
10823
10824                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
10825                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
10826                 {
10827                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
10828                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
10829                         // fee for the closing transaction has been negotiated and the parties has the other
10830                         // party's signature for the fee negotiated closing transaction.)
10831                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
10832                         assert_eq!(nodes_0_lock.len(), 1);
10833                         assert!(nodes_0_lock.contains_key(&channel_id));
10834                 }
10835
10836                 {
10837                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
10838                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
10839                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
10840                         // kept in the `nodes[1]`'s `id_to_peer` map.
10841                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
10842                         assert_eq!(nodes_1_lock.len(), 1);
10843                         assert!(nodes_1_lock.contains_key(&channel_id));
10844                 }
10845
10846                 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()));
10847                 {
10848                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
10849                         // therefore has all it needs to fully close the channel (both signatures for the
10850                         // closing transaction).
10851                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
10852                         // fully closed by `nodes[0]`.
10853                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
10854
10855                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
10856                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
10857                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
10858                         assert_eq!(nodes_1_lock.len(), 1);
10859                         assert!(nodes_1_lock.contains_key(&channel_id));
10860                 }
10861
10862                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
10863
10864                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
10865                 {
10866                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
10867                         // they both have everything required to fully close the channel.
10868                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10869                 }
10870                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
10871
10872                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
10873                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
10874         }
10875
10876         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
10877                 let expected_message = format!("Not connected to node: {}", expected_public_key);
10878                 check_api_error_message(expected_message, res_err)
10879         }
10880
10881         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
10882                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
10883                 check_api_error_message(expected_message, res_err)
10884         }
10885
10886         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
10887                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
10888                 check_api_error_message(expected_message, res_err)
10889         }
10890
10891         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
10892                 let expected_message = "No such channel awaiting to be accepted.".to_string();
10893                 check_api_error_message(expected_message, res_err)
10894         }
10895
10896         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
10897                 match res_err {
10898                         Err(APIError::APIMisuseError { err }) => {
10899                                 assert_eq!(err, expected_err_message);
10900                         },
10901                         Err(APIError::ChannelUnavailable { err }) => {
10902                                 assert_eq!(err, expected_err_message);
10903                         },
10904                         Ok(_) => panic!("Unexpected Ok"),
10905                         Err(_) => panic!("Unexpected Error"),
10906                 }
10907         }
10908
10909         #[test]
10910         fn test_api_calls_with_unkown_counterparty_node() {
10911                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
10912                 // expected if the `counterparty_node_id` is an unkown peer in the
10913                 // `ChannelManager::per_peer_state` map.
10914                 let chanmon_cfg = create_chanmon_cfgs(2);
10915                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
10916                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
10917                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
10918
10919                 // Dummy values
10920                 let channel_id = ChannelId::from_bytes([4; 32]);
10921                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
10922                 let intercept_id = InterceptId([0; 32]);
10923
10924                 // Test the API functions.
10925                 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);
10926
10927                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
10928
10929                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
10930
10931                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
10932
10933                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
10934
10935                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
10936
10937                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
10938         }
10939
10940         #[test]
10941         fn test_api_calls_with_unavailable_channel() {
10942                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
10943                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
10944                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
10945                 // the given `channel_id`.
10946                 let chanmon_cfg = create_chanmon_cfgs(2);
10947                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
10948                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
10949                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
10950
10951                 let counterparty_node_id = nodes[1].node.get_our_node_id();
10952
10953                 // Dummy values
10954                 let channel_id = ChannelId::from_bytes([4; 32]);
10955
10956                 // Test the API functions.
10957                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
10958
10959                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
10960
10961                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
10962
10963                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
10964
10965                 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);
10966
10967                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
10968         }
10969
10970         #[test]
10971         fn test_connection_limiting() {
10972                 // Test that we limit un-channel'd peers and un-funded channels properly.
10973                 let chanmon_cfgs = create_chanmon_cfgs(2);
10974                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10975                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10976                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10977
10978                 // Note that create_network connects the nodes together for us
10979
10980                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10981                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10982
10983                 let mut funding_tx = None;
10984                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
10985                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10986                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10987
10988                         if idx == 0 {
10989                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
10990                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
10991                                 funding_tx = Some(tx.clone());
10992                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
10993                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10994
10995                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
10996                                 check_added_monitors!(nodes[1], 1);
10997                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10998
10999                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11000
11001                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11002                                 check_added_monitors!(nodes[0], 1);
11003                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11004                         }
11005                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11006                 }
11007
11008                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
11009                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11010                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11011                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11012                         open_channel_msg.temporary_channel_id);
11013
11014                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
11015                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
11016                 // limit.
11017                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
11018                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
11019                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11020                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11021                         peer_pks.push(random_pk);
11022                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11023                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11024                         }, true).unwrap();
11025                 }
11026                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11027                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11028                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11029                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11030                 }, true).unwrap_err();
11031
11032                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
11033                 // them if we have too many un-channel'd peers.
11034                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11035                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
11036                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
11037                 for ev in chan_closed_events {
11038                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
11039                 }
11040                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11041                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11042                 }, true).unwrap();
11043                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11044                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11045                 }, true).unwrap_err();
11046
11047                 // but of course if the connection is outbound its allowed...
11048                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11049                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11050                 }, false).unwrap();
11051                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11052
11053                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
11054                 // Even though we accept one more connection from new peers, we won't actually let them
11055                 // open channels.
11056                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
11057                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11058                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
11059                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
11060                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11061                 }
11062                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11063                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11064                         open_channel_msg.temporary_channel_id);
11065
11066                 // Of course, however, outbound channels are always allowed
11067                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
11068                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
11069
11070                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
11071                 // "protected" and can connect again.
11072                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
11073                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11074                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11075                 }, true).unwrap();
11076                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
11077
11078                 // Further, because the first channel was funded, we can open another channel with
11079                 // last_random_pk.
11080                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11081                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11082         }
11083
11084         #[test]
11085         fn test_outbound_chans_unlimited() {
11086                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
11087                 let chanmon_cfgs = create_chanmon_cfgs(2);
11088                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11089                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11090                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11091
11092                 // Note that create_network connects the nodes together for us
11093
11094                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11095                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11096
11097                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
11098                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11099                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11100                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11101                 }
11102
11103                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
11104                 // rejected.
11105                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11106                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11107                         open_channel_msg.temporary_channel_id);
11108
11109                 // but we can still open an outbound channel.
11110                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11111                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
11112
11113                 // but even with such an outbound channel, additional inbound channels will still fail.
11114                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11115                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11116                         open_channel_msg.temporary_channel_id);
11117         }
11118
11119         #[test]
11120         fn test_0conf_limiting() {
11121                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11122                 // flag set and (sometimes) accept channels as 0conf.
11123                 let chanmon_cfgs = create_chanmon_cfgs(2);
11124                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11125                 let mut settings = test_default_channel_config();
11126                 settings.manually_accept_inbound_channels = true;
11127                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
11128                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11129
11130                 // Note that create_network connects the nodes together for us
11131
11132                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11133                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11134
11135                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
11136                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
11137                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11138                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11139                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
11140                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11141                         }, true).unwrap();
11142
11143                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
11144                         let events = nodes[1].node.get_and_clear_pending_events();
11145                         match events[0] {
11146                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11147                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
11148                                 }
11149                                 _ => panic!("Unexpected event"),
11150                         }
11151                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
11152                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
11153                 }
11154
11155                 // If we try to accept a channel from another peer non-0conf it will fail.
11156                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
11157                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
11158                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
11159                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11160                 }, true).unwrap();
11161                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11162                 let events = nodes[1].node.get_and_clear_pending_events();
11163                 match events[0] {
11164                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11165                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
11166                                         Err(APIError::APIMisuseError { err }) =>
11167                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
11168                                         _ => panic!(),
11169                                 }
11170                         }
11171                         _ => panic!("Unexpected event"),
11172                 }
11173                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
11174                         open_channel_msg.temporary_channel_id);
11175
11176                 // ...however if we accept the same channel 0conf it should work just fine.
11177                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
11178                 let events = nodes[1].node.get_and_clear_pending_events();
11179                 match events[0] {
11180                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11181                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
11182                         }
11183                         _ => panic!("Unexpected event"),
11184                 }
11185                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
11186         }
11187
11188         #[test]
11189         fn reject_excessively_underpaying_htlcs() {
11190                 let chanmon_cfg = create_chanmon_cfgs(1);
11191                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11192                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11193                 let node = create_network(1, &node_cfg, &node_chanmgr);
11194                 let sender_intended_amt_msat = 100;
11195                 let extra_fee_msat = 10;
11196                 let hop_data = msgs::InboundOnionPayload::Receive {
11197                         amt_msat: 100,
11198                         outgoing_cltv_value: 42,
11199                         payment_metadata: None,
11200                         keysend_preimage: None,
11201                         payment_data: Some(msgs::FinalOnionHopData {
11202                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11203                         }),
11204                         custom_tlvs: Vec::new(),
11205                 };
11206                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
11207                 // intended amount, we fail the payment.
11208                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
11209                         node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11210                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat))
11211                 {
11212                         assert_eq!(err_code, 19);
11213                 } else { panic!(); }
11214
11215                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
11216                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
11217                         amt_msat: 100,
11218                         outgoing_cltv_value: 42,
11219                         payment_metadata: None,
11220                         keysend_preimage: None,
11221                         payment_data: Some(msgs::FinalOnionHopData {
11222                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
11223                         }),
11224                         custom_tlvs: Vec::new(),
11225                 };
11226                 assert!(node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
11227                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat)).is_ok());
11228         }
11229
11230         #[test]
11231         fn test_final_incorrect_cltv(){
11232                 let chanmon_cfg = create_chanmon_cfgs(1);
11233                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
11234                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
11235                 let node = create_network(1, &node_cfg, &node_chanmgr);
11236
11237                 let result = node[0].node.construct_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
11238                         amt_msat: 100,
11239                         outgoing_cltv_value: 22,
11240                         payment_metadata: None,
11241                         keysend_preimage: None,
11242                         payment_data: Some(msgs::FinalOnionHopData {
11243                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
11244                         }),
11245                         custom_tlvs: Vec::new(),
11246                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None);
11247
11248                 // Should not return an error as this condition:
11249                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
11250                 // is not satisfied.
11251                 assert!(result.is_ok());
11252         }
11253
11254         #[test]
11255         fn test_inbound_anchors_manual_acceptance() {
11256                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
11257                 // flag set and (sometimes) accept channels as 0conf.
11258                 let mut anchors_cfg = test_default_channel_config();
11259                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11260
11261                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
11262                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
11263
11264                 let chanmon_cfgs = create_chanmon_cfgs(3);
11265                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11266                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
11267                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
11268                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11269
11270                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
11271                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11272
11273                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11274                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11275                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
11276                 match &msg_events[0] {
11277                         MessageSendEvent::HandleError { node_id, action } => {
11278                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
11279                                 match action {
11280                                         ErrorAction::SendErrorMessage { msg } =>
11281                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
11282                                         _ => panic!("Unexpected error action"),
11283                                 }
11284                         }
11285                         _ => panic!("Unexpected event"),
11286                 }
11287
11288                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11289                 let events = nodes[2].node.get_and_clear_pending_events();
11290                 match events[0] {
11291                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
11292                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
11293                         _ => panic!("Unexpected event"),
11294                 }
11295                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11296         }
11297
11298         #[test]
11299         fn test_anchors_zero_fee_htlc_tx_fallback() {
11300                 // Tests that if both nodes support anchors, but the remote node does not want to accept
11301                 // anchor channels at the moment, an error it sent to the local node such that it can retry
11302                 // the channel without the anchors feature.
11303                 let chanmon_cfgs = create_chanmon_cfgs(2);
11304                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11305                 let mut anchors_config = test_default_channel_config();
11306                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
11307                 anchors_config.manually_accept_inbound_channels = true;
11308                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
11309                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11310
11311                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
11312                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11313                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
11314
11315                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11316                 let events = nodes[1].node.get_and_clear_pending_events();
11317                 match events[0] {
11318                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
11319                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
11320                         }
11321                         _ => panic!("Unexpected event"),
11322                 }
11323
11324                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
11325                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
11326
11327                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11328                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
11329
11330                 // Since nodes[1] should not have accepted the channel, it should
11331                 // not have generated any events.
11332                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
11333         }
11334
11335         #[test]
11336         fn test_update_channel_config() {
11337                 let chanmon_cfg = create_chanmon_cfgs(2);
11338                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11339                 let mut user_config = test_default_channel_config();
11340                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11341                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11342                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
11343                 let channel = &nodes[0].node.list_channels()[0];
11344
11345                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11346                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11347                 assert_eq!(events.len(), 0);
11348
11349                 user_config.channel_config.forwarding_fee_base_msat += 10;
11350                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
11351                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
11352                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11353                 assert_eq!(events.len(), 1);
11354                 match &events[0] {
11355                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11356                         _ => panic!("expected BroadcastChannelUpdate event"),
11357                 }
11358
11359                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
11360                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11361                 assert_eq!(events.len(), 0);
11362
11363                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
11364                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11365                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
11366                         ..Default::default()
11367                 }).unwrap();
11368                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11369                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11370                 assert_eq!(events.len(), 1);
11371                 match &events[0] {
11372                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11373                         _ => panic!("expected BroadcastChannelUpdate event"),
11374                 }
11375
11376                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
11377                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
11378                         forwarding_fee_proportional_millionths: Some(new_fee),
11379                         ..Default::default()
11380                 }).unwrap();
11381                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
11382                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
11383                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11384                 assert_eq!(events.len(), 1);
11385                 match &events[0] {
11386                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
11387                         _ => panic!("expected BroadcastChannelUpdate event"),
11388                 }
11389
11390                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
11391                 // should be applied to ensure update atomicity as specified in the API docs.
11392                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
11393                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
11394                 let new_fee = current_fee + 100;
11395                 assert!(
11396                         matches!(
11397                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
11398                                         forwarding_fee_proportional_millionths: Some(new_fee),
11399                                         ..Default::default()
11400                                 }),
11401                                 Err(APIError::ChannelUnavailable { err: _ }),
11402                         )
11403                 );
11404                 // Check that the fee hasn't changed for the channel that exists.
11405                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
11406                 let events = nodes[0].node.get_and_clear_pending_msg_events();
11407                 assert_eq!(events.len(), 0);
11408         }
11409
11410         #[test]
11411         fn test_payment_display() {
11412                 let payment_id = PaymentId([42; 32]);
11413                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11414                 let payment_hash = PaymentHash([42; 32]);
11415                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11416                 let payment_preimage = PaymentPreimage([42; 32]);
11417                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
11418         }
11419
11420         #[test]
11421         fn test_trigger_lnd_force_close() {
11422                 let chanmon_cfg = create_chanmon_cfgs(2);
11423                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11424                 let user_config = test_default_channel_config();
11425                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
11426                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11427
11428                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
11429                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
11430                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11431                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11432                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
11433                 check_closed_broadcast(&nodes[0], 1, true);
11434                 check_added_monitors(&nodes[0], 1);
11435                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11436                 {
11437                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
11438                         assert_eq!(txn.len(), 1);
11439                         check_spends!(txn[0], funding_tx);
11440                 }
11441
11442                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
11443                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
11444                 // their side.
11445                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
11446                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
11447                 }, true).unwrap();
11448                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11449                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11450                 }, false).unwrap();
11451                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
11452                 let channel_reestablish = get_event_msg!(
11453                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
11454                 );
11455                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
11456
11457                 // Alice should respond with an error since the channel isn't known, but a bogus
11458                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
11459                 // close even if it was an lnd node.
11460                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
11461                 assert_eq!(msg_events.len(), 2);
11462                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
11463                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
11464                         assert_eq!(msg.next_local_commitment_number, 0);
11465                         assert_eq!(msg.next_remote_commitment_number, 0);
11466                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
11467                 } else { panic!() };
11468                 check_closed_broadcast(&nodes[1], 1, true);
11469                 check_added_monitors(&nodes[1], 1);
11470                 let expected_close_reason = ClosureReason::ProcessingError {
11471                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
11472                 };
11473                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
11474                 {
11475                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
11476                         assert_eq!(txn.len(), 1);
11477                         check_spends!(txn[0], funding_tx);
11478                 }
11479         }
11480 }
11481
11482 #[cfg(ldk_bench)]
11483 pub mod bench {
11484         use crate::chain::Listen;
11485         use crate::chain::chainmonitor::{ChainMonitor, Persist};
11486         use crate::sign::{KeysManager, InMemorySigner};
11487         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
11488         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
11489         use crate::ln::functional_test_utils::*;
11490         use crate::ln::msgs::{ChannelMessageHandler, Init};
11491         use crate::routing::gossip::NetworkGraph;
11492         use crate::routing::router::{PaymentParameters, RouteParameters};
11493         use crate::util::test_utils;
11494         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
11495
11496         use bitcoin::hashes::Hash;
11497         use bitcoin::hashes::sha256::Hash as Sha256;
11498         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
11499
11500         use crate::sync::{Arc, Mutex, RwLock};
11501
11502         use criterion::Criterion;
11503
11504         type Manager<'a, P> = ChannelManager<
11505                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
11506                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
11507                         &'a test_utils::TestLogger, &'a P>,
11508                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
11509                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
11510                 &'a test_utils::TestLogger>;
11511
11512         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
11513                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
11514         }
11515         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
11516                 type CM = Manager<'chan_mon_cfg, P>;
11517                 #[inline]
11518                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
11519                 #[inline]
11520                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
11521         }
11522
11523         pub fn bench_sends(bench: &mut Criterion) {
11524                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
11525         }
11526
11527         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
11528                 // Do a simple benchmark of sending a payment back and forth between two nodes.
11529                 // Note that this is unrealistic as each payment send will require at least two fsync
11530                 // calls per node.
11531                 let network = bitcoin::Network::Testnet;
11532                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
11533
11534                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
11535                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
11536                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
11537                 let scorer = RwLock::new(test_utils::TestScorer::new());
11538                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
11539
11540                 let mut config: UserConfig = Default::default();
11541                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
11542                 config.channel_handshake_config.minimum_depth = 1;
11543
11544                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
11545                 let seed_a = [1u8; 32];
11546                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
11547                 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 {
11548                         network,
11549                         best_block: BestBlock::from_network(network),
11550                 }, genesis_block.header.time);
11551                 let node_a_holder = ANodeHolder { node: &node_a };
11552
11553                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
11554                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
11555                 let seed_b = [2u8; 32];
11556                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
11557                 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 {
11558                         network,
11559                         best_block: BestBlock::from_network(network),
11560                 }, genesis_block.header.time);
11561                 let node_b_holder = ANodeHolder { node: &node_b };
11562
11563                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
11564                         features: node_b.init_features(), networks: None, remote_network_address: None
11565                 }, true).unwrap();
11566                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
11567                         features: node_a.init_features(), networks: None, remote_network_address: None
11568                 }, false).unwrap();
11569                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
11570                 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()));
11571                 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()));
11572
11573                 let tx;
11574                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
11575                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
11576                                 value: 8_000_000, script_pubkey: output_script,
11577                         }]};
11578                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
11579                 } else { panic!(); }
11580
11581                 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()));
11582                 let events_b = node_b.get_and_clear_pending_events();
11583                 assert_eq!(events_b.len(), 1);
11584                 match events_b[0] {
11585                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11586                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11587                         },
11588                         _ => panic!("Unexpected event"),
11589                 }
11590
11591                 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()));
11592                 let events_a = node_a.get_and_clear_pending_events();
11593                 assert_eq!(events_a.len(), 1);
11594                 match events_a[0] {
11595                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
11596                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11597                         },
11598                         _ => panic!("Unexpected event"),
11599                 }
11600
11601                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
11602
11603                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
11604                 Listen::block_connected(&node_a, &block, 1);
11605                 Listen::block_connected(&node_b, &block, 1);
11606
11607                 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()));
11608                 let msg_events = node_a.get_and_clear_pending_msg_events();
11609                 assert_eq!(msg_events.len(), 2);
11610                 match msg_events[0] {
11611                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
11612                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
11613                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
11614                         },
11615                         _ => panic!(),
11616                 }
11617                 match msg_events[1] {
11618                         MessageSendEvent::SendChannelUpdate { .. } => {},
11619                         _ => panic!(),
11620                 }
11621
11622                 let events_a = node_a.get_and_clear_pending_events();
11623                 assert_eq!(events_a.len(), 1);
11624                 match events_a[0] {
11625                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11626                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
11627                         },
11628                         _ => panic!("Unexpected event"),
11629                 }
11630
11631                 let events_b = node_b.get_and_clear_pending_events();
11632                 assert_eq!(events_b.len(), 1);
11633                 match events_b[0] {
11634                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
11635                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
11636                         },
11637                         _ => panic!("Unexpected event"),
11638                 }
11639
11640                 let mut payment_count: u64 = 0;
11641                 macro_rules! send_payment {
11642                         ($node_a: expr, $node_b: expr) => {
11643                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
11644                                         .with_bolt11_features($node_b.invoice_features()).unwrap();
11645                                 let mut payment_preimage = PaymentPreimage([0; 32]);
11646                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
11647                                 payment_count += 1;
11648                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
11649                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
11650
11651                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
11652                                         PaymentId(payment_hash.0),
11653                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
11654                                         Retry::Attempts(0)).unwrap();
11655                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
11656                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
11657                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
11658                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
11659                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
11660                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
11661                                 $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()));
11662
11663                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
11664                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
11665                                 $node_b.claim_funds(payment_preimage);
11666                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
11667
11668                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
11669                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
11670                                                 assert_eq!(node_id, $node_a.get_our_node_id());
11671                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
11672                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
11673                                         },
11674                                         _ => panic!("Failed to generate claim event"),
11675                                 }
11676
11677                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
11678                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
11679                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
11680                                 $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()));
11681
11682                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
11683                         }
11684                 }
11685
11686                 bench.bench_function(bench_name, |b| b.iter(|| {
11687                         send_payment!(node_a, node_b);
11688                         send_payment!(node_b, node_a);
11689                 }));
11690         }
11691 }