6739e5260f52335a52c8c5b0d4090fcc412c9382
[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::{genesis_block, 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::chain;
34 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
35 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
36 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};
37 use crate::chain::transaction::{OutPoint, TransactionData};
38 use crate::events;
39 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
40 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
41 // construct one themselves.
42 use crate::ln::{inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
43 use crate::ln::channel::{Channel, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel};
44 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
45 #[cfg(any(feature = "_test_utils", test))]
46 use crate::ln::features::Bolt11InvoiceFeatures;
47 use crate::routing::gossip::NetworkGraph;
48 use crate::routing::router::{BlindedTail, DefaultRouter, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
49 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
50 use crate::ln::msgs;
51 use crate::ln::onion_utils;
52 use crate::ln::onion_utils::HTLCFailReason;
53 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
54 #[cfg(test)]
55 use crate::ln::outbound_payment;
56 use crate::ln::outbound_payment::{OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs};
57 use crate::ln::wire::Encode;
58 use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, ChannelSigner, WriteableEcdsaChannelSigner};
59 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
60 use crate::util::wakers::{Future, Notifier};
61 use crate::util::scid_utils::fake_scid;
62 use crate::util::string::UntrustedString;
63 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
64 use crate::util::logger::{Level, Logger};
65 use crate::util::errors::APIError;
66
67 use alloc::collections::BTreeMap;
68
69 use crate::io;
70 use crate::prelude::*;
71 use core::{cmp, mem};
72 use core::cell::RefCell;
73 use crate::io::Read;
74 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
75 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
76 use core::time::Duration;
77 use core::ops::Deref;
78
79 // Re-export this for use in the public API.
80 pub use crate::ln::outbound_payment::{PaymentSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
81 use crate::ln::script::ShutdownScript;
82
83 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
84 //
85 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
86 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
87 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
88 //
89 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
90 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
91 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
92 // before we forward it.
93 //
94 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
95 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
96 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
97 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
98 // our payment, which we can use to decode errors or inform the user that the payment was sent.
99
100 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
101 pub(super) enum PendingHTLCRouting {
102         Forward {
103                 onion_packet: msgs::OnionPacket,
104                 /// The SCID from the onion that we should forward to. This could be a real SCID or a fake one
105                 /// generated using `get_fake_scid` from the scid_utils::fake_scid module.
106                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
107         },
108         Receive {
109                 payment_data: msgs::FinalOnionHopData,
110                 payment_metadata: Option<Vec<u8>>,
111                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
112                 phantom_shared_secret: Option<[u8; 32]>,
113                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
114                 custom_tlvs: Vec<(u64, Vec<u8>)>,
115         },
116         ReceiveKeysend {
117                 /// This was added in 0.0.116 and will break deserialization on downgrades.
118                 payment_data: Option<msgs::FinalOnionHopData>,
119                 payment_preimage: PaymentPreimage,
120                 payment_metadata: Option<Vec<u8>>,
121                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
122                 /// See [`RecipientOnionFields::custom_tlvs`] for more info.
123                 custom_tlvs: Vec<(u64, Vec<u8>)>,
124         },
125 }
126
127 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
128 pub(super) struct PendingHTLCInfo {
129         pub(super) routing: PendingHTLCRouting,
130         pub(super) incoming_shared_secret: [u8; 32],
131         payment_hash: PaymentHash,
132         /// Amount received
133         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
134         /// Sender intended amount to forward or receive (actual amount received
135         /// may overshoot this in either case)
136         pub(super) outgoing_amt_msat: u64,
137         pub(super) outgoing_cltv_value: u32,
138         /// The fee being skimmed off the top of this HTLC. If this is a forward, it'll be the fee we are
139         /// skimming. If we're receiving this HTLC, it's the fee that our counterparty skimmed.
140         pub(super) skimmed_fee_msat: Option<u64>,
141 }
142
143 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
144 pub(super) enum HTLCFailureMsg {
145         Relay(msgs::UpdateFailHTLC),
146         Malformed(msgs::UpdateFailMalformedHTLC),
147 }
148
149 /// Stores whether we can't forward an HTLC or relevant forwarding info
150 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
151 pub(super) enum PendingHTLCStatus {
152         Forward(PendingHTLCInfo),
153         Fail(HTLCFailureMsg),
154 }
155
156 pub(super) struct PendingAddHTLCInfo {
157         pub(super) forward_info: PendingHTLCInfo,
158
159         // These fields are produced in `forward_htlcs()` and consumed in
160         // `process_pending_htlc_forwards()` for constructing the
161         // `HTLCSource::PreviousHopData` for failed and forwarded
162         // HTLCs.
163         //
164         // Note that this may be an outbound SCID alias for the associated channel.
165         prev_short_channel_id: u64,
166         prev_htlc_id: u64,
167         prev_funding_outpoint: OutPoint,
168         prev_user_channel_id: u128,
169 }
170
171 pub(super) enum HTLCForwardInfo {
172         AddHTLC(PendingAddHTLCInfo),
173         FailHTLC {
174                 htlc_id: u64,
175                 err_packet: msgs::OnionErrorPacket,
176         },
177 }
178
179 /// Tracks the inbound corresponding to an outbound HTLC
180 #[derive(Clone, Hash, PartialEq, Eq)]
181 pub(crate) struct HTLCPreviousHopData {
182         // Note that this may be an outbound SCID alias for the associated channel.
183         short_channel_id: u64,
184         htlc_id: u64,
185         incoming_packet_shared_secret: [u8; 32],
186         phantom_shared_secret: Option<[u8; 32]>,
187
188         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
189         // channel with a preimage provided by the forward channel.
190         outpoint: OutPoint,
191 }
192
193 enum OnionPayload {
194         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
195         Invoice {
196                 /// This is only here for backwards-compatibility in serialization, in the future it can be
197                 /// removed, breaking clients running 0.0.106 and earlier.
198                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
199         },
200         /// Contains the payer-provided preimage.
201         Spontaneous(PaymentPreimage),
202 }
203
204 /// HTLCs that are to us and can be failed/claimed by the user
205 struct ClaimableHTLC {
206         prev_hop: HTLCPreviousHopData,
207         cltv_expiry: u32,
208         /// The amount (in msats) of this MPP part
209         value: u64,
210         /// The amount (in msats) that the sender intended to be sent in this MPP
211         /// part (used for validating total MPP amount)
212         sender_intended_value: u64,
213         onion_payload: OnionPayload,
214         timer_ticks: u8,
215         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
216         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
217         total_value_received: Option<u64>,
218         /// The sender intended sum total of all MPP parts specified in the onion
219         total_msat: u64,
220         /// The extra fee our counterparty skimmed off the top of this HTLC.
221         counterparty_skimmed_fee_msat: Option<u64>,
222 }
223
224 /// A payment identifier used to uniquely identify a payment to LDK.
225 ///
226 /// This is not exported to bindings users as we just use [u8; 32] directly
227 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
228 pub struct PaymentId(pub [u8; 32]);
229
230 impl Writeable for PaymentId {
231         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
232                 self.0.write(w)
233         }
234 }
235
236 impl Readable for PaymentId {
237         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
238                 let buf: [u8; 32] = Readable::read(r)?;
239                 Ok(PaymentId(buf))
240         }
241 }
242
243 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
244 ///
245 /// This is not exported to bindings users as we just use [u8; 32] directly
246 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
247 pub struct InterceptId(pub [u8; 32]);
248
249 impl Writeable for InterceptId {
250         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
251                 self.0.write(w)
252         }
253 }
254
255 impl Readable for InterceptId {
256         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
257                 let buf: [u8; 32] = Readable::read(r)?;
258                 Ok(InterceptId(buf))
259         }
260 }
261
262 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
263 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
264 pub(crate) enum SentHTLCId {
265         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
266         OutboundRoute { session_priv: SecretKey },
267 }
268 impl SentHTLCId {
269         pub(crate) fn from_source(source: &HTLCSource) -> Self {
270                 match source {
271                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
272                                 short_channel_id: hop_data.short_channel_id,
273                                 htlc_id: hop_data.htlc_id,
274                         },
275                         HTLCSource::OutboundRoute { session_priv, .. } =>
276                                 Self::OutboundRoute { session_priv: *session_priv },
277                 }
278         }
279 }
280 impl_writeable_tlv_based_enum!(SentHTLCId,
281         (0, PreviousHopData) => {
282                 (0, short_channel_id, required),
283                 (2, htlc_id, required),
284         },
285         (2, OutboundRoute) => {
286                 (0, session_priv, required),
287         };
288 );
289
290
291 /// Tracks the inbound corresponding to an outbound HTLC
292 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
293 #[derive(Clone, PartialEq, Eq)]
294 pub(crate) enum HTLCSource {
295         PreviousHopData(HTLCPreviousHopData),
296         OutboundRoute {
297                 path: Path,
298                 session_priv: SecretKey,
299                 /// Technically we can recalculate this from the route, but we cache it here to avoid
300                 /// doing a double-pass on route when we get a failure back
301                 first_hop_htlc_msat: u64,
302                 payment_id: PaymentId,
303         },
304 }
305 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
306 impl core::hash::Hash for HTLCSource {
307         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
308                 match self {
309                         HTLCSource::PreviousHopData(prev_hop_data) => {
310                                 0u8.hash(hasher);
311                                 prev_hop_data.hash(hasher);
312                         },
313                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
314                                 1u8.hash(hasher);
315                                 path.hash(hasher);
316                                 session_priv[..].hash(hasher);
317                                 payment_id.hash(hasher);
318                                 first_hop_htlc_msat.hash(hasher);
319                         },
320                 }
321         }
322 }
323 impl HTLCSource {
324         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
325         #[cfg(test)]
326         pub fn dummy() -> Self {
327                 HTLCSource::OutboundRoute {
328                         path: Path { hops: Vec::new(), blinded_tail: None },
329                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
330                         first_hop_htlc_msat: 0,
331                         payment_id: PaymentId([2; 32]),
332                 }
333         }
334
335         #[cfg(debug_assertions)]
336         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
337         /// transaction. Useful to ensure different datastructures match up.
338         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
339                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
340                         *first_hop_htlc_msat == htlc.amount_msat
341                 } else {
342                         // There's nothing we can check for forwarded HTLCs
343                         true
344                 }
345         }
346 }
347
348 struct InboundOnionErr {
349         err_code: u16,
350         err_data: Vec<u8>,
351         msg: &'static str,
352 }
353
354 /// This enum is used to specify which error data to send to peers when failing back an HTLC
355 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
356 ///
357 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
358 #[derive(Clone, Copy)]
359 pub enum FailureCode {
360         /// We had a temporary error processing the payment. Useful if no other error codes fit
361         /// and you want to indicate that the payer may want to retry.
362         TemporaryNodeFailure,
363         /// We have a required feature which was not in this onion. For example, you may require
364         /// some additional metadata that was not provided with this payment.
365         RequiredNodeFeatureMissing,
366         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
367         /// the HTLC is too close to the current block height for safe handling.
368         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
369         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
370         IncorrectOrUnknownPaymentDetails,
371         /// We failed to process the payload after the onion was decrypted. You may wish to
372         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
373         ///
374         /// If available, the tuple data may include the type number and byte offset in the
375         /// decrypted byte stream where the failure occurred.
376         InvalidOnionPayload(Option<(u64, u16)>),
377 }
378
379 impl Into<u16> for FailureCode {
380     fn into(self) -> u16 {
381                 match self {
382                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
383                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
384                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
385                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
386                 }
387         }
388 }
389
390 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
391 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
392 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
393 /// peer_state lock. We then return the set of things that need to be done outside the lock in
394 /// this struct and call handle_error!() on it.
395
396 struct MsgHandleErrInternal {
397         err: msgs::LightningError,
398         chan_id: Option<([u8; 32], u128)>, // If Some a channel of ours has been closed
399         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
400         channel_capacity: Option<u64>,
401 }
402 impl MsgHandleErrInternal {
403         #[inline]
404         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
405                 Self {
406                         err: LightningError {
407                                 err: err.clone(),
408                                 action: msgs::ErrorAction::SendErrorMessage {
409                                         msg: msgs::ErrorMessage {
410                                                 channel_id,
411                                                 data: err
412                                         },
413                                 },
414                         },
415                         chan_id: None,
416                         shutdown_finish: None,
417                         channel_capacity: None,
418                 }
419         }
420         #[inline]
421         fn from_no_close(err: msgs::LightningError) -> Self {
422                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
423         }
424         #[inline]
425         fn from_finish_shutdown(err: String, channel_id: [u8; 32], user_channel_id: u128, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>, channel_capacity: u64) -> Self {
426                 Self {
427                         err: LightningError {
428                                 err: err.clone(),
429                                 action: msgs::ErrorAction::SendErrorMessage {
430                                         msg: msgs::ErrorMessage {
431                                                 channel_id,
432                                                 data: err
433                                         },
434                                 },
435                         },
436                         chan_id: Some((channel_id, user_channel_id)),
437                         shutdown_finish: Some((shutdown_res, channel_update)),
438                         channel_capacity: Some(channel_capacity)
439                 }
440         }
441         #[inline]
442         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
443                 Self {
444                         err: match err {
445                                 ChannelError::Warn(msg) =>  LightningError {
446                                         err: msg.clone(),
447                                         action: msgs::ErrorAction::SendWarningMessage {
448                                                 msg: msgs::WarningMessage {
449                                                         channel_id,
450                                                         data: msg
451                                                 },
452                                                 log_level: Level::Warn,
453                                         },
454                                 },
455                                 ChannelError::Ignore(msg) => LightningError {
456                                         err: msg,
457                                         action: msgs::ErrorAction::IgnoreError,
458                                 },
459                                 ChannelError::Close(msg) => LightningError {
460                                         err: msg.clone(),
461                                         action: msgs::ErrorAction::SendErrorMessage {
462                                                 msg: msgs::ErrorMessage {
463                                                         channel_id,
464                                                         data: msg
465                                                 },
466                                         },
467                                 },
468                         },
469                         chan_id: None,
470                         shutdown_finish: None,
471                         channel_capacity: None,
472                 }
473         }
474 }
475
476 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
477 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
478 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
479 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
480 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
481
482 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
483 /// be sent in the order they appear in the return value, however sometimes the order needs to be
484 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
485 /// they were originally sent). In those cases, this enum is also returned.
486 #[derive(Clone, PartialEq)]
487 pub(super) enum RAACommitmentOrder {
488         /// Send the CommitmentUpdate messages first
489         CommitmentFirst,
490         /// Send the RevokeAndACK message first
491         RevokeAndACKFirst,
492 }
493
494 /// Information about a payment which is currently being claimed.
495 struct ClaimingPayment {
496         amount_msat: u64,
497         payment_purpose: events::PaymentPurpose,
498         receiver_node_id: PublicKey,
499 }
500 impl_writeable_tlv_based!(ClaimingPayment, {
501         (0, amount_msat, required),
502         (2, payment_purpose, required),
503         (4, receiver_node_id, required),
504 });
505
506 struct ClaimablePayment {
507         purpose: events::PaymentPurpose,
508         onion_fields: Option<RecipientOnionFields>,
509         htlcs: Vec<ClaimableHTLC>,
510 }
511
512 /// Information about claimable or being-claimed payments
513 struct ClaimablePayments {
514         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
515         /// failed/claimed by the user.
516         ///
517         /// Note that, no consistency guarantees are made about the channels given here actually
518         /// existing anymore by the time you go to read them!
519         ///
520         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
521         /// we don't get a duplicate payment.
522         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
523
524         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
525         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
526         /// as an [`events::Event::PaymentClaimed`].
527         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
528 }
529
530 /// Events which we process internally but cannot be processed immediately at the generation site
531 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
532 /// running normally, and specifically must be processed before any other non-background
533 /// [`ChannelMonitorUpdate`]s are applied.
534 enum BackgroundEvent {
535         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
536         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
537         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
538         /// channel has been force-closed we do not need the counterparty node_id.
539         ///
540         /// Note that any such events are lost on shutdown, so in general they must be updates which
541         /// are regenerated on startup.
542         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
543         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
544         /// channel to continue normal operation.
545         ///
546         /// In general this should be used rather than
547         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
548         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
549         /// error the other variant is acceptable.
550         ///
551         /// Note that any such events are lost on shutdown, so in general they must be updates which
552         /// are regenerated on startup.
553         MonitorUpdateRegeneratedOnStartup {
554                 counterparty_node_id: PublicKey,
555                 funding_txo: OutPoint,
556                 update: ChannelMonitorUpdate
557         },
558         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
559         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
560         /// on a channel.
561         MonitorUpdatesComplete {
562                 counterparty_node_id: PublicKey,
563                 channel_id: [u8; 32],
564         },
565 }
566
567 #[derive(Debug)]
568 pub(crate) enum MonitorUpdateCompletionAction {
569         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
570         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
571         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
572         /// event can be generated.
573         PaymentClaimed { payment_hash: PaymentHash },
574         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
575         /// operation of another channel.
576         ///
577         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
578         /// from completing a monitor update which removes the payment preimage until the inbound edge
579         /// completes a monitor update containing the payment preimage. In that case, after the inbound
580         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
581         /// outbound edge.
582         EmitEventAndFreeOtherChannel {
583                 event: events::Event,
584                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
585         },
586 }
587
588 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
589         (0, PaymentClaimed) => { (0, payment_hash, required) },
590         (2, EmitEventAndFreeOtherChannel) => {
591                 (0, event, upgradable_required),
592                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
593                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
594                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
595                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
596                 // downgrades to prior versions.
597                 (1, downstream_counterparty_and_funding_outpoint, option),
598         },
599 );
600
601 #[derive(Clone, Debug, PartialEq, Eq)]
602 pub(crate) enum EventCompletionAction {
603         ReleaseRAAChannelMonitorUpdate {
604                 counterparty_node_id: PublicKey,
605                 channel_funding_outpoint: OutPoint,
606         },
607 }
608 impl_writeable_tlv_based_enum!(EventCompletionAction,
609         (0, ReleaseRAAChannelMonitorUpdate) => {
610                 (0, channel_funding_outpoint, required),
611                 (2, counterparty_node_id, required),
612         };
613 );
614
615 #[derive(Clone, PartialEq, Eq, Debug)]
616 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
617 /// the blocked action here. See enum variants for more info.
618 pub(crate) enum RAAMonitorUpdateBlockingAction {
619         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
620         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
621         /// durably to disk.
622         ForwardedPaymentInboundClaim {
623                 /// The upstream channel ID (i.e. the inbound edge).
624                 channel_id: [u8; 32],
625                 /// The HTLC ID on the inbound edge.
626                 htlc_id: u64,
627         },
628 }
629
630 impl RAAMonitorUpdateBlockingAction {
631         #[allow(unused)]
632         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
633                 Self::ForwardedPaymentInboundClaim {
634                         channel_id: prev_hop.outpoint.to_channel_id(),
635                         htlc_id: prev_hop.htlc_id,
636                 }
637         }
638 }
639
640 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
641         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
642 ;);
643
644
645 /// State we hold per-peer.
646 pub(super) struct PeerState<Signer: ChannelSigner> {
647         /// `channel_id` -> `Channel`.
648         ///
649         /// Holds all funded channels where the peer is the counterparty.
650         pub(super) channel_by_id: HashMap<[u8; 32], Channel<Signer>>,
651         /// `temporary_channel_id` -> `OutboundV1Channel`.
652         ///
653         /// Holds all outbound V1 channels where the peer is the counterparty. Once an outbound channel has
654         /// been assigned a `channel_id`, the entry in this map is removed and one is created in
655         /// `channel_by_id`.
656         pub(super) outbound_v1_channel_by_id: HashMap<[u8; 32], OutboundV1Channel<Signer>>,
657         /// `temporary_channel_id` -> `InboundV1Channel`.
658         ///
659         /// Holds all inbound V1 channels where the peer is the counterparty. Once an inbound channel has
660         /// been assigned a `channel_id`, the entry in this map is removed and one is created in
661         /// `channel_by_id`.
662         pub(super) inbound_v1_channel_by_id: HashMap<[u8; 32], InboundV1Channel<Signer>>,
663         /// `temporary_channel_id` -> `InboundChannelRequest`.
664         ///
665         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
666         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
667         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
668         /// the channel is rejected, then the entry is simply removed.
669         pub(super) inbound_channel_request_by_id: HashMap<[u8; 32], InboundChannelRequest>,
670         /// The latest `InitFeatures` we heard from the peer.
671         latest_features: InitFeatures,
672         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
673         /// for broadcast messages, where ordering isn't as strict).
674         pub(super) pending_msg_events: Vec<MessageSendEvent>,
675         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
676         /// user but which have not yet completed.
677         ///
678         /// Note that the channel may no longer exist. For example if the channel was closed but we
679         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
680         /// for a missing channel.
681         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
682         /// Map from a specific channel to some action(s) that should be taken when all pending
683         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
684         ///
685         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
686         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
687         /// channels with a peer this will just be one allocation and will amount to a linear list of
688         /// channels to walk, avoiding the whole hashing rigmarole.
689         ///
690         /// Note that the channel may no longer exist. For example, if a channel was closed but we
691         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
692         /// for a missing channel. While a malicious peer could construct a second channel with the
693         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
694         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
695         /// duplicates do not occur, so such channels should fail without a monitor update completing.
696         monitor_update_blocked_actions: BTreeMap<[u8; 32], Vec<MonitorUpdateCompletionAction>>,
697         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
698         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
699         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
700         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
701         actions_blocking_raa_monitor_updates: BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
702         /// The peer is currently connected (i.e. we've seen a
703         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
704         /// [`ChannelMessageHandler::peer_disconnected`].
705         is_connected: bool,
706 }
707
708 impl <Signer: ChannelSigner> PeerState<Signer> {
709         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
710         /// If true is passed for `require_disconnected`, the function will return false if we haven't
711         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
712         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
713                 if require_disconnected && self.is_connected {
714                         return false
715                 }
716                 self.channel_by_id.is_empty() && self.monitor_update_blocked_actions.is_empty()
717                         && self.in_flight_monitor_updates.is_empty()
718         }
719
720         // Returns a count of all channels we have with this peer, including unfunded channels.
721         fn total_channel_count(&self) -> usize {
722                 self.channel_by_id.len() +
723                         self.outbound_v1_channel_by_id.len() +
724                         self.inbound_v1_channel_by_id.len() +
725                         self.inbound_channel_request_by_id.len()
726         }
727
728         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
729         fn has_channel(&self, channel_id: &[u8; 32]) -> bool {
730                 self.channel_by_id.contains_key(channel_id) ||
731                         self.outbound_v1_channel_by_id.contains_key(channel_id) ||
732                         self.inbound_v1_channel_by_id.contains_key(channel_id) ||
733                         self.inbound_channel_request_by_id.contains_key(channel_id)
734         }
735 }
736
737 /// A not-yet-accepted inbound (from counterparty) channel. Once
738 /// accepted, the parameters will be used to construct a channel.
739 pub(super) struct InboundChannelRequest {
740         /// The original OpenChannel message.
741         pub open_channel_msg: msgs::OpenChannel,
742         /// The number of ticks remaining before the request expires.
743         pub ticks_remaining: i32,
744 }
745
746 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
747 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
748 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
749
750 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
751 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
752 ///
753 /// For users who don't want to bother doing their own payment preimage storage, we also store that
754 /// here.
755 ///
756 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
757 /// and instead encoding it in the payment secret.
758 struct PendingInboundPayment {
759         /// The payment secret that the sender must use for us to accept this payment
760         payment_secret: PaymentSecret,
761         /// Time at which this HTLC expires - blocks with a header time above this value will result in
762         /// this payment being removed.
763         expiry_time: u64,
764         /// Arbitrary identifier the user specifies (or not)
765         user_payment_id: u64,
766         // Other required attributes of the payment, optionally enforced:
767         payment_preimage: Option<PaymentPreimage>,
768         min_value_msat: Option<u64>,
769 }
770
771 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
772 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
773 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
774 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
775 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
776 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
777 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
778 /// of [`KeysManager`] and [`DefaultRouter`].
779 ///
780 /// This is not exported to bindings users as Arcs don't make sense in bindings
781 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
782         Arc<M>,
783         Arc<T>,
784         Arc<KeysManager>,
785         Arc<KeysManager>,
786         Arc<KeysManager>,
787         Arc<F>,
788         Arc<DefaultRouter<
789                 Arc<NetworkGraph<Arc<L>>>,
790                 Arc<L>,
791                 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
792                 ProbabilisticScoringFeeParameters,
793                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
794         >>,
795         Arc<L>
796 >;
797
798 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
799 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
800 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
801 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
802 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
803 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
804 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
805 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
806 /// of [`KeysManager`] and [`DefaultRouter`].
807 ///
808 /// This is not exported to bindings users as Arcs don't make sense in bindings
809 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
810         ChannelManager<
811                 &'a M,
812                 &'b T,
813                 &'c KeysManager,
814                 &'c KeysManager,
815                 &'c KeysManager,
816                 &'d F,
817                 &'e DefaultRouter<
818                         &'f NetworkGraph<&'g L>,
819                         &'g L,
820                         &'h Mutex<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
821                         ProbabilisticScoringFeeParameters,
822                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
823                 >,
824                 &'g L
825         >;
826
827 macro_rules! define_test_pub_trait { ($vis: vis) => {
828 /// A trivial trait which describes any [`ChannelManager`] used in testing.
829 $vis trait AChannelManager {
830         type Watch: chain::Watch<Self::Signer> + ?Sized;
831         type M: Deref<Target = Self::Watch>;
832         type Broadcaster: BroadcasterInterface + ?Sized;
833         type T: Deref<Target = Self::Broadcaster>;
834         type EntropySource: EntropySource + ?Sized;
835         type ES: Deref<Target = Self::EntropySource>;
836         type NodeSigner: NodeSigner + ?Sized;
837         type NS: Deref<Target = Self::NodeSigner>;
838         type Signer: WriteableEcdsaChannelSigner + Sized;
839         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
840         type SP: Deref<Target = Self::SignerProvider>;
841         type FeeEstimator: FeeEstimator + ?Sized;
842         type F: Deref<Target = Self::FeeEstimator>;
843         type Router: Router + ?Sized;
844         type R: Deref<Target = Self::Router>;
845         type Logger: Logger + ?Sized;
846         type L: Deref<Target = Self::Logger>;
847         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
848 }
849 } }
850 #[cfg(any(test, feature = "_test_utils"))]
851 define_test_pub_trait!(pub);
852 #[cfg(not(any(test, feature = "_test_utils")))]
853 define_test_pub_trait!(pub(crate));
854 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
855 for ChannelManager<M, T, ES, NS, SP, F, R, L>
856 where
857         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
858         T::Target: BroadcasterInterface,
859         ES::Target: EntropySource,
860         NS::Target: NodeSigner,
861         SP::Target: SignerProvider,
862         F::Target: FeeEstimator,
863         R::Target: Router,
864         L::Target: Logger,
865 {
866         type Watch = M::Target;
867         type M = M;
868         type Broadcaster = T::Target;
869         type T = T;
870         type EntropySource = ES::Target;
871         type ES = ES;
872         type NodeSigner = NS::Target;
873         type NS = NS;
874         type Signer = <SP::Target as SignerProvider>::Signer;
875         type SignerProvider = SP::Target;
876         type SP = SP;
877         type FeeEstimator = F::Target;
878         type F = F;
879         type Router = R::Target;
880         type R = R;
881         type Logger = L::Target;
882         type L = L;
883         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
884 }
885
886 /// Manager which keeps track of a number of channels and sends messages to the appropriate
887 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
888 ///
889 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
890 /// to individual Channels.
891 ///
892 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
893 /// all peers during write/read (though does not modify this instance, only the instance being
894 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
895 /// called [`funding_transaction_generated`] for outbound channels) being closed.
896 ///
897 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
898 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST write each monitor update out to disk before
899 /// returning from [`chain::Watch::watch_channel`]/[`update_channel`], with ChannelManagers, writing updates
900 /// happens out-of-band (and will prevent any other `ChannelManager` operations from occurring during
901 /// the serialization process). If the deserialized version is out-of-date compared to the
902 /// [`ChannelMonitor`] passed by reference to [`read`], those channels will be force-closed based on the
903 /// `ChannelMonitor` state and no funds will be lost (mod on-chain transaction fees).
904 ///
905 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
906 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
907 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
908 ///
909 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
910 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
911 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
912 /// offline for a full minute. In order to track this, you must call
913 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
914 ///
915 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
916 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
917 /// not have a channel with being unable to connect to us or open new channels with us if we have
918 /// many peers with unfunded channels.
919 ///
920 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
921 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
922 /// never limited. Please ensure you limit the count of such channels yourself.
923 ///
924 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
925 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
926 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
927 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
928 /// you're using lightning-net-tokio.
929 ///
930 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
931 /// [`funding_created`]: msgs::FundingCreated
932 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
933 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
934 /// [`update_channel`]: chain::Watch::update_channel
935 /// [`ChannelUpdate`]: msgs::ChannelUpdate
936 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
937 /// [`read`]: ReadableArgs::read
938 //
939 // Lock order:
940 // The tree structure below illustrates the lock order requirements for the different locks of the
941 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
942 // and should then be taken in the order of the lowest to the highest level in the tree.
943 // Note that locks on different branches shall not be taken at the same time, as doing so will
944 // create a new lock order for those specific locks in the order they were taken.
945 //
946 // Lock order tree:
947 //
948 // `total_consistency_lock`
949 //  |
950 //  |__`forward_htlcs`
951 //  |   |
952 //  |   |__`pending_intercepted_htlcs`
953 //  |
954 //  |__`per_peer_state`
955 //  |   |
956 //  |   |__`pending_inbound_payments`
957 //  |       |
958 //  |       |__`claimable_payments`
959 //  |       |
960 //  |       |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
961 //  |           |
962 //  |           |__`peer_state`
963 //  |               |
964 //  |               |__`id_to_peer`
965 //  |               |
966 //  |               |__`short_to_chan_info`
967 //  |               |
968 //  |               |__`outbound_scid_aliases`
969 //  |               |
970 //  |               |__`best_block`
971 //  |               |
972 //  |               |__`pending_events`
973 //  |                   |
974 //  |                   |__`pending_background_events`
975 //
976 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
977 where
978         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
979         T::Target: BroadcasterInterface,
980         ES::Target: EntropySource,
981         NS::Target: NodeSigner,
982         SP::Target: SignerProvider,
983         F::Target: FeeEstimator,
984         R::Target: Router,
985         L::Target: Logger,
986 {
987         default_configuration: UserConfig,
988         genesis_hash: BlockHash,
989         fee_estimator: LowerBoundedFeeEstimator<F>,
990         chain_monitor: M,
991         tx_broadcaster: T,
992         #[allow(unused)]
993         router: R,
994
995         /// See `ChannelManager` struct-level documentation for lock order requirements.
996         #[cfg(test)]
997         pub(super) best_block: RwLock<BestBlock>,
998         #[cfg(not(test))]
999         best_block: RwLock<BestBlock>,
1000         secp_ctx: Secp256k1<secp256k1::All>,
1001
1002         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1003         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1004         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1005         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1006         ///
1007         /// See `ChannelManager` struct-level documentation for lock order requirements.
1008         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1009
1010         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1011         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1012         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1013         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1014         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1015         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1016         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1017         /// after reloading from disk while replaying blocks against ChannelMonitors.
1018         ///
1019         /// See `PendingOutboundPayment` documentation for more info.
1020         ///
1021         /// See `ChannelManager` struct-level documentation for lock order requirements.
1022         pending_outbound_payments: OutboundPayments,
1023
1024         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1025         ///
1026         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1027         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1028         /// and via the classic SCID.
1029         ///
1030         /// Note that no consistency guarantees are made about the existence of a channel with the
1031         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1032         ///
1033         /// See `ChannelManager` struct-level documentation for lock order requirements.
1034         #[cfg(test)]
1035         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1036         #[cfg(not(test))]
1037         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1038         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1039         /// until the user tells us what we should do with them.
1040         ///
1041         /// See `ChannelManager` struct-level documentation for lock order requirements.
1042         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1043
1044         /// The sets of payments which are claimable or currently being claimed. See
1045         /// [`ClaimablePayments`]' individual field docs for more info.
1046         ///
1047         /// See `ChannelManager` struct-level documentation for lock order requirements.
1048         claimable_payments: Mutex<ClaimablePayments>,
1049
1050         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1051         /// and some closed channels which reached a usable state prior to being closed. This is used
1052         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1053         /// active channel list on load.
1054         ///
1055         /// See `ChannelManager` struct-level documentation for lock order requirements.
1056         outbound_scid_aliases: Mutex<HashSet<u64>>,
1057
1058         /// `channel_id` -> `counterparty_node_id`.
1059         ///
1060         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1061         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1062         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1063         ///
1064         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1065         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1066         /// the handling of the events.
1067         ///
1068         /// Note that no consistency guarantees are made about the existence of a peer with the
1069         /// `counterparty_node_id` in our other maps.
1070         ///
1071         /// TODO:
1072         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1073         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1074         /// would break backwards compatability.
1075         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1076         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1077         /// required to access the channel with the `counterparty_node_id`.
1078         ///
1079         /// See `ChannelManager` struct-level documentation for lock order requirements.
1080         id_to_peer: Mutex<HashMap<[u8; 32], PublicKey>>,
1081
1082         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1083         ///
1084         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1085         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1086         /// confirmation depth.
1087         ///
1088         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1089         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1090         /// channel with the `channel_id` in our other maps.
1091         ///
1092         /// See `ChannelManager` struct-level documentation for lock order requirements.
1093         #[cfg(test)]
1094         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
1095         #[cfg(not(test))]
1096         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
1097
1098         our_network_pubkey: PublicKey,
1099
1100         inbound_payment_key: inbound_payment::ExpandedKey,
1101
1102         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1103         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1104         /// we encrypt the namespace identifier using these bytes.
1105         ///
1106         /// [fake scids]: crate::util::scid_utils::fake_scid
1107         fake_scid_rand_bytes: [u8; 32],
1108
1109         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1110         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1111         /// keeping additional state.
1112         probing_cookie_secret: [u8; 32],
1113
1114         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1115         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1116         /// very far in the past, and can only ever be up to two hours in the future.
1117         highest_seen_timestamp: AtomicUsize,
1118
1119         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1120         /// basis, as well as the peer's latest features.
1121         ///
1122         /// If we are connected to a peer we always at least have an entry here, even if no channels
1123         /// are currently open with that peer.
1124         ///
1125         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1126         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1127         /// channels.
1128         ///
1129         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1130         ///
1131         /// See `ChannelManager` struct-level documentation for lock order requirements.
1132         #[cfg(not(any(test, feature = "_test_utils")))]
1133         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
1134         #[cfg(any(test, feature = "_test_utils"))]
1135         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
1136
1137         /// The set of events which we need to give to the user to handle. In some cases an event may
1138         /// require some further action after the user handles it (currently only blocking a monitor
1139         /// update from being handed to the user to ensure the included changes to the channel state
1140         /// are handled by the user before they're persisted durably to disk). In that case, the second
1141         /// element in the tuple is set to `Some` with further details of the action.
1142         ///
1143         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1144         /// could be in the middle of being processed without the direct mutex held.
1145         ///
1146         /// See `ChannelManager` struct-level documentation for lock order requirements.
1147         #[cfg(not(any(test, feature = "_test_utils")))]
1148         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1149         #[cfg(any(test, feature = "_test_utils"))]
1150         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1151
1152         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1153         pending_events_processor: AtomicBool,
1154
1155         /// If we are running during init (either directly during the deserialization method or in
1156         /// block connection methods which run after deserialization but before normal operation) we
1157         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1158         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1159         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1160         ///
1161         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1162         ///
1163         /// See `ChannelManager` struct-level documentation for lock order requirements.
1164         ///
1165         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1166         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1167         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1168         /// Essentially just when we're serializing ourselves out.
1169         /// Taken first everywhere where we are making changes before any other locks.
1170         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1171         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1172         /// Notifier the lock contains sends out a notification when the lock is released.
1173         total_consistency_lock: RwLock<()>,
1174
1175         background_events_processed_since_startup: AtomicBool,
1176
1177         persistence_notifier: Notifier,
1178
1179         entropy_source: ES,
1180         node_signer: NS,
1181         signer_provider: SP,
1182
1183         logger: L,
1184 }
1185
1186 /// Chain-related parameters used to construct a new `ChannelManager`.
1187 ///
1188 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1189 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1190 /// are not needed when deserializing a previously constructed `ChannelManager`.
1191 #[derive(Clone, Copy, PartialEq)]
1192 pub struct ChainParameters {
1193         /// The network for determining the `chain_hash` in Lightning messages.
1194         pub network: Network,
1195
1196         /// The hash and height of the latest block successfully connected.
1197         ///
1198         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1199         pub best_block: BestBlock,
1200 }
1201
1202 #[derive(Copy, Clone, PartialEq)]
1203 #[must_use]
1204 enum NotifyOption {
1205         DoPersist,
1206         SkipPersist,
1207 }
1208
1209 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1210 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1211 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1212 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1213 /// sending the aforementioned notification (since the lock being released indicates that the
1214 /// updates are ready for persistence).
1215 ///
1216 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1217 /// notify or not based on whether relevant changes have been made, providing a closure to
1218 /// `optionally_notify` which returns a `NotifyOption`.
1219 struct PersistenceNotifierGuard<'a, F: Fn() -> NotifyOption> {
1220         persistence_notifier: &'a Notifier,
1221         should_persist: F,
1222         // We hold onto this result so the lock doesn't get released immediately.
1223         _read_guard: RwLockReadGuard<'a, ()>,
1224 }
1225
1226 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1227         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl Fn() -> NotifyOption> {
1228                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1229                 let _ = cm.get_cm().process_background_events(); // We always persist
1230
1231                 PersistenceNotifierGuard {
1232                         persistence_notifier: &cm.get_cm().persistence_notifier,
1233                         should_persist: || -> NotifyOption { NotifyOption::DoPersist },
1234                         _read_guard: read_guard,
1235                 }
1236
1237         }
1238
1239         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1240         /// [`ChannelManager::process_background_events`] MUST be called first.
1241         fn optionally_notify<F: Fn() -> NotifyOption>(lock: &'a RwLock<()>, notifier: &'a Notifier, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1242                 let read_guard = lock.read().unwrap();
1243
1244                 PersistenceNotifierGuard {
1245                         persistence_notifier: notifier,
1246                         should_persist: persist_check,
1247                         _read_guard: read_guard,
1248                 }
1249         }
1250 }
1251
1252 impl<'a, F: Fn() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1253         fn drop(&mut self) {
1254                 if (self.should_persist)() == NotifyOption::DoPersist {
1255                         self.persistence_notifier.notify();
1256                 }
1257         }
1258 }
1259
1260 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1261 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1262 ///
1263 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1264 ///
1265 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1266 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1267 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1268 /// the maximum required amount in lnd as of March 2021.
1269 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1270
1271 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1272 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1273 ///
1274 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1275 ///
1276 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1277 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1278 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1279 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1280 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1281 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1282 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1283 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1284 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1285 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1286 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1287 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1288 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1289
1290 /// Minimum CLTV difference between the current block height and received inbound payments.
1291 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1292 /// this value.
1293 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1294 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1295 // a payment was being routed, so we add an extra block to be safe.
1296 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1297
1298 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1299 // ie that if the next-hop peer fails the HTLC within
1300 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1301 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1302 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1303 // LATENCY_GRACE_PERIOD_BLOCKS.
1304 #[deny(const_err)]
1305 #[allow(dead_code)]
1306 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;
1307
1308 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1309 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1310 #[deny(const_err)]
1311 #[allow(dead_code)]
1312 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1313
1314 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1315 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1316
1317 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the
1318 /// idempotency of payments by [`PaymentId`]. See
1319 /// [`OutboundPayments::remove_stale_resolved_payments`].
1320 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
1321
1322 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1323 /// until we mark the channel disabled and gossip the update.
1324 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1325
1326 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1327 /// we mark the channel enabled and gossip the update.
1328 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1329
1330 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1331 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1332 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1333 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1334
1335 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1336 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1337 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1338
1339 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1340 /// many peers we reject new (inbound) connections.
1341 const MAX_NO_CHANNEL_PEERS: usize = 250;
1342
1343 /// Information needed for constructing an invoice route hint for this channel.
1344 #[derive(Clone, Debug, PartialEq)]
1345 pub struct CounterpartyForwardingInfo {
1346         /// Base routing fee in millisatoshis.
1347         pub fee_base_msat: u32,
1348         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1349         pub fee_proportional_millionths: u32,
1350         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1351         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1352         /// `cltv_expiry_delta` for more details.
1353         pub cltv_expiry_delta: u16,
1354 }
1355
1356 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1357 /// to better separate parameters.
1358 #[derive(Clone, Debug, PartialEq)]
1359 pub struct ChannelCounterparty {
1360         /// The node_id of our counterparty
1361         pub node_id: PublicKey,
1362         /// The Features the channel counterparty provided upon last connection.
1363         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1364         /// many routing-relevant features are present in the init context.
1365         pub features: InitFeatures,
1366         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1367         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1368         /// claiming at least this value on chain.
1369         ///
1370         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1371         ///
1372         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1373         pub unspendable_punishment_reserve: u64,
1374         /// Information on the fees and requirements that the counterparty requires when forwarding
1375         /// payments to us through this channel.
1376         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1377         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1378         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1379         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1380         pub outbound_htlc_minimum_msat: Option<u64>,
1381         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1382         pub outbound_htlc_maximum_msat: Option<u64>,
1383 }
1384
1385 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1386 ///
1387 /// Balances of a channel are available through [`ChainMonitor::get_claimable_balances`] and
1388 /// [`ChannelMonitor::get_claimable_balances`], calculated with respect to the corresponding on-chain
1389 /// transactions.
1390 ///
1391 /// [`ChainMonitor::get_claimable_balances`]: crate::chain::chainmonitor::ChainMonitor::get_claimable_balances
1392 #[derive(Clone, Debug, PartialEq)]
1393 pub struct ChannelDetails {
1394         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1395         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1396         /// Note that this means this value is *not* persistent - it can change once during the
1397         /// lifetime of the channel.
1398         pub channel_id: [u8; 32],
1399         /// Parameters which apply to our counterparty. See individual fields for more information.
1400         pub counterparty: ChannelCounterparty,
1401         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1402         /// our counterparty already.
1403         ///
1404         /// Note that, if this has been set, `channel_id` will be equivalent to
1405         /// `funding_txo.unwrap().to_channel_id()`.
1406         pub funding_txo: Option<OutPoint>,
1407         /// The features which this channel operates with. See individual features for more info.
1408         ///
1409         /// `None` until negotiation completes and the channel type is finalized.
1410         pub channel_type: Option<ChannelTypeFeatures>,
1411         /// The position of the funding transaction in the chain. None if the funding transaction has
1412         /// not yet been confirmed and the channel fully opened.
1413         ///
1414         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1415         /// payments instead of this. See [`get_inbound_payment_scid`].
1416         ///
1417         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1418         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1419         ///
1420         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1421         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1422         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1423         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1424         /// [`confirmations_required`]: Self::confirmations_required
1425         pub short_channel_id: Option<u64>,
1426         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1427         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1428         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1429         /// `Some(0)`).
1430         ///
1431         /// This will be `None` as long as the channel is not available for routing outbound payments.
1432         ///
1433         /// [`short_channel_id`]: Self::short_channel_id
1434         /// [`confirmations_required`]: Self::confirmations_required
1435         pub outbound_scid_alias: Option<u64>,
1436         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1437         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1438         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1439         /// when they see a payment to be routed to us.
1440         ///
1441         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1442         /// previous values for inbound payment forwarding.
1443         ///
1444         /// [`short_channel_id`]: Self::short_channel_id
1445         pub inbound_scid_alias: Option<u64>,
1446         /// The value, in satoshis, of this channel as appears in the funding output
1447         pub channel_value_satoshis: u64,
1448         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1449         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1450         /// this value on chain.
1451         ///
1452         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1453         ///
1454         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1455         ///
1456         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1457         pub unspendable_punishment_reserve: Option<u64>,
1458         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1459         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1460         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1461         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1462         /// serialized with LDK versions prior to 0.0.113.
1463         ///
1464         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1465         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1466         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1467         pub user_channel_id: u128,
1468         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1469         /// which is applied to commitment and HTLC transactions.
1470         ///
1471         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1472         pub feerate_sat_per_1000_weight: Option<u32>,
1473         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1474         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1475         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1476         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1477         ///
1478         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1479         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1480         /// should be able to spend nearly this amount.
1481         pub outbound_capacity_msat: u64,
1482         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1483         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1484         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1485         /// to use a limit as close as possible to the HTLC limit we can currently send.
1486         ///
1487         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`] and
1488         /// [`ChannelDetails::outbound_capacity_msat`].
1489         pub next_outbound_htlc_limit_msat: u64,
1490         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1491         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1492         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1493         /// route which is valid.
1494         pub next_outbound_htlc_minimum_msat: u64,
1495         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1496         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1497         /// available for inclusion in new inbound HTLCs).
1498         /// Note that there are some corner cases not fully handled here, so the actual available
1499         /// inbound capacity may be slightly higher than this.
1500         ///
1501         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1502         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1503         /// However, our counterparty should be able to spend nearly this amount.
1504         pub inbound_capacity_msat: u64,
1505         /// The number of required confirmations on the funding transaction before the funding will be
1506         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1507         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1508         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1509         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1510         ///
1511         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1512         ///
1513         /// [`is_outbound`]: ChannelDetails::is_outbound
1514         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1515         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1516         pub confirmations_required: Option<u32>,
1517         /// The current number of confirmations on the funding transaction.
1518         ///
1519         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1520         pub confirmations: Option<u32>,
1521         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1522         /// until we can claim our funds after we force-close the channel. During this time our
1523         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1524         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1525         /// time to claim our non-HTLC-encumbered funds.
1526         ///
1527         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1528         pub force_close_spend_delay: Option<u16>,
1529         /// True if the channel was initiated (and thus funded) by us.
1530         pub is_outbound: bool,
1531         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1532         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1533         /// required confirmation count has been reached (and we were connected to the peer at some
1534         /// point after the funding transaction received enough confirmations). The required
1535         /// confirmation count is provided in [`confirmations_required`].
1536         ///
1537         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1538         pub is_channel_ready: bool,
1539         /// The stage of the channel's shutdown.
1540         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1541         pub channel_shutdown_state: Option<ChannelShutdownState>,
1542         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1543         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1544         ///
1545         /// This is a strict superset of `is_channel_ready`.
1546         pub is_usable: bool,
1547         /// True if this channel is (or will be) publicly-announced.
1548         pub is_public: bool,
1549         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1550         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1551         pub inbound_htlc_minimum_msat: Option<u64>,
1552         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1553         pub inbound_htlc_maximum_msat: Option<u64>,
1554         /// Set of configurable parameters that affect channel operation.
1555         ///
1556         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1557         pub config: Option<ChannelConfig>,
1558 }
1559
1560 impl ChannelDetails {
1561         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1562         /// This should be used for providing invoice hints or in any other context where our
1563         /// counterparty will forward a payment to us.
1564         ///
1565         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1566         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1567         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1568                 self.inbound_scid_alias.or(self.short_channel_id)
1569         }
1570
1571         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1572         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1573         /// we're sending or forwarding a payment outbound over this channel.
1574         ///
1575         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1576         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1577         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1578                 self.short_channel_id.or(self.outbound_scid_alias)
1579         }
1580
1581         fn from_channel_context<Signer: WriteableEcdsaChannelSigner, F: Deref>(
1582                 context: &ChannelContext<Signer>, best_block_height: u32, latest_features: InitFeatures,
1583                 fee_estimator: &LowerBoundedFeeEstimator<F>
1584         ) -> Self
1585         where F::Target: FeeEstimator
1586         {
1587                 let balance = context.get_available_balances(fee_estimator);
1588                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1589                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1590                 ChannelDetails {
1591                         channel_id: context.channel_id(),
1592                         counterparty: ChannelCounterparty {
1593                                 node_id: context.get_counterparty_node_id(),
1594                                 features: latest_features,
1595                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1596                                 forwarding_info: context.counterparty_forwarding_info(),
1597                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1598                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1599                                 // message (as they are always the first message from the counterparty).
1600                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1601                                 // default `0` value set by `Channel::new_outbound`.
1602                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1603                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1604                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1605                         },
1606                         funding_txo: context.get_funding_txo(),
1607                         // Note that accept_channel (or open_channel) is always the first message, so
1608                         // `have_received_message` indicates that type negotiation has completed.
1609                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1610                         short_channel_id: context.get_short_channel_id(),
1611                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1612                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1613                         channel_value_satoshis: context.get_value_satoshis(),
1614                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1615                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1616                         inbound_capacity_msat: balance.inbound_capacity_msat,
1617                         outbound_capacity_msat: balance.outbound_capacity_msat,
1618                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1619                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1620                         user_channel_id: context.get_user_id(),
1621                         confirmations_required: context.minimum_depth(),
1622                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1623                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1624                         is_outbound: context.is_outbound(),
1625                         is_channel_ready: context.is_usable(),
1626                         is_usable: context.is_live(),
1627                         is_public: context.should_announce(),
1628                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1629                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1630                         config: Some(context.config()),
1631                         channel_shutdown_state: Some(context.shutdown_state()),
1632                 }
1633         }
1634 }
1635
1636 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1637 /// Further information on the details of the channel shutdown.
1638 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1639 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1640 /// the channel will be removed shortly.
1641 /// Also note, that in normal operation, peers could disconnect at any of these states
1642 /// and require peer re-connection before making progress onto other states
1643 pub enum ChannelShutdownState {
1644         /// Channel has not sent or received a shutdown message.
1645         NotShuttingDown,
1646         /// Local node has sent a shutdown message for this channel.
1647         ShutdownInitiated,
1648         /// Shutdown message exchanges have concluded and the channels are in the midst of
1649         /// resolving all existing open HTLCs before closing can continue.
1650         ResolvingHTLCs,
1651         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1652         NegotiatingClosingFee,
1653         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1654         /// to drop the channel.
1655         ShutdownComplete,
1656 }
1657
1658 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1659 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1660 #[derive(Debug, PartialEq)]
1661 pub enum RecentPaymentDetails {
1662         /// When a payment is still being sent and awaiting successful delivery.
1663         Pending {
1664                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1665                 /// abandoned.
1666                 payment_hash: PaymentHash,
1667                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1668                 /// not just the amount currently inflight.
1669                 total_msat: u64,
1670         },
1671         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1672         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1673         /// payment is removed from tracking.
1674         Fulfilled {
1675                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1676                 /// made before LDK version 0.0.104.
1677                 payment_hash: Option<PaymentHash>,
1678         },
1679         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1680         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1681         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1682         Abandoned {
1683                 /// Hash of the payment that we have given up trying to send.
1684                 payment_hash: PaymentHash,
1685         },
1686 }
1687
1688 /// Route hints used in constructing invoices for [phantom node payents].
1689 ///
1690 /// [phantom node payments]: crate::sign::PhantomKeysManager
1691 #[derive(Clone)]
1692 pub struct PhantomRouteHints {
1693         /// The list of channels to be included in the invoice route hints.
1694         pub channels: Vec<ChannelDetails>,
1695         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1696         /// route hints.
1697         pub phantom_scid: u64,
1698         /// The pubkey of the real backing node that would ultimately receive the payment.
1699         pub real_node_pubkey: PublicKey,
1700 }
1701
1702 macro_rules! handle_error {
1703         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1704                 // In testing, ensure there are no deadlocks where the lock is already held upon
1705                 // entering the macro.
1706                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1707                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1708
1709                 match $internal {
1710                         Ok(msg) => Ok(msg),
1711                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1712                                 let mut msg_events = Vec::with_capacity(2);
1713
1714                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1715                                         $self.finish_force_close_channel(shutdown_res);
1716                                         if let Some(update) = update_option {
1717                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1718                                                         msg: update
1719                                                 });
1720                                         }
1721                                         if let Some((channel_id, user_channel_id)) = chan_id {
1722                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1723                                                         channel_id, user_channel_id,
1724                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1725                                                         counterparty_node_id: Some($counterparty_node_id),
1726                                                         channel_capacity_sats: channel_capacity,
1727                                                 }, None));
1728                                         }
1729                                 }
1730
1731                                 log_error!($self.logger, "{}", err.err);
1732                                 if let msgs::ErrorAction::IgnoreError = err.action {
1733                                 } else {
1734                                         msg_events.push(events::MessageSendEvent::HandleError {
1735                                                 node_id: $counterparty_node_id,
1736                                                 action: err.action.clone()
1737                                         });
1738                                 }
1739
1740                                 if !msg_events.is_empty() {
1741                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1742                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1743                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1744                                                 peer_state.pending_msg_events.append(&mut msg_events);
1745                                         }
1746                                 }
1747
1748                                 // Return error in case higher-API need one
1749                                 Err(err)
1750                         },
1751                 }
1752         } };
1753         ($self: ident, $internal: expr) => {
1754                 match $internal {
1755                         Ok(res) => Ok(res),
1756                         Err((chan, msg_handle_err)) => {
1757                                 let counterparty_node_id = chan.get_counterparty_node_id();
1758                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1759                         },
1760                 }
1761         };
1762 }
1763
1764 macro_rules! update_maps_on_chan_removal {
1765         ($self: expr, $channel_context: expr) => {{
1766                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1767                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1768                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1769                         short_to_chan_info.remove(&short_id);
1770                 } else {
1771                         // If the channel was never confirmed on-chain prior to its closure, remove the
1772                         // outbound SCID alias we used for it from the collision-prevention set. While we
1773                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1774                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1775                         // opening a million channels with us which are closed before we ever reach the funding
1776                         // stage.
1777                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1778                         debug_assert!(alias_removed);
1779                 }
1780                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1781         }}
1782 }
1783
1784 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1785 macro_rules! convert_chan_err {
1786         ($self: ident, $err: expr, $channel: expr, $channel_id: expr) => {
1787                 match $err {
1788                         ChannelError::Warn(msg) => {
1789                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), $channel_id.clone()))
1790                         },
1791                         ChannelError::Ignore(msg) => {
1792                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $channel_id.clone()))
1793                         },
1794                         ChannelError::Close(msg) => {
1795                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", log_bytes!($channel_id[..]), msg);
1796                                 update_maps_on_chan_removal!($self, &$channel.context);
1797                                 let shutdown_res = $channel.context.force_shutdown(true);
1798                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.context.get_user_id(),
1799                                         shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok(), $channel.context.get_value_satoshis()))
1800                         },
1801                 }
1802         };
1803         ($self: ident, $err: expr, $channel_context: expr, $channel_id: expr, UNFUNDED) => {
1804                 match $err {
1805                         // We should only ever have `ChannelError::Close` when unfunded channels error.
1806                         // In any case, just close the channel.
1807                         ChannelError::Warn(msg) | ChannelError::Ignore(msg) | ChannelError::Close(msg) => {
1808                                 log_error!($self.logger, "Closing unfunded channel {} due to an error: {}", log_bytes!($channel_id[..]), msg);
1809                                 update_maps_on_chan_removal!($self, &$channel_context);
1810                                 let shutdown_res = $channel_context.force_shutdown(false);
1811                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel_context.get_user_id(),
1812                                         shutdown_res, None, $channel_context.get_value_satoshis()))
1813                         },
1814                 }
1815         }
1816 }
1817
1818 macro_rules! break_chan_entry {
1819         ($self: ident, $res: expr, $entry: expr) => {
1820                 match $res {
1821                         Ok(res) => res,
1822                         Err(e) => {
1823                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1824                                 if drop {
1825                                         $entry.remove_entry();
1826                                 }
1827                                 break Err(res);
1828                         }
1829                 }
1830         }
1831 }
1832
1833 macro_rules! try_v1_outbound_chan_entry {
1834         ($self: ident, $res: expr, $entry: expr) => {
1835                 match $res {
1836                         Ok(res) => res,
1837                         Err(e) => {
1838                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut().context, $entry.key(), UNFUNDED);
1839                                 if drop {
1840                                         $entry.remove_entry();
1841                                 }
1842                                 return Err(res);
1843                         }
1844                 }
1845         }
1846 }
1847
1848 macro_rules! try_chan_entry {
1849         ($self: ident, $res: expr, $entry: expr) => {
1850                 match $res {
1851                         Ok(res) => res,
1852                         Err(e) => {
1853                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1854                                 if drop {
1855                                         $entry.remove_entry();
1856                                 }
1857                                 return Err(res);
1858                         }
1859                 }
1860         }
1861 }
1862
1863 macro_rules! remove_channel {
1864         ($self: expr, $entry: expr) => {
1865                 {
1866                         let channel = $entry.remove_entry().1;
1867                         update_maps_on_chan_removal!($self, &channel.context);
1868                         channel
1869                 }
1870         }
1871 }
1872
1873 macro_rules! send_channel_ready {
1874         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1875                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1876                         node_id: $channel.context.get_counterparty_node_id(),
1877                         msg: $channel_ready_msg,
1878                 });
1879                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1880                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
1881                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1882                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1883                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1884                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1885                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
1886                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1887                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1888                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1889                 }
1890         }}
1891 }
1892
1893 macro_rules! emit_channel_pending_event {
1894         ($locked_events: expr, $channel: expr) => {
1895                 if $channel.context.should_emit_channel_pending_event() {
1896                         $locked_events.push_back((events::Event::ChannelPending {
1897                                 channel_id: $channel.context.channel_id(),
1898                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
1899                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
1900                                 user_channel_id: $channel.context.get_user_id(),
1901                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
1902                         }, None));
1903                         $channel.context.set_channel_pending_event_emitted();
1904                 }
1905         }
1906 }
1907
1908 macro_rules! emit_channel_ready_event {
1909         ($locked_events: expr, $channel: expr) => {
1910                 if $channel.context.should_emit_channel_ready_event() {
1911                         debug_assert!($channel.context.channel_pending_event_emitted());
1912                         $locked_events.push_back((events::Event::ChannelReady {
1913                                 channel_id: $channel.context.channel_id(),
1914                                 user_channel_id: $channel.context.get_user_id(),
1915                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
1916                                 channel_type: $channel.context.get_channel_type().clone(),
1917                         }, None));
1918                         $channel.context.set_channel_ready_event_emitted();
1919                 }
1920         }
1921 }
1922
1923 macro_rules! handle_monitor_update_completion {
1924         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
1925                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
1926                         &$self.node_signer, $self.genesis_hash, &$self.default_configuration,
1927                         $self.best_block.read().unwrap().height());
1928                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
1929                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
1930                         // We only send a channel_update in the case where we are just now sending a
1931                         // channel_ready and the channel is in a usable state. We may re-send a
1932                         // channel_update later through the announcement_signatures process for public
1933                         // channels, but there's no reason not to just inform our counterparty of our fees
1934                         // now.
1935                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
1936                                 Some(events::MessageSendEvent::SendChannelUpdate {
1937                                         node_id: counterparty_node_id,
1938                                         msg,
1939                                 })
1940                         } else { None }
1941                 } else { None };
1942
1943                 let update_actions = $peer_state.monitor_update_blocked_actions
1944                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
1945
1946                 let htlc_forwards = $self.handle_channel_resumption(
1947                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
1948                         updates.commitment_update, updates.order, updates.accepted_htlcs,
1949                         updates.funding_broadcastable, updates.channel_ready,
1950                         updates.announcement_sigs);
1951                 if let Some(upd) = channel_update {
1952                         $peer_state.pending_msg_events.push(upd);
1953                 }
1954
1955                 let channel_id = $chan.context.channel_id();
1956                 core::mem::drop($peer_state_lock);
1957                 core::mem::drop($per_peer_state_lock);
1958
1959                 $self.handle_monitor_update_completion_actions(update_actions);
1960
1961                 if let Some(forwards) = htlc_forwards {
1962                         $self.forward_htlcs(&mut [forwards][..]);
1963                 }
1964                 $self.finalize_claims(updates.finalized_claimed_htlcs);
1965                 for failure in updates.failed_htlcs.drain(..) {
1966                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
1967                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
1968                 }
1969         } }
1970 }
1971
1972 macro_rules! handle_new_monitor_update {
1973         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, _internal, $remove: expr, $completed: expr) => { {
1974                 // update_maps_on_chan_removal needs to be able to take id_to_peer, so make sure we can in
1975                 // any case so that it won't deadlock.
1976                 debug_assert_ne!($self.id_to_peer.held_by_thread(), LockHeldState::HeldByThread);
1977                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
1978                 match $update_res {
1979                         ChannelMonitorUpdateStatus::InProgress => {
1980                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
1981                                         log_bytes!($chan.context.channel_id()[..]));
1982                                 Ok(false)
1983                         },
1984                         ChannelMonitorUpdateStatus::PermanentFailure => {
1985                                 log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateStatus::PermanentFailure",
1986                                         log_bytes!($chan.context.channel_id()[..]));
1987                                 update_maps_on_chan_removal!($self, &$chan.context);
1988                                 let res = Err(MsgHandleErrInternal::from_finish_shutdown(
1989                                         "ChannelMonitor storage failure".to_owned(), $chan.context.channel_id(),
1990                                         $chan.context.get_user_id(), $chan.context.force_shutdown(false),
1991                                         $self.get_channel_update_for_broadcast(&$chan).ok(), $chan.context.get_value_satoshis()));
1992                                 $remove;
1993                                 res
1994                         },
1995                         ChannelMonitorUpdateStatus::Completed => {
1996                                 $completed;
1997                                 Ok(true)
1998                         },
1999                 }
2000         } };
2001         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, MANUALLY_REMOVING_INITIAL_MONITOR, $remove: expr) => {
2002                 handle_new_monitor_update!($self, $update_res, $peer_state_lock, $peer_state,
2003                         $per_peer_state_lock, $chan, _internal, $remove,
2004                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2005         };
2006         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr, INITIAL_MONITOR) => {
2007                 handle_new_monitor_update!($self, $update_res, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan_entry.get_mut(), MANUALLY_REMOVING_INITIAL_MONITOR, $chan_entry.remove_entry())
2008         };
2009         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, MANUALLY_REMOVING, $remove: expr) => { {
2010                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2011                         .or_insert_with(Vec::new);
2012                 // During startup, we push monitor updates as background events through to here in
2013                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2014                 // filter for uniqueness here.
2015                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2016                         .unwrap_or_else(|| {
2017                                 in_flight_updates.push($update);
2018                                 in_flight_updates.len() - 1
2019                         });
2020                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2021                 handle_new_monitor_update!($self, update_res, $peer_state_lock, $peer_state,
2022                         $per_peer_state_lock, $chan, _internal, $remove,
2023                         {
2024                                 let _ = in_flight_updates.remove(idx);
2025                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2026                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2027                                 }
2028                         })
2029         } };
2030         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr) => {
2031                 handle_new_monitor_update!($self, $funding_txo, $update, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan_entry.get_mut(), MANUALLY_REMOVING, $chan_entry.remove_entry())
2032         }
2033 }
2034
2035 macro_rules! process_events_body {
2036         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2037                 let mut processed_all_events = false;
2038                 while !processed_all_events {
2039                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2040                                 return;
2041                         }
2042
2043                         let mut result = NotifyOption::SkipPersist;
2044
2045                         {
2046                                 // We'll acquire our total consistency lock so that we can be sure no other
2047                                 // persists happen while processing monitor events.
2048                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2049
2050                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2051                                 // ensure any startup-generated background events are handled first.
2052                                 if $self.process_background_events() == NotifyOption::DoPersist { result = NotifyOption::DoPersist; }
2053
2054                                 // TODO: This behavior should be documented. It's unintuitive that we query
2055                                 // ChannelMonitors when clearing other events.
2056                                 if $self.process_pending_monitor_events() {
2057                                         result = NotifyOption::DoPersist;
2058                                 }
2059                         }
2060
2061                         let pending_events = $self.pending_events.lock().unwrap().clone();
2062                         let num_events = pending_events.len();
2063                         if !pending_events.is_empty() {
2064                                 result = NotifyOption::DoPersist;
2065                         }
2066
2067                         let mut post_event_actions = Vec::new();
2068
2069                         for (event, action_opt) in pending_events {
2070                                 $event_to_handle = event;
2071                                 $handle_event;
2072                                 if let Some(action) = action_opt {
2073                                         post_event_actions.push(action);
2074                                 }
2075                         }
2076
2077                         {
2078                                 let mut pending_events = $self.pending_events.lock().unwrap();
2079                                 pending_events.drain(..num_events);
2080                                 processed_all_events = pending_events.is_empty();
2081                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2082                                 // updated here with the `pending_events` lock acquired.
2083                                 $self.pending_events_processor.store(false, Ordering::Release);
2084                         }
2085
2086                         if !post_event_actions.is_empty() {
2087                                 $self.handle_post_event_actions(post_event_actions);
2088                                 // If we had some actions, go around again as we may have more events now
2089                                 processed_all_events = false;
2090                         }
2091
2092                         if result == NotifyOption::DoPersist {
2093                                 $self.persistence_notifier.notify();
2094                         }
2095                 }
2096         }
2097 }
2098
2099 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>
2100 where
2101         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2102         T::Target: BroadcasterInterface,
2103         ES::Target: EntropySource,
2104         NS::Target: NodeSigner,
2105         SP::Target: SignerProvider,
2106         F::Target: FeeEstimator,
2107         R::Target: Router,
2108         L::Target: Logger,
2109 {
2110         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2111         ///
2112         /// The current time or latest block header time can be provided as the `current_timestamp`.
2113         ///
2114         /// This is the main "logic hub" for all channel-related actions, and implements
2115         /// [`ChannelMessageHandler`].
2116         ///
2117         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2118         ///
2119         /// Users need to notify the new `ChannelManager` when a new block is connected or
2120         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2121         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2122         /// more details.
2123         ///
2124         /// [`block_connected`]: chain::Listen::block_connected
2125         /// [`block_disconnected`]: chain::Listen::block_disconnected
2126         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2127         pub fn new(
2128                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2129                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2130                 current_timestamp: u32,
2131         ) -> Self {
2132                 let mut secp_ctx = Secp256k1::new();
2133                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2134                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2135                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2136                 ChannelManager {
2137                         default_configuration: config.clone(),
2138                         genesis_hash: genesis_block(params.network).header.block_hash(),
2139                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2140                         chain_monitor,
2141                         tx_broadcaster,
2142                         router,
2143
2144                         best_block: RwLock::new(params.best_block),
2145
2146                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2147                         pending_inbound_payments: Mutex::new(HashMap::new()),
2148                         pending_outbound_payments: OutboundPayments::new(),
2149                         forward_htlcs: Mutex::new(HashMap::new()),
2150                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2151                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2152                         id_to_peer: Mutex::new(HashMap::new()),
2153                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2154
2155                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2156                         secp_ctx,
2157
2158                         inbound_payment_key: expanded_inbound_key,
2159                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2160
2161                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2162
2163                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2164
2165                         per_peer_state: FairRwLock::new(HashMap::new()),
2166
2167                         pending_events: Mutex::new(VecDeque::new()),
2168                         pending_events_processor: AtomicBool::new(false),
2169                         pending_background_events: Mutex::new(Vec::new()),
2170                         total_consistency_lock: RwLock::new(()),
2171                         background_events_processed_since_startup: AtomicBool::new(false),
2172                         persistence_notifier: Notifier::new(),
2173
2174                         entropy_source,
2175                         node_signer,
2176                         signer_provider,
2177
2178                         logger,
2179                 }
2180         }
2181
2182         /// Gets the current configuration applied to all new channels.
2183         pub fn get_current_default_configuration(&self) -> &UserConfig {
2184                 &self.default_configuration
2185         }
2186
2187         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2188                 let height = self.best_block.read().unwrap().height();
2189                 let mut outbound_scid_alias = 0;
2190                 let mut i = 0;
2191                 loop {
2192                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2193                                 outbound_scid_alias += 1;
2194                         } else {
2195                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2196                         }
2197                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2198                                 break;
2199                         }
2200                         i += 1;
2201                         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"); }
2202                 }
2203                 outbound_scid_alias
2204         }
2205
2206         /// Creates a new outbound channel to the given remote node and with the given value.
2207         ///
2208         /// `user_channel_id` will be provided back as in
2209         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2210         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2211         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2212         /// is simply copied to events and otherwise ignored.
2213         ///
2214         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2215         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2216         ///
2217         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2218         /// generate a shutdown scriptpubkey or destination script set by
2219         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2220         ///
2221         /// Note that we do not check if you are currently connected to the given peer. If no
2222         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2223         /// the channel eventually being silently forgotten (dropped on reload).
2224         ///
2225         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2226         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2227         /// [`ChannelDetails::channel_id`] until after
2228         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2229         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2230         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2231         ///
2232         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2233         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2234         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2235         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<[u8; 32], APIError> {
2236                 if channel_value_satoshis < 1000 {
2237                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2238                 }
2239
2240                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2241                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2242                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2243
2244                 let per_peer_state = self.per_peer_state.read().unwrap();
2245
2246                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2247                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2248
2249                 let mut peer_state = peer_state_mutex.lock().unwrap();
2250                 let channel = {
2251                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2252                         let their_features = &peer_state.latest_features;
2253                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2254                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2255                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2256                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2257                         {
2258                                 Ok(res) => res,
2259                                 Err(e) => {
2260                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2261                                         return Err(e);
2262                                 },
2263                         }
2264                 };
2265                 let res = channel.get_open_channel(self.genesis_hash.clone());
2266
2267                 let temporary_channel_id = channel.context.channel_id();
2268                 match peer_state.outbound_v1_channel_by_id.entry(temporary_channel_id) {
2269                         hash_map::Entry::Occupied(_) => {
2270                                 if cfg!(fuzzing) {
2271                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2272                                 } else {
2273                                         panic!("RNG is bad???");
2274                                 }
2275                         },
2276                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
2277                 }
2278
2279                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2280                         node_id: their_network_key,
2281                         msg: res,
2282                 });
2283                 Ok(temporary_channel_id)
2284         }
2285
2286         fn list_funded_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<<SP::Target as SignerProvider>::Signer>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2287                 // Allocate our best estimate of the number of channels we have in the `res`
2288                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2289                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2290                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2291                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2292                 // the same channel.
2293                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2294                 {
2295                         let best_block_height = self.best_block.read().unwrap().height();
2296                         let per_peer_state = self.per_peer_state.read().unwrap();
2297                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2298                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2299                                 let peer_state = &mut *peer_state_lock;
2300                                 // Only `Channels` in the channel_by_id map can be considered funded.
2301                                 for (_channel_id, channel) in peer_state.channel_by_id.iter().filter(f) {
2302                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2303                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2304                                         res.push(details);
2305                                 }
2306                         }
2307                 }
2308                 res
2309         }
2310
2311         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2312         /// more information.
2313         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2314                 // Allocate our best estimate of the number of channels we have in the `res`
2315                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2316                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2317                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2318                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2319                 // the same channel.
2320                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2321                 {
2322                         let best_block_height = self.best_block.read().unwrap().height();
2323                         let per_peer_state = self.per_peer_state.read().unwrap();
2324                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2325                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2326                                 let peer_state = &mut *peer_state_lock;
2327                                 for (_channel_id, channel) in peer_state.channel_by_id.iter() {
2328                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2329                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2330                                         res.push(details);
2331                                 }
2332                                 for (_channel_id, channel) in peer_state.inbound_v1_channel_by_id.iter() {
2333                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2334                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2335                                         res.push(details);
2336                                 }
2337                                 for (_channel_id, channel) in peer_state.outbound_v1_channel_by_id.iter() {
2338                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2339                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2340                                         res.push(details);
2341                                 }
2342                         }
2343                 }
2344                 res
2345         }
2346
2347         /// Gets the list of usable channels, in random order. Useful as an argument to
2348         /// [`Router::find_route`] to ensure non-announced channels are used.
2349         ///
2350         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2351         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2352         /// are.
2353         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2354                 // Note we use is_live here instead of usable which leads to somewhat confused
2355                 // internal/external nomenclature, but that's ok cause that's probably what the user
2356                 // really wanted anyway.
2357                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2358         }
2359
2360         /// Gets the list of channels we have with a given counterparty, in random order.
2361         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2362                 let best_block_height = self.best_block.read().unwrap().height();
2363                 let per_peer_state = self.per_peer_state.read().unwrap();
2364
2365                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2366                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2367                         let peer_state = &mut *peer_state_lock;
2368                         let features = &peer_state.latest_features;
2369                         let chan_context_to_details = |context| {
2370                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2371                         };
2372                         return peer_state.channel_by_id
2373                                 .iter()
2374                                 .map(|(_, channel)| &channel.context)
2375                                 .chain(peer_state.outbound_v1_channel_by_id.iter().map(|(_, channel)| &channel.context))
2376                                 .chain(peer_state.inbound_v1_channel_by_id.iter().map(|(_, channel)| &channel.context))
2377                                 .map(chan_context_to_details)
2378                                 .collect();
2379                 }
2380                 vec![]
2381         }
2382
2383         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2384         /// successful path, or have unresolved HTLCs.
2385         ///
2386         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2387         /// result of a crash. If such a payment exists, is not listed here, and an
2388         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2389         ///
2390         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2391         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2392                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2393                         .filter_map(|(_, pending_outbound_payment)| match pending_outbound_payment {
2394                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2395                                         Some(RecentPaymentDetails::Pending {
2396                                                 payment_hash: *payment_hash,
2397                                                 total_msat: *total_msat,
2398                                         })
2399                                 },
2400                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2401                                         Some(RecentPaymentDetails::Abandoned { payment_hash: *payment_hash })
2402                                 },
2403                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2404                                         Some(RecentPaymentDetails::Fulfilled { payment_hash: *payment_hash })
2405                                 },
2406                                 PendingOutboundPayment::Legacy { .. } => None
2407                         })
2408                         .collect()
2409         }
2410
2411         /// Helper function that issues the channel close events
2412         fn issue_channel_close_events(&self, context: &ChannelContext<<SP::Target as SignerProvider>::Signer>, closure_reason: ClosureReason) {
2413                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2414                 match context.unbroadcasted_funding() {
2415                         Some(transaction) => {
2416                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2417                                         channel_id: context.channel_id(), transaction
2418                                 }, None));
2419                         },
2420                         None => {},
2421                 }
2422                 pending_events_lock.push_back((events::Event::ChannelClosed {
2423                         channel_id: context.channel_id(),
2424                         user_channel_id: context.get_user_id(),
2425                         reason: closure_reason,
2426                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2427                         channel_capacity_sats: Some(context.get_value_satoshis()),
2428                 }, None));
2429         }
2430
2431         fn close_channel_internal(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, override_shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
2432                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2433
2434                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2435                 let result: Result<(), _> = loop {
2436                         {
2437                                 let per_peer_state = self.per_peer_state.read().unwrap();
2438
2439                                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2440                                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2441
2442                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2443                                 let peer_state = &mut *peer_state_lock;
2444
2445                                 match peer_state.channel_by_id.entry(channel_id.clone()) {
2446                                         hash_map::Entry::Occupied(mut chan_entry) => {
2447                                                 let funding_txo_opt = chan_entry.get().context.get_funding_txo();
2448                                                 let their_features = &peer_state.latest_features;
2449                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) = chan_entry.get_mut()
2450                                                         .get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2451                                                 failed_htlcs = htlcs;
2452
2453                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2454                                                 // here as we don't need the monitor update to complete until we send a
2455                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2456                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2457                                                         node_id: *counterparty_node_id,
2458                                                         msg: shutdown_msg,
2459                                                 });
2460
2461                                                 // Update the monitor with the shutdown script if necessary.
2462                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2463                                                         break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2464                                                                 peer_state_lock, peer_state, per_peer_state, chan_entry).map(|_| ());
2465                                                 }
2466
2467                                                 if chan_entry.get().is_shutdown() {
2468                                                         let channel = remove_channel!(self, chan_entry);
2469                                                         if let Ok(channel_update) = self.get_channel_update_for_broadcast(&channel) {
2470                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2471                                                                         msg: channel_update
2472                                                                 });
2473                                                         }
2474                                                         self.issue_channel_close_events(&channel.context, ClosureReason::HolderForceClosed);
2475                                                 }
2476                                                 break Ok(());
2477                                         },
2478                                         hash_map::Entry::Vacant(_) => (),
2479                                 }
2480                         }
2481                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2482                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2483                         //
2484                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2485                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2486                         // TODO(dunxen): This is still not ideal as we're doing some extra lookups.
2487                         // Fix this with https://github.com/lightningdevkit/rust-lightning/issues/2422
2488                 };
2489
2490                 for htlc_source in failed_htlcs.drain(..) {
2491                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2492                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2493                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2494                 }
2495
2496                 let _ = handle_error!(self, result, *counterparty_node_id);
2497                 Ok(())
2498         }
2499
2500         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2501         /// will be accepted on the given channel, and after additional timeout/the closing of all
2502         /// pending HTLCs, the channel will be closed on chain.
2503         ///
2504         ///  * If we are the channel initiator, we will pay between our [`Background`] and
2505         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2506         ///    estimate.
2507         ///  * If our counterparty is the channel initiator, we will require a channel closing
2508         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
2509         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2510         ///    counterparty to pay as much fee as they'd like, however.
2511         ///
2512         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2513         ///
2514         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2515         /// generate a shutdown scriptpubkey or destination script set by
2516         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2517         /// channel.
2518         ///
2519         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2520         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2521         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2522         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2523         pub fn close_channel(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2524                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2525         }
2526
2527         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2528         /// will be accepted on the given channel, and after additional timeout/the closing of all
2529         /// pending HTLCs, the channel will be closed on chain.
2530         ///
2531         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2532         /// the channel being closed or not:
2533         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2534         ///    transaction. The upper-bound is set by
2535         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2536         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2537         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2538         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2539         ///    will appear on a force-closure transaction, whichever is lower).
2540         ///
2541         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2542         /// Will fail if a shutdown script has already been set for this channel by
2543         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2544         /// also be compatible with our and the counterparty's features.
2545         ///
2546         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2547         ///
2548         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2549         /// generate a shutdown scriptpubkey or destination script set by
2550         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2551         /// channel.
2552         ///
2553         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2554         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2555         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2556         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2557         pub fn close_channel_with_feerate_and_script(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
2558                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2559         }
2560
2561         #[inline]
2562         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
2563                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
2564                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
2565                 for htlc_source in failed_htlcs.drain(..) {
2566                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2567                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2568                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2569                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2570                 }
2571                 if let Some((_, funding_txo, monitor_update)) = monitor_update_option {
2572                         // There isn't anything we can do if we get an update failure - we're already
2573                         // force-closing. The monitor update on the required in-memory copy should broadcast
2574                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2575                         // ignore the result here.
2576                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2577                 }
2578         }
2579
2580         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2581         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2582         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2583         -> Result<PublicKey, APIError> {
2584                 let per_peer_state = self.per_peer_state.read().unwrap();
2585                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2586                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2587                 let (update_opt, counterparty_node_id) = {
2588                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2589                         let peer_state = &mut *peer_state_lock;
2590                         let closure_reason = if let Some(peer_msg) = peer_msg {
2591                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2592                         } else {
2593                                 ClosureReason::HolderForceClosed
2594                         };
2595                         if let hash_map::Entry::Occupied(chan) = peer_state.channel_by_id.entry(channel_id.clone()) {
2596                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2597                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2598                                 let mut chan = remove_channel!(self, chan);
2599                                 self.finish_force_close_channel(chan.context.force_shutdown(broadcast));
2600                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2601                         } else if let hash_map::Entry::Occupied(chan) = peer_state.outbound_v1_channel_by_id.entry(channel_id.clone()) {
2602                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2603                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2604                                 let mut chan = remove_channel!(self, chan);
2605                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
2606                                 // Unfunded channel has no update
2607                                 (None, chan.context.get_counterparty_node_id())
2608                         } else if let hash_map::Entry::Occupied(chan) = peer_state.inbound_v1_channel_by_id.entry(channel_id.clone()) {
2609                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2610                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2611                                 let mut chan = remove_channel!(self, chan);
2612                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
2613                                 // Unfunded channel has no update
2614                                 (None, chan.context.get_counterparty_node_id())
2615                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2616                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2617                                 // N.B. that we don't send any channel close event here: we
2618                                 // don't have a user_channel_id, and we never sent any opening
2619                                 // events anyway.
2620                                 (None, *peer_node_id)
2621                         } else {
2622                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*channel_id), peer_node_id) });
2623                         }
2624                 };
2625                 if let Some(update) = update_opt {
2626                         let mut peer_state = peer_state_mutex.lock().unwrap();
2627                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2628                                 msg: update
2629                         });
2630                 }
2631
2632                 Ok(counterparty_node_id)
2633         }
2634
2635         fn force_close_sending_error(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2636                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2637                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2638                         Ok(counterparty_node_id) => {
2639                                 let per_peer_state = self.per_peer_state.read().unwrap();
2640                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2641                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2642                                         peer_state.pending_msg_events.push(
2643                                                 events::MessageSendEvent::HandleError {
2644                                                         node_id: counterparty_node_id,
2645                                                         action: msgs::ErrorAction::SendErrorMessage {
2646                                                                 msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
2647                                                         },
2648                                                 }
2649                                         );
2650                                 }
2651                                 Ok(())
2652                         },
2653                         Err(e) => Err(e)
2654                 }
2655         }
2656
2657         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2658         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2659         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2660         /// channel.
2661         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2662         -> Result<(), APIError> {
2663                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2664         }
2665
2666         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2667         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2668         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2669         ///
2670         /// You can always get the latest local transaction(s) to broadcast from
2671         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2672         pub fn force_close_without_broadcasting_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2673         -> Result<(), APIError> {
2674                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2675         }
2676
2677         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2678         /// for each to the chain and rejecting new HTLCs on each.
2679         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2680                 for chan in self.list_channels() {
2681                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2682                 }
2683         }
2684
2685         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2686         /// local transaction(s).
2687         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2688                 for chan in self.list_channels() {
2689                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2690                 }
2691         }
2692
2693         fn construct_fwd_pending_htlc_info(
2694                 &self, msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
2695                 new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
2696                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
2697         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2698                 debug_assert!(next_packet_pubkey_opt.is_some());
2699                 let outgoing_packet = msgs::OnionPacket {
2700                         version: 0,
2701                         public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
2702                         hop_data: new_packet_bytes,
2703                         hmac: hop_hmac,
2704                 };
2705
2706                 let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
2707                         msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
2708                                 (short_channel_id, amt_to_forward, outgoing_cltv_value),
2709                         msgs::InboundOnionPayload::Receive { .. } =>
2710                                 return Err(InboundOnionErr {
2711                                         msg: "Final Node OnionHopData provided for us as an intermediary node",
2712                                         err_code: 0x4000 | 22,
2713                                         err_data: Vec::new(),
2714                                 }),
2715                 };
2716
2717                 Ok(PendingHTLCInfo {
2718                         routing: PendingHTLCRouting::Forward {
2719                                 onion_packet: outgoing_packet,
2720                                 short_channel_id,
2721                         },
2722                         payment_hash: msg.payment_hash,
2723                         incoming_shared_secret: shared_secret,
2724                         incoming_amt_msat: Some(msg.amount_msat),
2725                         outgoing_amt_msat: amt_to_forward,
2726                         outgoing_cltv_value,
2727                         skimmed_fee_msat: None,
2728                 })
2729         }
2730
2731         fn construct_recv_pending_htlc_info(
2732                 &self, hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
2733                 amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
2734                 counterparty_skimmed_fee_msat: Option<u64>,
2735         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2736                 let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
2737                         msgs::InboundOnionPayload::Receive {
2738                                 payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
2739                         } =>
2740                                 (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
2741                         _ =>
2742                                 return Err(InboundOnionErr {
2743                                         err_code: 0x4000|22,
2744                                         err_data: Vec::new(),
2745                                         msg: "Got non final data with an HMAC of 0",
2746                                 }),
2747                 };
2748                 // final_incorrect_cltv_expiry
2749                 if outgoing_cltv_value > cltv_expiry {
2750                         return Err(InboundOnionErr {
2751                                 msg: "Upstream node set CLTV to less than the CLTV set by the sender",
2752                                 err_code: 18,
2753                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2754                         })
2755                 }
2756                 // final_expiry_too_soon
2757                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2758                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2759                 //
2760                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2761                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2762                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2763                 let current_height: u32 = self.best_block.read().unwrap().height();
2764                 if (outgoing_cltv_value as u64) <= current_height as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
2765                         let mut err_data = Vec::with_capacity(12);
2766                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2767                         err_data.extend_from_slice(&current_height.to_be_bytes());
2768                         return Err(InboundOnionErr {
2769                                 err_code: 0x4000 | 15, err_data,
2770                                 msg: "The final CLTV expiry is too soon to handle",
2771                         });
2772                 }
2773                 if (!allow_underpay && onion_amt_msat > amt_msat) ||
2774                         (allow_underpay && onion_amt_msat >
2775                          amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
2776                 {
2777                         return Err(InboundOnionErr {
2778                                 err_code: 19,
2779                                 err_data: amt_msat.to_be_bytes().to_vec(),
2780                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2781                         });
2782                 }
2783
2784                 let routing = if let Some(payment_preimage) = keysend_preimage {
2785                         // We need to check that the sender knows the keysend preimage before processing this
2786                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
2787                         // could discover the final destination of X, by probing the adjacent nodes on the route
2788                         // with a keysend payment of identical payment hash to X and observing the processing
2789                         // time discrepancies due to a hash collision with X.
2790                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2791                         if hashed_preimage != payment_hash {
2792                                 return Err(InboundOnionErr {
2793                                         err_code: 0x4000|22,
2794                                         err_data: Vec::new(),
2795                                         msg: "Payment preimage didn't match payment hash",
2796                                 });
2797                         }
2798                         if !self.default_configuration.accept_mpp_keysend && payment_data.is_some() {
2799                                 return Err(InboundOnionErr {
2800                                         err_code: 0x4000|22,
2801                                         err_data: Vec::new(),
2802                                         msg: "We don't support MPP keysend payments",
2803                                 });
2804                         }
2805                         PendingHTLCRouting::ReceiveKeysend {
2806                                 payment_data,
2807                                 payment_preimage,
2808                                 payment_metadata,
2809                                 incoming_cltv_expiry: outgoing_cltv_value,
2810                                 custom_tlvs,
2811                         }
2812                 } else if let Some(data) = payment_data {
2813                         PendingHTLCRouting::Receive {
2814                                 payment_data: data,
2815                                 payment_metadata,
2816                                 incoming_cltv_expiry: outgoing_cltv_value,
2817                                 phantom_shared_secret,
2818                                 custom_tlvs,
2819                         }
2820                 } else {
2821                         return Err(InboundOnionErr {
2822                                 err_code: 0x4000|0x2000|3,
2823                                 err_data: Vec::new(),
2824                                 msg: "We require payment_secrets",
2825                         });
2826                 };
2827                 Ok(PendingHTLCInfo {
2828                         routing,
2829                         payment_hash,
2830                         incoming_shared_secret: shared_secret,
2831                         incoming_amt_msat: Some(amt_msat),
2832                         outgoing_amt_msat: onion_amt_msat,
2833                         outgoing_cltv_value,
2834                         skimmed_fee_msat: counterparty_skimmed_fee_msat,
2835                 })
2836         }
2837
2838         fn decode_update_add_htlc_onion(
2839                 &self, msg: &msgs::UpdateAddHTLC
2840         ) -> Result<(onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg> {
2841                 macro_rules! return_malformed_err {
2842                         ($msg: expr, $err_code: expr) => {
2843                                 {
2844                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2845                                         return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
2846                                                 channel_id: msg.channel_id,
2847                                                 htlc_id: msg.htlc_id,
2848                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
2849                                                 failure_code: $err_code,
2850                                         }));
2851                                 }
2852                         }
2853                 }
2854
2855                 if let Err(_) = msg.onion_routing_packet.public_key {
2856                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
2857                 }
2858
2859                 let shared_secret = self.node_signer.ecdh(
2860                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
2861                 ).unwrap().secret_bytes();
2862
2863                 if msg.onion_routing_packet.version != 0 {
2864                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
2865                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
2866                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
2867                         //receiving node would have to brute force to figure out which version was put in the
2868                         //packet by the node that send us the message, in the case of hashing the hop_data, the
2869                         //node knows the HMAC matched, so they already know what is there...
2870                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
2871                 }
2872                 macro_rules! return_err {
2873                         ($msg: expr, $err_code: expr, $data: expr) => {
2874                                 {
2875                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2876                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2877                                                 channel_id: msg.channel_id,
2878                                                 htlc_id: msg.htlc_id,
2879                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2880                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2881                                         }));
2882                                 }
2883                         }
2884                 }
2885
2886                 let next_hop = match onion_utils::decode_next_payment_hop(shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac, msg.payment_hash) {
2887                         Ok(res) => res,
2888                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2889                                 return_malformed_err!(err_msg, err_code);
2890                         },
2891                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2892                                 return_err!(err_msg, err_code, &[0; 0]);
2893                         },
2894                 };
2895                 let (outgoing_scid, outgoing_amt_msat, outgoing_cltv_value, next_packet_pk_opt) = match next_hop {
2896                         onion_utils::Hop::Forward {
2897                                 next_hop_data: msgs::InboundOnionPayload::Forward {
2898                                         short_channel_id, amt_to_forward, outgoing_cltv_value
2899                                 }, ..
2900                         } => {
2901                                 let next_pk = onion_utils::next_hop_packet_pubkey(&self.secp_ctx,
2902                                         msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
2903                                 (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(next_pk))
2904                         },
2905                         // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
2906                         // inbound channel's state.
2907                         onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
2908                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } => {
2909                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
2910                         }
2911                 };
2912
2913                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
2914                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
2915                 if let Some((err, mut code, chan_update)) = loop {
2916                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
2917                         let forwarding_chan_info_opt = match id_option {
2918                                 None => { // unknown_next_peer
2919                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2920                                         // phantom or an intercept.
2921                                         if (self.default_configuration.accept_intercept_htlcs &&
2922                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)) ||
2923                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)
2924                                         {
2925                                                 None
2926                                         } else {
2927                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2928                                         }
2929                                 },
2930                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
2931                         };
2932                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
2933                                 let per_peer_state = self.per_peer_state.read().unwrap();
2934                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2935                                 if peer_state_mutex_opt.is_none() {
2936                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2937                                 }
2938                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2939                                 let peer_state = &mut *peer_state_lock;
2940                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id) {
2941                                         None => {
2942                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
2943                                                 // have no consistency guarantees.
2944                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2945                                         },
2946                                         Some(chan) => chan
2947                                 };
2948                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2949                                         // Note that the behavior here should be identical to the above block - we
2950                                         // should NOT reveal the existence or non-existence of a private channel if
2951                                         // we don't allow forwards outbound over them.
2952                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2953                                 }
2954                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
2955                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
2956                                         // "refuse to forward unless the SCID alias was used", so we pretend
2957                                         // we don't have the channel here.
2958                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
2959                                 }
2960                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
2961
2962                                 // Note that we could technically not return an error yet here and just hope
2963                                 // that the connection is reestablished or monitor updated by the time we get
2964                                 // around to doing the actual forward, but better to fail early if we can and
2965                                 // hopefully an attacker trying to path-trace payments cannot make this occur
2966                                 // on a small/per-node/per-channel scale.
2967                                 if !chan.context.is_live() { // channel_disabled
2968                                         // If the channel_update we're going to return is disabled (i.e. the
2969                                         // peer has been disabled for some time), return `channel_disabled`,
2970                                         // otherwise return `temporary_channel_failure`.
2971                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
2972                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
2973                                         } else {
2974                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
2975                                         }
2976                                 }
2977                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
2978                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
2979                                 }
2980                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
2981                                         break Some((err, code, chan_update_opt));
2982                                 }
2983                                 chan_update_opt
2984                         } else {
2985                                 if (msg.cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
2986                                         // We really should set `incorrect_cltv_expiry` here but as we're not
2987                                         // forwarding over a real channel we can't generate a channel_update
2988                                         // for it. Instead we just return a generic temporary_node_failure.
2989                                         break Some((
2990                                                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
2991                                                         0x2000 | 2, None,
2992                                         ));
2993                                 }
2994                                 None
2995                         };
2996
2997                         let cur_height = self.best_block.read().unwrap().height() + 1;
2998                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
2999                         // but we want to be robust wrt to counterparty packet sanitization (see
3000                         // HTLC_FAIL_BACK_BUFFER rationale).
3001                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
3002                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
3003                         }
3004                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
3005                                 break Some(("CLTV expiry is too far in the future", 21, None));
3006                         }
3007                         // If the HTLC expires ~now, don't bother trying to forward it to our
3008                         // counterparty. They should fail it anyway, but we don't want to bother with
3009                         // the round-trips or risk them deciding they definitely want the HTLC and
3010                         // force-closing to ensure they get it if we're offline.
3011                         // We previously had a much more aggressive check here which tried to ensure
3012                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
3013                         // but there is no need to do that, and since we're a bit conservative with our
3014                         // risk threshold it just results in failing to forward payments.
3015                         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
3016                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
3017                         }
3018
3019                         break None;
3020                 }
3021                 {
3022                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3023                         if let Some(chan_update) = chan_update {
3024                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3025                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3026                                 }
3027                                 else if code == 0x1000 | 13 {
3028                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3029                                 }
3030                                 else if code == 0x1000 | 20 {
3031                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3032                                         0u16.write(&mut res).expect("Writes cannot fail");
3033                                 }
3034                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3035                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3036                                 chan_update.write(&mut res).expect("Writes cannot fail");
3037                         } else if code & 0x1000 == 0x1000 {
3038                                 // If we're trying to return an error that requires a `channel_update` but
3039                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3040                                 // generate an update), just use the generic "temporary_node_failure"
3041                                 // instead.
3042                                 code = 0x2000 | 2;
3043                         }
3044                         return_err!(err, code, &res.0[..]);
3045                 }
3046                 Ok((next_hop, shared_secret, next_packet_pk_opt))
3047         }
3048
3049         fn construct_pending_htlc_status<'a>(
3050                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3051                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3052         ) -> PendingHTLCStatus {
3053                 macro_rules! return_err {
3054                         ($msg: expr, $err_code: expr, $data: expr) => {
3055                                 {
3056                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3057                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3058                                                 channel_id: msg.channel_id,
3059                                                 htlc_id: msg.htlc_id,
3060                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3061                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3062                                         }));
3063                                 }
3064                         }
3065                 }
3066                 match decoded_hop {
3067                         onion_utils::Hop::Receive(next_hop_data) => {
3068                                 // OUR PAYMENT!
3069                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3070                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat)
3071                                 {
3072                                         Ok(info) => {
3073                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3074                                                 // message, however that would leak that we are the recipient of this payment, so
3075                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3076                                                 // delay) once they've send us a commitment_signed!
3077                                                 PendingHTLCStatus::Forward(info)
3078                                         },
3079                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3080                                 }
3081                         },
3082                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3083                                 match self.construct_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3084                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3085                                         Ok(info) => PendingHTLCStatus::Forward(info),
3086                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3087                                 }
3088                         }
3089                 }
3090         }
3091
3092         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3093         /// public, and thus should be called whenever the result is going to be passed out in a
3094         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3095         ///
3096         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3097         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3098         /// storage and the `peer_state` lock has been dropped.
3099         ///
3100         /// [`channel_update`]: msgs::ChannelUpdate
3101         /// [`internal_closing_signed`]: Self::internal_closing_signed
3102         fn get_channel_update_for_broadcast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3103                 if !chan.context.should_announce() {
3104                         return Err(LightningError {
3105                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3106                                 action: msgs::ErrorAction::IgnoreError
3107                         });
3108                 }
3109                 if chan.context.get_short_channel_id().is_none() {
3110                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3111                 }
3112                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", log_bytes!(chan.context.channel_id()));
3113                 self.get_channel_update_for_unicast(chan)
3114         }
3115
3116         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3117         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3118         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3119         /// provided evidence that they know about the existence of the channel.
3120         ///
3121         /// Note that through [`internal_closing_signed`], this function is called without the
3122         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3123         /// removed from the storage and the `peer_state` lock has been dropped.
3124         ///
3125         /// [`channel_update`]: msgs::ChannelUpdate
3126         /// [`internal_closing_signed`]: Self::internal_closing_signed
3127         fn get_channel_update_for_unicast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3128                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.context.channel_id()));
3129                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3130                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3131                         Some(id) => id,
3132                 };
3133
3134                 self.get_channel_update_for_onion(short_channel_id, chan)
3135         }
3136
3137         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3138                 log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.context.channel_id()));
3139                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3140
3141                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3142                         ChannelUpdateStatus::Enabled => true,
3143                         ChannelUpdateStatus::DisabledStaged(_) => true,
3144                         ChannelUpdateStatus::Disabled => false,
3145                         ChannelUpdateStatus::EnabledStaged(_) => false,
3146                 };
3147
3148                 let unsigned = msgs::UnsignedChannelUpdate {
3149                         chain_hash: self.genesis_hash,
3150                         short_channel_id,
3151                         timestamp: chan.context.get_update_time_counter(),
3152                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3153                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3154                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3155                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3156                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3157                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3158                         excess_data: Vec::new(),
3159                 };
3160                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3161                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3162                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3163                 // channel.
3164                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3165
3166                 Ok(msgs::ChannelUpdate {
3167                         signature: sig,
3168                         contents: unsigned
3169                 })
3170         }
3171
3172         #[cfg(test)]
3173         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> {
3174                 let _lck = self.total_consistency_lock.read().unwrap();
3175                 self.send_payment_along_path(SendAlongPathArgs {
3176                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3177                         session_priv_bytes
3178                 })
3179         }
3180
3181         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3182                 let SendAlongPathArgs {
3183                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3184                         session_priv_bytes
3185                 } = args;
3186                 // The top-level caller should hold the total_consistency_lock read lock.
3187                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3188
3189                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.hops.first().unwrap().short_channel_id);
3190                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3191                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3192
3193                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3194                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3195                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3196
3197                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3198                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3199
3200                 let err: Result<(), _> = loop {
3201                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3202                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3203                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3204                         };
3205
3206                         let per_peer_state = self.per_peer_state.read().unwrap();
3207                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3208                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3209                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3210                         let peer_state = &mut *peer_state_lock;
3211                         if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(id) {
3212                                 if !chan.get().context.is_live() {
3213                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3214                                 }
3215                                 let funding_txo = chan.get().context.get_funding_txo().unwrap();
3216                                 let send_res = chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3217                                         htlc_cltv, HTLCSource::OutboundRoute {
3218                                                 path: path.clone(),
3219                                                 session_priv: session_priv.clone(),
3220                                                 first_hop_htlc_msat: htlc_msat,
3221                                                 payment_id,
3222                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3223                                 match break_chan_entry!(self, send_res, chan) {
3224                                         Some(monitor_update) => {
3225                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3226                                                         Err(e) => break Err(e),
3227                                                         Ok(false) => {
3228                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3229                                                                 // docs) that we will resend the commitment update once monitor
3230                                                                 // updating completes. Therefore, we must return an error
3231                                                                 // indicating that it is unsafe to retry the payment wholesale,
3232                                                                 // which we do in the send_payment check for
3233                                                                 // MonitorUpdateInProgress, below.
3234                                                                 return Err(APIError::MonitorUpdateInProgress);
3235                                                         },
3236                                                         Ok(true) => {},
3237                                                 }
3238                                         },
3239                                         None => { },
3240                                 }
3241                         } else {
3242                                 // The channel was likely removed after we fetched the id from the
3243                                 // `short_to_chan_info` map, but before we successfully locked the
3244                                 // `channel_by_id` map.
3245                                 // This can occur as no consistency guarantees exists between the two maps.
3246                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3247                         }
3248                         return Ok(());
3249                 };
3250
3251                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3252                         Ok(_) => unreachable!(),
3253                         Err(e) => {
3254                                 Err(APIError::ChannelUnavailable { err: e.err })
3255                         },
3256                 }
3257         }
3258
3259         /// Sends a payment along a given route.
3260         ///
3261         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3262         /// fields for more info.
3263         ///
3264         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3265         /// [`PeerManager::process_events`]).
3266         ///
3267         /// # Avoiding Duplicate Payments
3268         ///
3269         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3270         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3271         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3272         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3273         /// second payment with the same [`PaymentId`].
3274         ///
3275         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3276         /// tracking of payments, including state to indicate once a payment has completed. Because you
3277         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3278         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3279         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3280         ///
3281         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3282         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3283         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3284         /// [`ChannelManager::list_recent_payments`] for more information.
3285         ///
3286         /// # Possible Error States on [`PaymentSendFailure`]
3287         ///
3288         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3289         /// each entry matching the corresponding-index entry in the route paths, see
3290         /// [`PaymentSendFailure`] for more info.
3291         ///
3292         /// In general, a path may raise:
3293         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3294         ///    node public key) is specified.
3295         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available for updates
3296         ///    (including due to previous monitor update failure or new permanent monitor update
3297         ///    failure).
3298         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3299         ///    relevant updates.
3300         ///
3301         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3302         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3303         /// different route unless you intend to pay twice!
3304         ///
3305         /// [`RouteHop`]: crate::routing::router::RouteHop
3306         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3307         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3308         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3309         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3310         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3311         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3312                 let best_block_height = self.best_block.read().unwrap().height();
3313                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3314                 self.pending_outbound_payments
3315                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3316                                 &self.entropy_source, &self.node_signer, best_block_height,
3317                                 |args| self.send_payment_along_path(args))
3318         }
3319
3320         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3321         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3322         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3323                 let best_block_height = self.best_block.read().unwrap().height();
3324                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3325                 self.pending_outbound_payments
3326                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3327                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3328                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3329                                 &self.pending_events, |args| self.send_payment_along_path(args))
3330         }
3331
3332         #[cfg(test)]
3333         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> {
3334                 let best_block_height = self.best_block.read().unwrap().height();
3335                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3336                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3337                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3338                         best_block_height, |args| self.send_payment_along_path(args))
3339         }
3340
3341         #[cfg(test)]
3342         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> {
3343                 let best_block_height = self.best_block.read().unwrap().height();
3344                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3345         }
3346
3347         #[cfg(test)]
3348         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3349                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3350         }
3351
3352
3353         /// Signals that no further retries for the given payment should occur. Useful if you have a
3354         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3355         /// retries are exhausted.
3356         ///
3357         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3358         /// as there are no remaining pending HTLCs for this payment.
3359         ///
3360         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3361         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3362         /// determine the ultimate status of a payment.
3363         ///
3364         /// If an [`Event::PaymentFailed`] event is generated and we restart without this
3365         /// [`ChannelManager`] having been persisted, another [`Event::PaymentFailed`] may be generated.
3366         ///
3367         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3368         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3369         pub fn abandon_payment(&self, payment_id: PaymentId) {
3370                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3371                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3372         }
3373
3374         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3375         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3376         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3377         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3378         /// never reach the recipient.
3379         ///
3380         /// See [`send_payment`] documentation for more details on the return value of this function
3381         /// and idempotency guarantees provided by the [`PaymentId`] key.
3382         ///
3383         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3384         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3385         ///
3386         /// [`send_payment`]: Self::send_payment
3387         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3388                 let best_block_height = self.best_block.read().unwrap().height();
3389                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3390                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3391                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3392                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3393         }
3394
3395         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3396         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3397         ///
3398         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3399         /// payments.
3400         ///
3401         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3402         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> {
3403                 let best_block_height = self.best_block.read().unwrap().height();
3404                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3405                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3406                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3407                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3408                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3409         }
3410
3411         /// Send a payment that is probing the given route for liquidity. We calculate the
3412         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3413         /// us to easily discern them from real payments.
3414         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3415                 let best_block_height = self.best_block.read().unwrap().height();
3416                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3417                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3418                         &self.entropy_source, &self.node_signer, best_block_height,
3419                         |args| self.send_payment_along_path(args))
3420         }
3421
3422         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3423         /// payment probe.
3424         #[cfg(test)]
3425         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3426                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3427         }
3428
3429         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3430         /// which checks the correctness of the funding transaction given the associated channel.
3431         fn funding_transaction_generated_intern<FundingOutput: Fn(&OutboundV1Channel<<SP::Target as SignerProvider>::Signer>, &Transaction) -> Result<OutPoint, APIError>>(
3432                 &self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction, find_funding_output: FundingOutput
3433         ) -> Result<(), APIError> {
3434                 let per_peer_state = self.per_peer_state.read().unwrap();
3435                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3436                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3437
3438                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3439                 let peer_state = &mut *peer_state_lock;
3440                 let (chan, msg) = match peer_state.outbound_v1_channel_by_id.remove(temporary_channel_id) {
3441                         Some(chan) => {
3442                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3443
3444                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, &self.logger)
3445                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3446                                                 let channel_id = chan.context.channel_id();
3447                                                 let user_id = chan.context.get_user_id();
3448                                                 let shutdown_res = chan.context.force_shutdown(false);
3449                                                 let channel_capacity = chan.context.get_value_satoshis();
3450                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3451                                         } else { unreachable!(); });
3452                                 match funding_res {
3453                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3454                                         Err((chan, err)) => {
3455                                                 mem::drop(peer_state_lock);
3456                                                 mem::drop(per_peer_state);
3457
3458                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3459                                                 return Err(APIError::ChannelUnavailable {
3460                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3461                                                 });
3462                                         },
3463                                 }
3464                         },
3465                         None => {
3466                                 return Err(APIError::ChannelUnavailable {
3467                                         err: format!(
3468                                                 "Channel with id {} not found for the passed counterparty node_id {}",
3469                                                 log_bytes!(*temporary_channel_id), counterparty_node_id),
3470                                 })
3471                         },
3472                 };
3473
3474                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3475                         node_id: chan.context.get_counterparty_node_id(),
3476                         msg,
3477                 });
3478                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3479                         hash_map::Entry::Occupied(_) => {
3480                                 panic!("Generated duplicate funding txid?");
3481                         },
3482                         hash_map::Entry::Vacant(e) => {
3483                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3484                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3485                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3486                                 }
3487                                 e.insert(chan);
3488                         }
3489                 }
3490                 Ok(())
3491         }
3492
3493         #[cfg(test)]
3494         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3495                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |_, tx| {
3496                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3497                 })
3498         }
3499
3500         /// Call this upon creation of a funding transaction for the given channel.
3501         ///
3502         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3503         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3504         ///
3505         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3506         /// across the p2p network.
3507         ///
3508         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3509         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3510         ///
3511         /// May panic if the output found in the funding transaction is duplicative with some other
3512         /// channel (note that this should be trivially prevented by using unique funding transaction
3513         /// keys per-channel).
3514         ///
3515         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3516         /// counterparty's signature the funding transaction will automatically be broadcast via the
3517         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3518         ///
3519         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3520         /// not currently support replacing a funding transaction on an existing channel. Instead,
3521         /// create a new channel with a conflicting funding transaction.
3522         ///
3523         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3524         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3525         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3526         /// for more details.
3527         ///
3528         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3529         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3530         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3531                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3532
3533                 for inp in funding_transaction.input.iter() {
3534                         if inp.witness.is_empty() {
3535                                 return Err(APIError::APIMisuseError {
3536                                         err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3537                                 });
3538                         }
3539                 }
3540                 {
3541                         let height = self.best_block.read().unwrap().height();
3542                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3543                         // lower than the next block height. However, the modules constituting our Lightning
3544                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3545                         // module is ahead of LDK, only allow one more block of headroom.
3546                         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 {
3547                                 return Err(APIError::APIMisuseError {
3548                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3549                                 });
3550                         }
3551                 }
3552                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |chan, tx| {
3553                         if tx.output.len() > u16::max_value() as usize {
3554                                 return Err(APIError::APIMisuseError {
3555                                         err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3556                                 });
3557                         }
3558
3559                         let mut output_index = None;
3560                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3561                         for (idx, outp) in tx.output.iter().enumerate() {
3562                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3563                                         if output_index.is_some() {
3564                                                 return Err(APIError::APIMisuseError {
3565                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3566                                                 });
3567                                         }
3568                                         output_index = Some(idx as u16);
3569                                 }
3570                         }
3571                         if output_index.is_none() {
3572                                 return Err(APIError::APIMisuseError {
3573                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3574                                 });
3575                         }
3576                         Ok(OutPoint { txid: tx.txid(), index: output_index.unwrap() })
3577                 })
3578         }
3579
3580         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3581         ///
3582         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3583         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3584         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3585         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3586         ///
3587         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3588         /// `counterparty_node_id` is provided.
3589         ///
3590         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3591         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3592         ///
3593         /// If an error is returned, none of the updates should be considered applied.
3594         ///
3595         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3596         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3597         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3598         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3599         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3600         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3601         /// [`APIMisuseError`]: APIError::APIMisuseError
3602         pub fn update_partial_channel_config(
3603                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config_update: &ChannelConfigUpdate,
3604         ) -> Result<(), APIError> {
3605                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
3606                         return Err(APIError::APIMisuseError {
3607                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
3608                         });
3609                 }
3610
3611                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3612                 let per_peer_state = self.per_peer_state.read().unwrap();
3613                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3614                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3615                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3616                 let peer_state = &mut *peer_state_lock;
3617                 for channel_id in channel_ids {
3618                         if !peer_state.has_channel(channel_id) {
3619                                 return Err(APIError::ChannelUnavailable {
3620                                         err: format!("Channel with ID {} was not found for the passed counterparty_node_id {}", log_bytes!(*channel_id), counterparty_node_id),
3621                                 });
3622                         };
3623                 }
3624                 for channel_id in channel_ids {
3625                         if let Some(channel) = peer_state.channel_by_id.get_mut(channel_id) {
3626                                 let mut config = channel.context.config();
3627                                 config.apply(config_update);
3628                                 if !channel.context.update_config(&config) {
3629                                         continue;
3630                                 }
3631                                 if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
3632                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
3633                                 } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
3634                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
3635                                                 node_id: channel.context.get_counterparty_node_id(),
3636                                                 msg,
3637                                         });
3638                                 }
3639                                 continue;
3640                         }
3641
3642                         let context = if let Some(channel) = peer_state.inbound_v1_channel_by_id.get_mut(channel_id) {
3643                                 &mut channel.context
3644                         } else if let Some(channel) = peer_state.outbound_v1_channel_by_id.get_mut(channel_id) {
3645                                 &mut channel.context
3646                         } else {
3647                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
3648                                 debug_assert!(false);
3649                                 return Err(APIError::ChannelUnavailable {
3650                                         err: format!(
3651                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
3652                                                 log_bytes!(*channel_id), counterparty_node_id),
3653                                 });
3654                         };
3655                         let mut config = context.config();
3656                         config.apply(config_update);
3657                         // We update the config, but we MUST NOT broadcast a `channel_update` before `channel_ready`
3658                         // which would be the case for pending inbound/outbound channels.
3659                         context.update_config(&config);
3660                 }
3661                 Ok(())
3662         }
3663
3664         /// Atomically updates the [`ChannelConfig`] for the given channels.
3665         ///
3666         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3667         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3668         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3669         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3670         ///
3671         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3672         /// `counterparty_node_id` is provided.
3673         ///
3674         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3675         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3676         ///
3677         /// If an error is returned, none of the updates should be considered applied.
3678         ///
3679         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3680         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3681         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3682         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3683         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3684         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3685         /// [`APIMisuseError`]: APIError::APIMisuseError
3686         pub fn update_channel_config(
3687                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
3688         ) -> Result<(), APIError> {
3689                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
3690         }
3691
3692         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
3693         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
3694         ///
3695         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
3696         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
3697         ///
3698         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
3699         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
3700         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
3701         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
3702         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
3703         ///
3704         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
3705         /// you from forwarding more than you received. See
3706         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
3707         /// than expected.
3708         ///
3709         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3710         /// backwards.
3711         ///
3712         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
3713         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3714         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
3715         // TODO: when we move to deciding the best outbound channel at forward time, only take
3716         // `next_node_id` and not `next_hop_channel_id`
3717         pub fn forward_intercepted_htlc(&self, intercept_id: InterceptId, next_hop_channel_id: &[u8; 32], next_node_id: PublicKey, amt_to_forward_msat: u64) -> Result<(), APIError> {
3718                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3719
3720                 let next_hop_scid = {
3721                         let peer_state_lock = self.per_peer_state.read().unwrap();
3722                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
3723                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
3724                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3725                         let peer_state = &mut *peer_state_lock;
3726                         match peer_state.channel_by_id.get(next_hop_channel_id) {
3727                                 Some(chan) => {
3728                                         if !chan.context.is_usable() {
3729                                                 return Err(APIError::ChannelUnavailable {
3730                                                         err: format!("Channel with id {} not fully established", log_bytes!(*next_hop_channel_id))
3731                                                 })
3732                                         }
3733                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
3734                                 },
3735                                 None => return Err(APIError::ChannelUnavailable {
3736                                         err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
3737                                                 log_bytes!(*next_hop_channel_id), next_node_id)
3738                                 })
3739                         }
3740                 };
3741
3742                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3743                         .ok_or_else(|| APIError::APIMisuseError {
3744                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3745                         })?;
3746
3747                 let routing = match payment.forward_info.routing {
3748                         PendingHTLCRouting::Forward { onion_packet, .. } => {
3749                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
3750                         },
3751                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
3752                 };
3753                 let skimmed_fee_msat =
3754                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
3755                 let pending_htlc_info = PendingHTLCInfo {
3756                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
3757                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
3758                 };
3759
3760                 let mut per_source_pending_forward = [(
3761                         payment.prev_short_channel_id,
3762                         payment.prev_funding_outpoint,
3763                         payment.prev_user_channel_id,
3764                         vec![(pending_htlc_info, payment.prev_htlc_id)]
3765                 )];
3766                 self.forward_htlcs(&mut per_source_pending_forward);
3767                 Ok(())
3768         }
3769
3770         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
3771         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
3772         ///
3773         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3774         /// backwards.
3775         ///
3776         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3777         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
3778                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3779
3780                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3781                         .ok_or_else(|| APIError::APIMisuseError {
3782                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3783                         })?;
3784
3785                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
3786                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3787                                 short_channel_id: payment.prev_short_channel_id,
3788                                 outpoint: payment.prev_funding_outpoint,
3789                                 htlc_id: payment.prev_htlc_id,
3790                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
3791                                 phantom_shared_secret: None,
3792                         });
3793
3794                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
3795                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
3796                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
3797                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
3798
3799                 Ok(())
3800         }
3801
3802         /// Processes HTLCs which are pending waiting on random forward delay.
3803         ///
3804         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
3805         /// Will likely generate further events.
3806         pub fn process_pending_htlc_forwards(&self) {
3807                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3808
3809                 let mut new_events = VecDeque::new();
3810                 let mut failed_forwards = Vec::new();
3811                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
3812                 {
3813                         let mut forward_htlcs = HashMap::new();
3814                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
3815
3816                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
3817                                 if short_chan_id != 0 {
3818                                         macro_rules! forwarding_channel_not_found {
3819                                                 () => {
3820                                                         for forward_info in pending_forwards.drain(..) {
3821                                                                 match forward_info {
3822                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3823                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3824                                                                                 forward_info: PendingHTLCInfo {
3825                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
3826                                                                                         outgoing_cltv_value, ..
3827                                                                                 }
3828                                                                         }) => {
3829                                                                                 macro_rules! failure_handler {
3830                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
3831                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3832
3833                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3834                                                                                                         short_channel_id: prev_short_channel_id,
3835                                                                                                         outpoint: prev_funding_outpoint,
3836                                                                                                         htlc_id: prev_htlc_id,
3837                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3838                                                                                                         phantom_shared_secret: $phantom_ss,
3839                                                                                                 });
3840
3841                                                                                                 let reason = if $next_hop_unknown {
3842                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
3843                                                                                                 } else {
3844                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
3845                                                                                                 };
3846
3847                                                                                                 failed_forwards.push((htlc_source, payment_hash,
3848                                                                                                         HTLCFailReason::reason($err_code, $err_data),
3849                                                                                                         reason
3850                                                                                                 ));
3851                                                                                                 continue;
3852                                                                                         }
3853                                                                                 }
3854                                                                                 macro_rules! fail_forward {
3855                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3856                                                                                                 {
3857                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
3858                                                                                                 }
3859                                                                                         }
3860                                                                                 }
3861                                                                                 macro_rules! failed_payment {
3862                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3863                                                                                                 {
3864                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
3865                                                                                                 }
3866                                                                                         }
3867                                                                                 }
3868                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
3869                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
3870                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.genesis_hash) {
3871                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
3872                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
3873                                                                                                         Ok(res) => res,
3874                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3875                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
3876                                                                                                                 // In this scenario, the phantom would have sent us an
3877                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
3878                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
3879                                                                                                                 // of the onion.
3880                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
3881                                                                                                         },
3882                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3883                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
3884                                                                                                         },
3885                                                                                                 };
3886                                                                                                 match next_hop {
3887                                                                                                         onion_utils::Hop::Receive(hop_data) => {
3888                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data,
3889                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
3890                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None)
3891                                                                                                                 {
3892                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
3893                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
3894                                                                                                                 }
3895                                                                                                         },
3896                                                                                                         _ => panic!(),
3897                                                                                                 }
3898                                                                                         } else {
3899                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3900                                                                                         }
3901                                                                                 } else {
3902                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3903                                                                                 }
3904                                                                         },
3905                                                                         HTLCForwardInfo::FailHTLC { .. } => {
3906                                                                                 // Channel went away before we could fail it. This implies
3907                                                                                 // the channel is now on chain and our counterparty is
3908                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
3909                                                                                 // problem, not ours.
3910                                                                         }
3911                                                                 }
3912                                                         }
3913                                                 }
3914                                         }
3915                                         let (counterparty_node_id, forward_chan_id) = match self.short_to_chan_info.read().unwrap().get(&short_chan_id) {
3916                                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3917                                                 None => {
3918                                                         forwarding_channel_not_found!();
3919                                                         continue;
3920                                                 }
3921                                         };
3922                                         let per_peer_state = self.per_peer_state.read().unwrap();
3923                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3924                                         if peer_state_mutex_opt.is_none() {
3925                                                 forwarding_channel_not_found!();
3926                                                 continue;
3927                                         }
3928                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3929                                         let peer_state = &mut *peer_state_lock;
3930                                         match peer_state.channel_by_id.entry(forward_chan_id) {
3931                                                 hash_map::Entry::Vacant(_) => {
3932                                                         forwarding_channel_not_found!();
3933                                                         continue;
3934                                                 },
3935                                                 hash_map::Entry::Occupied(mut chan) => {
3936                                                         for forward_info in pending_forwards.drain(..) {
3937                                                                 match forward_info {
3938                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3939                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id: _,
3940                                                                                 forward_info: PendingHTLCInfo {
3941                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
3942                                                                                         routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
3943                                                                                 },
3944                                                                         }) => {
3945                                                                                 log_trace!(self.logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", prev_short_channel_id, log_bytes!(payment_hash.0), short_chan_id);
3946                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3947                                                                                         short_channel_id: prev_short_channel_id,
3948                                                                                         outpoint: prev_funding_outpoint,
3949                                                                                         htlc_id: prev_htlc_id,
3950                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3951                                                                                         // Phantom payments are only PendingHTLCRouting::Receive.
3952                                                                                         phantom_shared_secret: None,
3953                                                                                 });
3954                                                                                 if let Err(e) = chan.get_mut().queue_add_htlc(outgoing_amt_msat,
3955                                                                                         payment_hash, outgoing_cltv_value, htlc_source.clone(),
3956                                                                                         onion_packet, skimmed_fee_msat, &self.fee_estimator,
3957                                                                                         &self.logger)
3958                                                                                 {
3959                                                                                         if let ChannelError::Ignore(msg) = e {
3960                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3961                                                                                         } else {
3962                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
3963                                                                                         }
3964                                                                                         let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3965                                                                                         failed_forwards.push((htlc_source, payment_hash,
3966                                                                                                 HTLCFailReason::reason(failure_code, data),
3967                                                                                                 HTLCDestination::NextHopChannel { node_id: Some(chan.get().context.get_counterparty_node_id()), channel_id: forward_chan_id }
3968                                                                                         ));
3969                                                                                         continue;
3970                                                                                 }
3971                                                                         },
3972                                                                         HTLCForwardInfo::AddHTLC { .. } => {
3973                                                                                 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3974                                                                         },
3975                                                                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3976                                                                                 log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3977                                                                                 if let Err(e) = chan.get_mut().queue_fail_htlc(
3978                                                                                         htlc_id, err_packet, &self.logger
3979                                                                                 ) {
3980                                                                                         if let ChannelError::Ignore(msg) = e {
3981                                                                                                 log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3982                                                                                         } else {
3983                                                                                                 panic!("Stated return value requirements in queue_fail_htlc() were not met");
3984                                                                                         }
3985                                                                                         // fail-backs are best-effort, we probably already have one
3986                                                                                         // pending, and if not that's OK, if not, the channel is on
3987                                                                                         // the chain and sending the HTLC-Timeout is their problem.
3988                                                                                         continue;
3989                                                                                 }
3990                                                                         },
3991                                                                 }
3992                                                         }
3993                                                 }
3994                                         }
3995                                 } else {
3996                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
3997                                                 match forward_info {
3998                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3999                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4000                                                                 forward_info: PendingHTLCInfo {
4001                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4002                                                                         skimmed_fee_msat, ..
4003                                                                 }
4004                                                         }) => {
4005                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4006                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4007                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4008                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4009                                                                                                 payment_metadata, custom_tlvs };
4010                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4011                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4012                                                                         },
4013                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4014                                                                                 let onion_fields = RecipientOnionFields {
4015                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4016                                                                                         payment_metadata,
4017                                                                                         custom_tlvs,
4018                                                                                 };
4019                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4020                                                                                         payment_data, None, onion_fields)
4021                                                                         },
4022                                                                         _ => {
4023                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4024                                                                         }
4025                                                                 };
4026                                                                 let claimable_htlc = ClaimableHTLC {
4027                                                                         prev_hop: HTLCPreviousHopData {
4028                                                                                 short_channel_id: prev_short_channel_id,
4029                                                                                 outpoint: prev_funding_outpoint,
4030                                                                                 htlc_id: prev_htlc_id,
4031                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4032                                                                                 phantom_shared_secret,
4033                                                                         },
4034                                                                         // We differentiate the received value from the sender intended value
4035                                                                         // if possible so that we don't prematurely mark MPP payments complete
4036                                                                         // if routing nodes overpay
4037                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4038                                                                         sender_intended_value: outgoing_amt_msat,
4039                                                                         timer_ticks: 0,
4040                                                                         total_value_received: None,
4041                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4042                                                                         cltv_expiry,
4043                                                                         onion_payload,
4044                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4045                                                                 };
4046
4047                                                                 let mut committed_to_claimable = false;
4048
4049                                                                 macro_rules! fail_htlc {
4050                                                                         ($htlc: expr, $payment_hash: expr) => {
4051                                                                                 debug_assert!(!committed_to_claimable);
4052                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4053                                                                                 htlc_msat_height_data.extend_from_slice(
4054                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4055                                                                                 );
4056                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4057                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4058                                                                                                 outpoint: prev_funding_outpoint,
4059                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4060                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4061                                                                                                 phantom_shared_secret,
4062                                                                                         }), payment_hash,
4063                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4064                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4065                                                                                 ));
4066                                                                                 continue 'next_forwardable_htlc;
4067                                                                         }
4068                                                                 }
4069                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4070                                                                 let mut receiver_node_id = self.our_network_pubkey;
4071                                                                 if phantom_shared_secret.is_some() {
4072                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4073                                                                                 .expect("Failed to get node_id for phantom node recipient");
4074                                                                 }
4075
4076                                                                 macro_rules! check_total_value {
4077                                                                         ($purpose: expr) => {{
4078                                                                                 let mut payment_claimable_generated = false;
4079                                                                                 let is_keysend = match $purpose {
4080                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4081                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4082                                                                                 };
4083                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4084                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4085                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4086                                                                                 }
4087                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4088                                                                                         .entry(payment_hash)
4089                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4090                                                                                         .or_insert_with(|| {
4091                                                                                                 committed_to_claimable = true;
4092                                                                                                 ClaimablePayment {
4093                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4094                                                                                                 }
4095                                                                                         });
4096                                                                                 if $purpose != claimable_payment.purpose {
4097                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4098                                                                                         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), log_bytes!(payment_hash.0), log_keysend(!is_keysend));
4099                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4100                                                                                 }
4101                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4102                                                                                         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", log_bytes!(payment_hash.0));
4103                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4104                                                                                 }
4105                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4106                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4107                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4108                                                                                         }
4109                                                                                 } else {
4110                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4111                                                                                 }
4112                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4113                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4114                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4115                                                                                 for htlc in htlcs.iter() {
4116                                                                                         total_value += htlc.sender_intended_value;
4117                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4118                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4119                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4120                                                                                                         log_bytes!(payment_hash.0), claimable_htlc.total_msat, htlc.total_msat);
4121                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4122                                                                                         }
4123                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4124                                                                                 }
4125                                                                                 // The condition determining whether an MPP is complete must
4126                                                                                 // match exactly the condition used in `timer_tick_occurred`
4127                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4128                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4129                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4130                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4131                                                                                                 log_bytes!(payment_hash.0));
4132                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4133                                                                                 } else if total_value >= claimable_htlc.total_msat {
4134                                                                                         #[allow(unused_assignments)] {
4135                                                                                                 committed_to_claimable = true;
4136                                                                                         }
4137                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4138                                                                                         htlcs.push(claimable_htlc);
4139                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4140                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4141                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4142                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4143                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4144                                                                                                 counterparty_skimmed_fee_msat);
4145                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4146                                                                                                 receiver_node_id: Some(receiver_node_id),
4147                                                                                                 payment_hash,
4148                                                                                                 purpose: $purpose,
4149                                                                                                 amount_msat,
4150                                                                                                 counterparty_skimmed_fee_msat,
4151                                                                                                 via_channel_id: Some(prev_channel_id),
4152                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4153                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4154                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4155                                                                                         }, None));
4156                                                                                         payment_claimable_generated = true;
4157                                                                                 } else {
4158                                                                                         // Nothing to do - we haven't reached the total
4159                                                                                         // payment value yet, wait until we receive more
4160                                                                                         // MPP parts.
4161                                                                                         htlcs.push(claimable_htlc);
4162                                                                                         #[allow(unused_assignments)] {
4163                                                                                                 committed_to_claimable = true;
4164                                                                                         }
4165                                                                                 }
4166                                                                                 payment_claimable_generated
4167                                                                         }}
4168                                                                 }
4169
4170                                                                 // Check that the payment hash and secret are known. Note that we
4171                                                                 // MUST take care to handle the "unknown payment hash" and
4172                                                                 // "incorrect payment secret" cases here identically or we'd expose
4173                                                                 // that we are the ultimate recipient of the given payment hash.
4174                                                                 // Further, we must not expose whether we have any other HTLCs
4175                                                                 // associated with the same payment_hash pending or not.
4176                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4177                                                                 match payment_secrets.entry(payment_hash) {
4178                                                                         hash_map::Entry::Vacant(_) => {
4179                                                                                 match claimable_htlc.onion_payload {
4180                                                                                         OnionPayload::Invoice { .. } => {
4181                                                                                                 let payment_data = payment_data.unwrap();
4182                                                                                                 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) {
4183                                                                                                         Ok(result) => result,
4184                                                                                                         Err(()) => {
4185                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", log_bytes!(payment_hash.0));
4186                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4187                                                                                                         }
4188                                                                                                 };
4189                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4190                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4191                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4192                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4193                                                                                                                         log_bytes!(payment_hash.0), cltv_expiry, expected_min_expiry_height);
4194                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4195                                                                                                         }
4196                                                                                                 }
4197                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4198                                                                                                         payment_preimage: payment_preimage.clone(),
4199                                                                                                         payment_secret: payment_data.payment_secret,
4200                                                                                                 };
4201                                                                                                 check_total_value!(purpose);
4202                                                                                         },
4203                                                                                         OnionPayload::Spontaneous(preimage) => {
4204                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4205                                                                                                 check_total_value!(purpose);
4206                                                                                         }
4207                                                                                 }
4208                                                                         },
4209                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4210                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4211                                                                                         log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} because we already have an inbound payment with the same payment hash", log_bytes!(payment_hash.0));
4212                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4213                                                                                 }
4214                                                                                 let payment_data = payment_data.unwrap();
4215                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4216                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", log_bytes!(payment_hash.0));
4217                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4218                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4219                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4220                                                                                                 log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4221                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4222                                                                                 } else {
4223                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4224                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4225                                                                                                 payment_secret: payment_data.payment_secret,
4226                                                                                         };
4227                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4228                                                                                         if payment_claimable_generated {
4229                                                                                                 inbound_payment.remove_entry();
4230                                                                                         }
4231                                                                                 }
4232                                                                         },
4233                                                                 };
4234                                                         },
4235                                                         HTLCForwardInfo::FailHTLC { .. } => {
4236                                                                 panic!("Got pending fail of our own HTLC");
4237                                                         }
4238                                                 }
4239                                         }
4240                                 }
4241                         }
4242                 }
4243
4244                 let best_block_height = self.best_block.read().unwrap().height();
4245                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4246                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4247                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4248
4249                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4250                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4251                 }
4252                 self.forward_htlcs(&mut phantom_receives);
4253
4254                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4255                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4256                 // nice to do the work now if we can rather than while we're trying to get messages in the
4257                 // network stack.
4258                 self.check_free_holding_cells();
4259
4260                 if new_events.is_empty() { return }
4261                 let mut events = self.pending_events.lock().unwrap();
4262                 events.append(&mut new_events);
4263         }
4264
4265         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4266         ///
4267         /// Expects the caller to have a total_consistency_lock read lock.
4268         fn process_background_events(&self) -> NotifyOption {
4269                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4270
4271                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4272
4273                 let mut background_events = Vec::new();
4274                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4275                 if background_events.is_empty() {
4276                         return NotifyOption::SkipPersist;
4277                 }
4278
4279                 for event in background_events.drain(..) {
4280                         match event {
4281                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4282                                         // The channel has already been closed, so no use bothering to care about the
4283                                         // monitor updating completing.
4284                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4285                                 },
4286                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4287                                         let mut updated_chan = false;
4288                                         let res = {
4289                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4290                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4291                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4292                                                         let peer_state = &mut *peer_state_lock;
4293                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4294                                                                 hash_map::Entry::Occupied(mut chan) => {
4295                                                                         updated_chan = true;
4296                                                                         handle_new_monitor_update!(self, funding_txo, update.clone(),
4297                                                                                 peer_state_lock, peer_state, per_peer_state, chan).map(|_| ())
4298                                                                 },
4299                                                                 hash_map::Entry::Vacant(_) => Ok(()),
4300                                                         }
4301                                                 } else { Ok(()) }
4302                                         };
4303                                         if !updated_chan {
4304                                                 // TODO: Track this as in-flight even though the channel is closed.
4305                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4306                                         }
4307                                         // TODO: If this channel has since closed, we're likely providing a payment
4308                                         // preimage update, which we must ensure is durable! We currently don't,
4309                                         // however, ensure that.
4310                                         if res.is_err() {
4311                                                 log_error!(self.logger,
4312                                                         "Failed to provide ChannelMonitorUpdate to closed channel! This likely lost us a payment preimage!");
4313                                         }
4314                                         let _ = handle_error!(self, res, counterparty_node_id);
4315                                 },
4316                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4317                                         let per_peer_state = self.per_peer_state.read().unwrap();
4318                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4319                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4320                                                 let peer_state = &mut *peer_state_lock;
4321                                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&channel_id) {
4322                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4323                                                 } else {
4324                                                         let update_actions = peer_state.monitor_update_blocked_actions
4325                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4326                                                         mem::drop(peer_state_lock);
4327                                                         mem::drop(per_peer_state);
4328                                                         self.handle_monitor_update_completion_actions(update_actions);
4329                                                 }
4330                                         }
4331                                 },
4332                         }
4333                 }
4334                 NotifyOption::DoPersist
4335         }
4336
4337         #[cfg(any(test, feature = "_test_utils"))]
4338         /// Process background events, for functional testing
4339         pub fn test_process_background_events(&self) {
4340                 let _lck = self.total_consistency_lock.read().unwrap();
4341                 let _ = self.process_background_events();
4342         }
4343
4344         fn update_channel_fee(&self, chan_id: &[u8; 32], chan: &mut Channel<<SP::Target as SignerProvider>::Signer>, new_feerate: u32) -> NotifyOption {
4345                 if !chan.context.is_outbound() { return NotifyOption::SkipPersist; }
4346                 // If the feerate has decreased by less than half, don't bother
4347                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4348                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4349                                 log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4350                         return NotifyOption::SkipPersist;
4351                 }
4352                 if !chan.context.is_live() {
4353                         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).",
4354                                 log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4355                         return NotifyOption::SkipPersist;
4356                 }
4357                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4358                         log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4359
4360                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4361                 NotifyOption::DoPersist
4362         }
4363
4364         #[cfg(fuzzing)]
4365         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4366         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4367         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4368         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4369         pub fn maybe_update_chan_fees(&self) {
4370                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
4371                         let mut should_persist = self.process_background_events();
4372
4373                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4374                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4375
4376                         let per_peer_state = self.per_peer_state.read().unwrap();
4377                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4378                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4379                                 let peer_state = &mut *peer_state_lock;
4380                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
4381                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4382                                                 min_mempool_feerate
4383                                         } else {
4384                                                 normal_feerate
4385                                         };
4386                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4387                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4388                                 }
4389                         }
4390
4391                         should_persist
4392                 });
4393         }
4394
4395         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4396         ///
4397         /// This currently includes:
4398         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4399         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4400         ///    than a minute, informing the network that they should no longer attempt to route over
4401         ///    the channel.
4402         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4403         ///    with the current [`ChannelConfig`].
4404         ///  * Removing peers which have disconnected but and no longer have any channels.
4405         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4406         ///
4407         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4408         /// estimate fetches.
4409         ///
4410         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4411         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4412         pub fn timer_tick_occurred(&self) {
4413                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
4414                         let mut should_persist = self.process_background_events();
4415
4416                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4417                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4418
4419                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4420                         let mut timed_out_mpp_htlcs = Vec::new();
4421                         let mut pending_peers_awaiting_removal = Vec::new();
4422                         {
4423                                 let per_peer_state = self.per_peer_state.read().unwrap();
4424                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4425                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4426                                         let peer_state = &mut *peer_state_lock;
4427                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4428                                         let counterparty_node_id = *counterparty_node_id;
4429                                         peer_state.channel_by_id.retain(|chan_id, chan| {
4430                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4431                                                         min_mempool_feerate
4432                                                 } else {
4433                                                         normal_feerate
4434                                                 };
4435                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4436                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4437
4438                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4439                                                         let (needs_close, err) = convert_chan_err!(self, e, chan, chan_id);
4440                                                         handle_errors.push((Err(err), counterparty_node_id));
4441                                                         if needs_close { return false; }
4442                                                 }
4443
4444                                                 match chan.channel_update_status() {
4445                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4446                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4447                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4448                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4449                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4450                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4451                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4452                                                                 n += 1;
4453                                                                 if n >= DISABLE_GOSSIP_TICKS {
4454                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4455                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4456                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4457                                                                                         msg: update
4458                                                                                 });
4459                                                                         }
4460                                                                         should_persist = NotifyOption::DoPersist;
4461                                                                 } else {
4462                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4463                                                                 }
4464                                                         },
4465                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4466                                                                 n += 1;
4467                                                                 if n >= ENABLE_GOSSIP_TICKS {
4468                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4469                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4470                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4471                                                                                         msg: update
4472                                                                                 });
4473                                                                         }
4474                                                                         should_persist = NotifyOption::DoPersist;
4475                                                                 } else {
4476                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4477                                                                 }
4478                                                         },
4479                                                         _ => {},
4480                                                 }
4481
4482                                                 chan.context.maybe_expire_prev_config();
4483
4484                                                 if chan.should_disconnect_peer_awaiting_response() {
4485                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4486                                                                         counterparty_node_id, log_bytes!(*chan_id));
4487                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4488                                                                 node_id: counterparty_node_id,
4489                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4490                                                                         msg: msgs::WarningMessage {
4491                                                                                 channel_id: *chan_id,
4492                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4493                                                                         },
4494                                                                 },
4495                                                         });
4496                                                 }
4497
4498                                                 true
4499                                         });
4500
4501                                         let process_unfunded_channel_tick = |
4502                                                 chan_id: &[u8; 32],
4503                                                 chan_context: &mut ChannelContext<<SP::Target as SignerProvider>::Signer>,
4504                                                 unfunded_chan_context: &mut UnfundedChannelContext,
4505                                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4506                                         | {
4507                                                 chan_context.maybe_expire_prev_config();
4508                                                 if unfunded_chan_context.should_expire_unfunded_channel() {
4509                                                         log_error!(self.logger,
4510                                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner",
4511                                                                 log_bytes!(&chan_id[..]));
4512                                                         update_maps_on_chan_removal!(self, &chan_context);
4513                                                         self.issue_channel_close_events(&chan_context, ClosureReason::HolderForceClosed);
4514                                                         self.finish_force_close_channel(chan_context.force_shutdown(false));
4515                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4516                                                                 node_id: counterparty_node_id,
4517                                                                 action: msgs::ErrorAction::SendErrorMessage {
4518                                                                         msg: msgs::ErrorMessage {
4519                                                                                 channel_id: *chan_id,
4520                                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4521                                                                         },
4522                                                                 },
4523                                                         });
4524                                                         false
4525                                                 } else {
4526                                                         true
4527                                                 }
4528                                         };
4529                                         peer_state.outbound_v1_channel_by_id.retain(|chan_id, chan| process_unfunded_channel_tick(
4530                                                 chan_id, &mut chan.context, &mut chan.unfunded_context, pending_msg_events));
4531                                         peer_state.inbound_v1_channel_by_id.retain(|chan_id, chan| process_unfunded_channel_tick(
4532                                                 chan_id, &mut chan.context, &mut chan.unfunded_context, pending_msg_events));
4533
4534                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4535                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4536                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", log_bytes!(&chan_id[..]));
4537                                                         peer_state.pending_msg_events.push(
4538                                                                 events::MessageSendEvent::HandleError {
4539                                                                         node_id: counterparty_node_id,
4540                                                                         action: msgs::ErrorAction::SendErrorMessage {
4541                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4542                                                                         },
4543                                                                 }
4544                                                         );
4545                                                 }
4546                                         }
4547                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4548
4549                                         if peer_state.ok_to_remove(true) {
4550                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4551                                         }
4552                                 }
4553                         }
4554
4555                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4556                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4557                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4558                         // we therefore need to remove the peer from `peer_state` separately.
4559                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4560                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4561                         // negative effects on parallelism as much as possible.
4562                         if pending_peers_awaiting_removal.len() > 0 {
4563                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4564                                 for counterparty_node_id in pending_peers_awaiting_removal {
4565                                         match per_peer_state.entry(counterparty_node_id) {
4566                                                 hash_map::Entry::Occupied(entry) => {
4567                                                         // Remove the entry if the peer is still disconnected and we still
4568                                                         // have no channels to the peer.
4569                                                         let remove_entry = {
4570                                                                 let peer_state = entry.get().lock().unwrap();
4571                                                                 peer_state.ok_to_remove(true)
4572                                                         };
4573                                                         if remove_entry {
4574                                                                 entry.remove_entry();
4575                                                         }
4576                                                 },
4577                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
4578                                         }
4579                                 }
4580                         }
4581
4582                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
4583                                 if payment.htlcs.is_empty() {
4584                                         // This should be unreachable
4585                                         debug_assert!(false);
4586                                         return false;
4587                                 }
4588                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
4589                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
4590                                         // In this case we're not going to handle any timeouts of the parts here.
4591                                         // This condition determining whether the MPP is complete here must match
4592                                         // exactly the condition used in `process_pending_htlc_forwards`.
4593                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
4594                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
4595                                         {
4596                                                 return true;
4597                                         } else if payment.htlcs.iter_mut().any(|htlc| {
4598                                                 htlc.timer_ticks += 1;
4599                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
4600                                         }) {
4601                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
4602                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
4603                                                 return false;
4604                                         }
4605                                 }
4606                                 true
4607                         });
4608
4609                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
4610                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
4611                                 let reason = HTLCFailReason::from_failure_code(23);
4612                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
4613                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
4614                         }
4615
4616                         for (err, counterparty_node_id) in handle_errors.drain(..) {
4617                                 let _ = handle_error!(self, err, counterparty_node_id);
4618                         }
4619
4620                         self.pending_outbound_payments.remove_stale_resolved_payments(&self.pending_events);
4621
4622                         // Technically we don't need to do this here, but if we have holding cell entries in a
4623                         // channel that need freeing, it's better to do that here and block a background task
4624                         // than block the message queueing pipeline.
4625                         if self.check_free_holding_cells() {
4626                                 should_persist = NotifyOption::DoPersist;
4627                         }
4628
4629                         should_persist
4630                 });
4631         }
4632
4633         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
4634         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
4635         /// along the path (including in our own channel on which we received it).
4636         ///
4637         /// Note that in some cases around unclean shutdown, it is possible the payment may have
4638         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
4639         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
4640         /// may have already been failed automatically by LDK if it was nearing its expiration time.
4641         ///
4642         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
4643         /// [`ChannelManager::claim_funds`]), you should still monitor for
4644         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
4645         /// startup during which time claims that were in-progress at shutdown may be replayed.
4646         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
4647                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
4648         }
4649
4650         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
4651         /// reason for the failure.
4652         ///
4653         /// See [`FailureCode`] for valid failure codes.
4654         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
4655                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4656
4657                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
4658                 if let Some(payment) = removed_source {
4659                         for htlc in payment.htlcs {
4660                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
4661                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4662                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
4663                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4664                         }
4665                 }
4666         }
4667
4668         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
4669         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
4670                 match failure_code {
4671                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
4672                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
4673                         FailureCode::IncorrectOrUnknownPaymentDetails => {
4674                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4675                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4676                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
4677                         },
4678                         FailureCode::InvalidOnionPayload(data) => {
4679                                 let fail_data = match data {
4680                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
4681                                         None => Vec::new(),
4682                                 };
4683                                 HTLCFailReason::reason(failure_code.into(), fail_data)
4684                         }
4685                 }
4686         }
4687
4688         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4689         /// that we want to return and a channel.
4690         ///
4691         /// This is for failures on the channel on which the HTLC was *received*, not failures
4692         /// forwarding
4693         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
4694                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
4695                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
4696                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
4697                 // an inbound SCID alias before the real SCID.
4698                 let scid_pref = if chan.context.should_announce() {
4699                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
4700                 } else {
4701                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
4702                 };
4703                 if let Some(scid) = scid_pref {
4704                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
4705                 } else {
4706                         (0x4000|10, Vec::new())
4707                 }
4708         }
4709
4710
4711         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4712         /// that we want to return and a channel.
4713         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
4714                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
4715                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
4716                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
4717                         if desired_err_code == 0x1000 | 20 {
4718                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
4719                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
4720                                 0u16.write(&mut enc).expect("Writes cannot fail");
4721                         }
4722                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
4723                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
4724                         upd.write(&mut enc).expect("Writes cannot fail");
4725                         (desired_err_code, enc.0)
4726                 } else {
4727                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
4728                         // which means we really shouldn't have gotten a payment to be forwarded over this
4729                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
4730                         // PERM|no_such_channel should be fine.
4731                         (0x4000|10, Vec::new())
4732                 }
4733         }
4734
4735         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
4736         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
4737         // be surfaced to the user.
4738         fn fail_holding_cell_htlcs(
4739                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32],
4740                 counterparty_node_id: &PublicKey
4741         ) {
4742                 let (failure_code, onion_failure_data) = {
4743                         let per_peer_state = self.per_peer_state.read().unwrap();
4744                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
4745                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4746                                 let peer_state = &mut *peer_state_lock;
4747                                 match peer_state.channel_by_id.entry(channel_id) {
4748                                         hash_map::Entry::Occupied(chan_entry) => {
4749                                                 self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
4750                                         },
4751                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
4752                                 }
4753                         } else { (0x4000|10, Vec::new()) }
4754                 };
4755
4756                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
4757                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
4758                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
4759                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
4760                 }
4761         }
4762
4763         /// Fails an HTLC backwards to the sender of it to us.
4764         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
4765         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
4766                 // Ensure that no peer state channel storage lock is held when calling this function.
4767                 // This ensures that future code doesn't introduce a lock-order requirement for
4768                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
4769                 // this function with any `per_peer_state` peer lock acquired would.
4770                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
4771                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
4772                 }
4773
4774                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
4775                 //identify whether we sent it or not based on the (I presume) very different runtime
4776                 //between the branches here. We should make this async and move it into the forward HTLCs
4777                 //timer handling.
4778
4779                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
4780                 // from block_connected which may run during initialization prior to the chain_monitor
4781                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
4782                 match source {
4783                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
4784                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
4785                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
4786                                         &self.pending_events, &self.logger)
4787                                 { self.push_pending_forwards_ev(); }
4788                         },
4789                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint }) => {
4790                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", log_bytes!(payment_hash.0), onion_error);
4791                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
4792
4793                                 let mut push_forward_ev = false;
4794                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
4795                                 if forward_htlcs.is_empty() {
4796                                         push_forward_ev = true;
4797                                 }
4798                                 match forward_htlcs.entry(*short_channel_id) {
4799                                         hash_map::Entry::Occupied(mut entry) => {
4800                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
4801                                         },
4802                                         hash_map::Entry::Vacant(entry) => {
4803                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
4804                                         }
4805                                 }
4806                                 mem::drop(forward_htlcs);
4807                                 if push_forward_ev { self.push_pending_forwards_ev(); }
4808                                 let mut pending_events = self.pending_events.lock().unwrap();
4809                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
4810                                         prev_channel_id: outpoint.to_channel_id(),
4811                                         failed_next_destination: destination,
4812                                 }, None));
4813                         },
4814                 }
4815         }
4816
4817         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
4818         /// [`MessageSendEvent`]s needed to claim the payment.
4819         ///
4820         /// This method is guaranteed to ensure the payment has been claimed but only if the current
4821         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
4822         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
4823         /// successful. It will generally be available in the next [`process_pending_events`] call.
4824         ///
4825         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
4826         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
4827         /// event matches your expectation. If you fail to do so and call this method, you may provide
4828         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
4829         ///
4830         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
4831         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
4832         /// [`claim_funds_with_known_custom_tlvs`].
4833         ///
4834         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
4835         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
4836         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
4837         /// [`process_pending_events`]: EventsProvider::process_pending_events
4838         /// [`create_inbound_payment`]: Self::create_inbound_payment
4839         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
4840         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
4841         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
4842                 self.claim_payment_internal(payment_preimage, false);
4843         }
4844
4845         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
4846         /// even type numbers.
4847         ///
4848         /// # Note
4849         ///
4850         /// You MUST check you've understood all even TLVs before using this to
4851         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
4852         ///
4853         /// [`claim_funds`]: Self::claim_funds
4854         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
4855                 self.claim_payment_internal(payment_preimage, true);
4856         }
4857
4858         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
4859                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
4860
4861                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4862
4863                 let mut sources = {
4864                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
4865                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
4866                                 let mut receiver_node_id = self.our_network_pubkey;
4867                                 for htlc in payment.htlcs.iter() {
4868                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
4869                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
4870                                                         .expect("Failed to get node_id for phantom node recipient");
4871                                                 receiver_node_id = phantom_pubkey;
4872                                                 break;
4873                                         }
4874                                 }
4875
4876                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
4877                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
4878                                         payment_purpose: payment.purpose, receiver_node_id,
4879                                 });
4880                                 if dup_purpose.is_some() {
4881                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
4882                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
4883                                                 log_bytes!(payment_hash.0));
4884                                 }
4885
4886                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
4887                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
4888                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
4889                                                         log_bytes!(payment_hash.0), log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
4890                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
4891                                                 mem::drop(claimable_payments);
4892                                                 for htlc in payment.htlcs {
4893                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
4894                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4895                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
4896                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4897                                                 }
4898                                                 return;
4899                                         }
4900                                 }
4901
4902                                 payment.htlcs
4903                         } else { return; }
4904                 };
4905                 debug_assert!(!sources.is_empty());
4906
4907                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
4908                 // and when we got here we need to check that the amount we're about to claim matches the
4909                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
4910                 // the MPP parts all have the same `total_msat`.
4911                 let mut claimable_amt_msat = 0;
4912                 let mut prev_total_msat = None;
4913                 let mut expected_amt_msat = None;
4914                 let mut valid_mpp = true;
4915                 let mut errs = Vec::new();
4916                 let per_peer_state = self.per_peer_state.read().unwrap();
4917                 for htlc in sources.iter() {
4918                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
4919                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
4920                                 debug_assert!(false);
4921                                 valid_mpp = false;
4922                                 break;
4923                         }
4924                         prev_total_msat = Some(htlc.total_msat);
4925
4926                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
4927                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
4928                                 debug_assert!(false);
4929                                 valid_mpp = false;
4930                                 break;
4931                         }
4932                         expected_amt_msat = htlc.total_value_received;
4933                         claimable_amt_msat += htlc.value;
4934                 }
4935                 mem::drop(per_peer_state);
4936                 if sources.is_empty() || expected_amt_msat.is_none() {
4937                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4938                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
4939                         return;
4940                 }
4941                 if claimable_amt_msat != expected_amt_msat.unwrap() {
4942                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4943                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
4944                                 expected_amt_msat.unwrap(), claimable_amt_msat);
4945                         return;
4946                 }
4947                 if valid_mpp {
4948                         for htlc in sources.drain(..) {
4949                                 if let Err((pk, err)) = self.claim_funds_from_hop(
4950                                         htlc.prev_hop, payment_preimage,
4951                                         |_| Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash }))
4952                                 {
4953                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
4954                                                 // We got a temporary failure updating monitor, but will claim the
4955                                                 // HTLC when the monitor updating is restored (or on chain).
4956                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
4957                                         } else { errs.push((pk, err)); }
4958                                 }
4959                         }
4960                 }
4961                 if !valid_mpp {
4962                         for htlc in sources.drain(..) {
4963                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4964                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4965                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4966                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
4967                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
4968                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4969                         }
4970                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4971                 }
4972
4973                 // Now we can handle any errors which were generated.
4974                 for (counterparty_node_id, err) in errs.drain(..) {
4975                         let res: Result<(), _> = Err(err);
4976                         let _ = handle_error!(self, res, counterparty_node_id);
4977                 }
4978         }
4979
4980         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>) -> Option<MonitorUpdateCompletionAction>>(&self,
4981                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
4982         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
4983                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
4984
4985                 // If we haven't yet run background events assume we're still deserializing and shouldn't
4986                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
4987                 // `BackgroundEvent`s.
4988                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
4989
4990                 {
4991                         let per_peer_state = self.per_peer_state.read().unwrap();
4992                         let chan_id = prev_hop.outpoint.to_channel_id();
4993                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
4994                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
4995                                 None => None
4996                         };
4997
4998                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
4999                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5000                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5001                         ).unwrap_or(None);
5002
5003                         if peer_state_opt.is_some() {
5004                                 let mut peer_state_lock = peer_state_opt.unwrap();
5005                                 let peer_state = &mut *peer_state_lock;
5006                                 if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(chan_id) {
5007                                         let counterparty_node_id = chan.get().context.get_counterparty_node_id();
5008                                         let fulfill_res = chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5009
5010                                         if let UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } = fulfill_res {
5011                                                 if let Some(action) = completion_action(Some(htlc_value_msat)) {
5012                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5013                                                                 log_bytes!(chan_id), action);
5014                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5015                                                 }
5016                                                 if !during_init {
5017                                                         let res = handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5018                                                                 peer_state, per_peer_state, chan);
5019                                                         if let Err(e) = res {
5020                                                                 // TODO: This is a *critical* error - we probably updated the outbound edge
5021                                                                 // of the HTLC's monitor with a preimage. We should retry this monitor
5022                                                                 // update over and over again until morale improves.
5023                                                                 log_error!(self.logger, "Failed to update channel monitor with preimage {:?}", payment_preimage);
5024                                                                 return Err((counterparty_node_id, e));
5025                                                         }
5026                                                 } else {
5027                                                         // If we're running during init we cannot update a monitor directly -
5028                                                         // they probably haven't actually been loaded yet. Instead, push the
5029                                                         // monitor update as a background event.
5030                                                         self.pending_background_events.lock().unwrap().push(
5031                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5032                                                                         counterparty_node_id,
5033                                                                         funding_txo: prev_hop.outpoint,
5034                                                                         update: monitor_update.clone(),
5035                                                                 });
5036                                                 }
5037                                         }
5038                                         return Ok(());
5039                                 }
5040                         }
5041                 }
5042                 let preimage_update = ChannelMonitorUpdate {
5043                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5044                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5045                                 payment_preimage,
5046                         }],
5047                 };
5048
5049                 if !during_init {
5050                         // We update the ChannelMonitor on the backward link, after
5051                         // receiving an `update_fulfill_htlc` from the forward link.
5052                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5053                         if update_res != ChannelMonitorUpdateStatus::Completed {
5054                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5055                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5056                                 // channel, or we must have an ability to receive the same event and try
5057                                 // again on restart.
5058                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5059                                         payment_preimage, update_res);
5060                         }
5061                 } else {
5062                         // If we're running during init we cannot update a monitor directly - they probably
5063                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5064                         // event.
5065                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5066                         // channel is already closed) we need to ultimately handle the monitor update
5067                         // completion action only after we've completed the monitor update. This is the only
5068                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5069                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5070                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5071                         // complete the monitor update completion action from `completion_action`.
5072                         self.pending_background_events.lock().unwrap().push(
5073                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5074                                         prev_hop.outpoint, preimage_update,
5075                                 )));
5076                 }
5077                 // Note that we do process the completion action here. This totally could be a
5078                 // duplicate claim, but we have no way of knowing without interrogating the
5079                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5080                 // generally always allowed to be duplicative (and it's specifically noted in
5081                 // `PaymentForwarded`).
5082                 self.handle_monitor_update_completion_actions(completion_action(None));
5083                 Ok(())
5084         }
5085
5086         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5087                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5088         }
5089
5090         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_outpoint: OutPoint) {
5091                 match source {
5092                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5093                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5094                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5095                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5096                                         channel_funding_outpoint: next_channel_outpoint,
5097                                         counterparty_node_id: path.hops[0].pubkey,
5098                                 };
5099                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5100                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5101                                         &self.logger);
5102                         },
5103                         HTLCSource::PreviousHopData(hop_data) => {
5104                                 let prev_outpoint = hop_data.outpoint;
5105                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5106                                         |htlc_claim_value_msat| {
5107                                                 if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5108                                                         let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5109                                                                 Some(claimed_htlc_value - forwarded_htlc_value)
5110                                                         } else { None };
5111
5112                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5113                                                                 event: events::Event::PaymentForwarded {
5114                                                                         fee_earned_msat,
5115                                                                         claim_from_onchain_tx: from_onchain,
5116                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5117                                                                         next_channel_id: Some(next_channel_outpoint.to_channel_id()),
5118                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5119                                                                 },
5120                                                                 downstream_counterparty_and_funding_outpoint: None,
5121                                                         })
5122                                                 } else { None }
5123                                         });
5124                                 if let Err((pk, err)) = res {
5125                                         let result: Result<(), _> = Err(err);
5126                                         let _ = handle_error!(self, result, pk);
5127                                 }
5128                         },
5129                 }
5130         }
5131
5132         /// Gets the node_id held by this ChannelManager
5133         pub fn get_our_node_id(&self) -> PublicKey {
5134                 self.our_network_pubkey.clone()
5135         }
5136
5137         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5138                 for action in actions.into_iter() {
5139                         match action {
5140                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5141                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5142                                         if let Some(ClaimingPayment { amount_msat, payment_purpose: purpose, receiver_node_id }) = payment {
5143                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5144                                                         payment_hash, purpose, amount_msat, receiver_node_id: Some(receiver_node_id),
5145                                                 }, None));
5146                                         }
5147                                 },
5148                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5149                                         event, downstream_counterparty_and_funding_outpoint
5150                                 } => {
5151                                         self.pending_events.lock().unwrap().push_back((event, None));
5152                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5153                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5154                                         }
5155                                 },
5156                         }
5157                 }
5158         }
5159
5160         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5161         /// update completion.
5162         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5163                 channel: &mut Channel<<SP::Target as SignerProvider>::Signer>, raa: Option<msgs::RevokeAndACK>,
5164                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5165                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5166                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5167         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5168                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5169                         log_bytes!(channel.context.channel_id()),
5170                         if raa.is_some() { "an" } else { "no" },
5171                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5172                         if funding_broadcastable.is_some() { "" } else { "not " },
5173                         if channel_ready.is_some() { "sending" } else { "without" },
5174                         if announcement_sigs.is_some() { "sending" } else { "without" });
5175
5176                 let mut htlc_forwards = None;
5177
5178                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5179                 if !pending_forwards.is_empty() {
5180                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5181                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5182                 }
5183
5184                 if let Some(msg) = channel_ready {
5185                         send_channel_ready!(self, pending_msg_events, channel, msg);
5186                 }
5187                 if let Some(msg) = announcement_sigs {
5188                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5189                                 node_id: counterparty_node_id,
5190                                 msg,
5191                         });
5192                 }
5193
5194                 macro_rules! handle_cs { () => {
5195                         if let Some(update) = commitment_update {
5196                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5197                                         node_id: counterparty_node_id,
5198                                         updates: update,
5199                                 });
5200                         }
5201                 } }
5202                 macro_rules! handle_raa { () => {
5203                         if let Some(revoke_and_ack) = raa {
5204                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5205                                         node_id: counterparty_node_id,
5206                                         msg: revoke_and_ack,
5207                                 });
5208                         }
5209                 } }
5210                 match order {
5211                         RAACommitmentOrder::CommitmentFirst => {
5212                                 handle_cs!();
5213                                 handle_raa!();
5214                         },
5215                         RAACommitmentOrder::RevokeAndACKFirst => {
5216                                 handle_raa!();
5217                                 handle_cs!();
5218                         },
5219                 }
5220
5221                 if let Some(tx) = funding_broadcastable {
5222                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5223                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5224                 }
5225
5226                 {
5227                         let mut pending_events = self.pending_events.lock().unwrap();
5228                         emit_channel_pending_event!(pending_events, channel);
5229                         emit_channel_ready_event!(pending_events, channel);
5230                 }
5231
5232                 htlc_forwards
5233         }
5234
5235         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5236                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5237
5238                 let counterparty_node_id = match counterparty_node_id {
5239                         Some(cp_id) => cp_id.clone(),
5240                         None => {
5241                                 // TODO: Once we can rely on the counterparty_node_id from the
5242                                 // monitor event, this and the id_to_peer map should be removed.
5243                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5244                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5245                                         Some(cp_id) => cp_id.clone(),
5246                                         None => return,
5247                                 }
5248                         }
5249                 };
5250                 let per_peer_state = self.per_peer_state.read().unwrap();
5251                 let mut peer_state_lock;
5252                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5253                 if peer_state_mutex_opt.is_none() { return }
5254                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5255                 let peer_state = &mut *peer_state_lock;
5256                 let channel =
5257                         if let Some(chan) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5258                                 chan
5259                         } else {
5260                                 let update_actions = peer_state.monitor_update_blocked_actions
5261                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5262                                 mem::drop(peer_state_lock);
5263                                 mem::drop(per_peer_state);
5264                                 self.handle_monitor_update_completion_actions(update_actions);
5265                                 return;
5266                         };
5267                 let remaining_in_flight =
5268                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5269                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5270                                 pending.len()
5271                         } else { 0 };
5272                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5273                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5274                         remaining_in_flight);
5275                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5276                         return;
5277                 }
5278                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5279         }
5280
5281         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5282         ///
5283         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5284         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5285         /// the channel.
5286         ///
5287         /// The `user_channel_id` parameter will be provided back in
5288         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5289         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5290         ///
5291         /// Note that this method will return an error and reject the channel, if it requires support
5292         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5293         /// used to accept such channels.
5294         ///
5295         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5296         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5297         pub fn accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5298                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5299         }
5300
5301         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5302         /// it as confirmed immediately.
5303         ///
5304         /// The `user_channel_id` parameter will be provided back in
5305         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5306         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5307         ///
5308         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5309         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5310         ///
5311         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5312         /// transaction and blindly assumes that it will eventually confirm.
5313         ///
5314         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5315         /// does not pay to the correct script the correct amount, *you will lose funds*.
5316         ///
5317         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5318         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5319         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5320                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5321         }
5322
5323         fn do_accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5324                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5325
5326                 let peers_without_funded_channels =
5327                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5328                 let per_peer_state = self.per_peer_state.read().unwrap();
5329                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5330                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5331                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5332                 let peer_state = &mut *peer_state_lock;
5333                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5334
5335                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5336                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5337                 // that we can delay allocating the SCID until after we're sure that the checks below will
5338                 // succeed.
5339                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5340                         Some(unaccepted_channel) => {
5341                                 let best_block_height = self.best_block.read().unwrap().height();
5342                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5343                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5344                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5345                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5346                         }
5347                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5348                 }?;
5349
5350                 if accept_0conf {
5351                         // This should have been correctly configured by the call to InboundV1Channel::new.
5352                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5353                 } else if channel.context.get_channel_type().requires_zero_conf() {
5354                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5355                                 node_id: channel.context.get_counterparty_node_id(),
5356                                 action: msgs::ErrorAction::SendErrorMessage{
5357                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5358                                 }
5359                         };
5360                         peer_state.pending_msg_events.push(send_msg_err_event);
5361                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5362                 } else {
5363                         // If this peer already has some channels, a new channel won't increase our number of peers
5364                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5365                         // channels per-peer we can accept channels from a peer with existing ones.
5366                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5367                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5368                                         node_id: channel.context.get_counterparty_node_id(),
5369                                         action: msgs::ErrorAction::SendErrorMessage{
5370                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5371                                         }
5372                                 };
5373                                 peer_state.pending_msg_events.push(send_msg_err_event);
5374                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5375                         }
5376                 }
5377
5378                 // Now that we know we have a channel, assign an outbound SCID alias.
5379                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5380                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5381
5382                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5383                         node_id: channel.context.get_counterparty_node_id(),
5384                         msg: channel.accept_inbound_channel(),
5385                 });
5386
5387                 peer_state.inbound_v1_channel_by_id.insert(temporary_channel_id.clone(), channel);
5388
5389                 Ok(())
5390         }
5391
5392         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5393         /// or 0-conf channels.
5394         ///
5395         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
5396         /// non-0-conf channels we have with the peer.
5397         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
5398         where Filter: Fn(&PeerState<<SP::Target as SignerProvider>::Signer>) -> bool {
5399                 let mut peers_without_funded_channels = 0;
5400                 let best_block_height = self.best_block.read().unwrap().height();
5401                 {
5402                         let peer_state_lock = self.per_peer_state.read().unwrap();
5403                         for (_, peer_mtx) in peer_state_lock.iter() {
5404                                 let peer = peer_mtx.lock().unwrap();
5405                                 if !maybe_count_peer(&*peer) { continue; }
5406                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
5407                                 if num_unfunded_channels == peer.total_channel_count() {
5408                                         peers_without_funded_channels += 1;
5409                                 }
5410                         }
5411                 }
5412                 return peers_without_funded_channels;
5413         }
5414
5415         fn unfunded_channel_count(
5416                 peer: &PeerState<<SP::Target as SignerProvider>::Signer>, best_block_height: u32
5417         ) -> usize {
5418                 let mut num_unfunded_channels = 0;
5419                 for (_, chan) in peer.channel_by_id.iter() {
5420                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
5421                         // which have not yet had any confirmations on-chain.
5422                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
5423                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
5424                         {
5425                                 num_unfunded_channels += 1;
5426                         }
5427                 }
5428                 for (_, chan) in peer.inbound_v1_channel_by_id.iter() {
5429                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
5430                                 num_unfunded_channels += 1;
5431                         }
5432                 }
5433                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
5434         }
5435
5436         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
5437                 if msg.chain_hash != self.genesis_hash {
5438                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
5439                 }
5440
5441                 if !self.default_configuration.accept_inbound_channels {
5442                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5443                 }
5444
5445                 // Get the number of peers with channels, but without funded ones. We don't care too much
5446                 // about peers that never open a channel, so we filter by peers that have at least one
5447                 // channel, and then limit the number of those with unfunded channels.
5448                 let channeled_peers_without_funding =
5449                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
5450
5451                 let per_peer_state = self.per_peer_state.read().unwrap();
5452                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5453                     .ok_or_else(|| {
5454                                 debug_assert!(false);
5455                                 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())
5456                         })?;
5457                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5458                 let peer_state = &mut *peer_state_lock;
5459
5460                 // If this peer already has some channels, a new channel won't increase our number of peers
5461                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5462                 // channels per-peer we can accept channels from a peer with existing ones.
5463                 if peer_state.total_channel_count() == 0 &&
5464                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
5465                         !self.default_configuration.manually_accept_inbound_channels
5466                 {
5467                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5468                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
5469                                 msg.temporary_channel_id.clone()));
5470                 }
5471
5472                 let best_block_height = self.best_block.read().unwrap().height();
5473                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
5474                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5475                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
5476                                 msg.temporary_channel_id.clone()));
5477                 }
5478
5479                 let channel_id = msg.temporary_channel_id;
5480                 let channel_exists = peer_state.has_channel(&channel_id);
5481                 if channel_exists {
5482                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
5483                 }
5484
5485                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
5486                 if self.default_configuration.manually_accept_inbound_channels {
5487                         let mut pending_events = self.pending_events.lock().unwrap();
5488                         pending_events.push_back((events::Event::OpenChannelRequest {
5489                                 temporary_channel_id: msg.temporary_channel_id.clone(),
5490                                 counterparty_node_id: counterparty_node_id.clone(),
5491                                 funding_satoshis: msg.funding_satoshis,
5492                                 push_msat: msg.push_msat,
5493                                 channel_type: msg.channel_type.clone().unwrap(),
5494                         }, None));
5495                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
5496                                 open_channel_msg: msg.clone(),
5497                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
5498                         });
5499                         return Ok(());
5500                 }
5501
5502                 // Otherwise create the channel right now.
5503                 let mut random_bytes = [0u8; 16];
5504                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
5505                 let user_channel_id = u128::from_be_bytes(random_bytes);
5506                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5507                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
5508                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
5509                 {
5510                         Err(e) => {
5511                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
5512                         },
5513                         Ok(res) => res
5514                 };
5515
5516                 let channel_type = channel.context.get_channel_type();
5517                 if channel_type.requires_zero_conf() {
5518                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5519                 }
5520                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
5521                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
5522                 }
5523
5524                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5525                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5526
5527                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5528                         node_id: counterparty_node_id.clone(),
5529                         msg: channel.accept_inbound_channel(),
5530                 });
5531                 peer_state.inbound_v1_channel_by_id.insert(channel_id, channel);
5532                 Ok(())
5533         }
5534
5535         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
5536                 let (value, output_script, user_id) = {
5537                         let per_peer_state = self.per_peer_state.read().unwrap();
5538                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5539                                 .ok_or_else(|| {
5540                                         debug_assert!(false);
5541                                         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)
5542                                 })?;
5543                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5544                         let peer_state = &mut *peer_state_lock;
5545                         match peer_state.outbound_v1_channel_by_id.entry(msg.temporary_channel_id) {
5546                                 hash_map::Entry::Occupied(mut chan) => {
5547                                         try_v1_outbound_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), chan);
5548                                         (chan.get().context.get_value_satoshis(), chan.get().context.get_funding_redeemscript().to_v0_p2wsh(), chan.get().context.get_user_id())
5549                                 },
5550                                 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))
5551                         }
5552                 };
5553                 let mut pending_events = self.pending_events.lock().unwrap();
5554                 pending_events.push_back((events::Event::FundingGenerationReady {
5555                         temporary_channel_id: msg.temporary_channel_id,
5556                         counterparty_node_id: *counterparty_node_id,
5557                         channel_value_satoshis: value,
5558                         output_script,
5559                         user_channel_id: user_id,
5560                 }, None));
5561                 Ok(())
5562         }
5563
5564         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
5565                 let best_block = *self.best_block.read().unwrap();
5566
5567                 let per_peer_state = self.per_peer_state.read().unwrap();
5568                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5569                         .ok_or_else(|| {
5570                                 debug_assert!(false);
5571                                 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)
5572                         })?;
5573
5574                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5575                 let peer_state = &mut *peer_state_lock;
5576                 let (chan, funding_msg, monitor) =
5577                         match peer_state.inbound_v1_channel_by_id.remove(&msg.temporary_channel_id) {
5578                                 Some(inbound_chan) => {
5579                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
5580                                                 Ok(res) => res,
5581                                                 Err((mut inbound_chan, err)) => {
5582                                                         // We've already removed this inbound channel from the map in `PeerState`
5583                                                         // above so at this point we just need to clean up any lingering entries
5584                                                         // concerning this channel as it is safe to do so.
5585                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
5586                                                         let user_id = inbound_chan.context.get_user_id();
5587                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
5588                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
5589                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
5590                                                 },
5591                                         }
5592                                 },
5593                                 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))
5594                         };
5595
5596                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
5597                         hash_map::Entry::Occupied(_) => {
5598                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
5599                         },
5600                         hash_map::Entry::Vacant(e) => {
5601                                 match self.id_to_peer.lock().unwrap().entry(chan.context.channel_id()) {
5602                                         hash_map::Entry::Occupied(_) => {
5603                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
5604                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
5605                                                         funding_msg.channel_id))
5606                                         },
5607                                         hash_map::Entry::Vacant(i_e) => {
5608                                                 i_e.insert(chan.context.get_counterparty_node_id());
5609                                         }
5610                                 }
5611
5612                                 // There's no problem signing a counterparty's funding transaction if our monitor
5613                                 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
5614                                 // accepted payment from yet. We do, however, need to wait to send our channel_ready
5615                                 // until we have persisted our monitor.
5616                                 let new_channel_id = funding_msg.channel_id;
5617                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
5618                                         node_id: counterparty_node_id.clone(),
5619                                         msg: funding_msg,
5620                                 });
5621
5622                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
5623
5624                                 let chan = e.insert(chan);
5625                                 let mut res = handle_new_monitor_update!(self, monitor_res, peer_state_lock, peer_state,
5626                                         per_peer_state, chan, MANUALLY_REMOVING_INITIAL_MONITOR,
5627                                         { peer_state.channel_by_id.remove(&new_channel_id) });
5628
5629                                 // Note that we reply with the new channel_id in error messages if we gave up on the
5630                                 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
5631                                 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
5632                                 // any messages referencing a previously-closed channel anyway.
5633                                 // We do not propagate the monitor update to the user as it would be for a monitor
5634                                 // that we didn't manage to store (and that we don't care about - we don't respond
5635                                 // with the funding_signed so the channel can never go on chain).
5636                                 if let Err(MsgHandleErrInternal { shutdown_finish: Some((res, _)), .. }) = &mut res {
5637                                         res.0 = None;
5638                                 }
5639                                 res.map(|_| ())
5640                         }
5641                 }
5642         }
5643
5644         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
5645                 let best_block = *self.best_block.read().unwrap();
5646                 let per_peer_state = self.per_peer_state.read().unwrap();
5647                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5648                         .ok_or_else(|| {
5649                                 debug_assert!(false);
5650                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5651                         })?;
5652
5653                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5654                 let peer_state = &mut *peer_state_lock;
5655                 match peer_state.channel_by_id.entry(msg.channel_id) {
5656                         hash_map::Entry::Occupied(mut chan) => {
5657                                 let monitor = try_chan_entry!(self,
5658                                         chan.get_mut().funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan);
5659                                 let update_res = self.chain_monitor.watch_channel(chan.get().context.get_funding_txo().unwrap(), monitor);
5660                                 let mut res = handle_new_monitor_update!(self, update_res, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
5661                                 if let Err(MsgHandleErrInternal { ref mut shutdown_finish, .. }) = res {
5662                                         // We weren't able to watch the channel to begin with, so no updates should be made on
5663                                         // it. Previously, full_stack_target found an (unreachable) panic when the
5664                                         // monitor update contained within `shutdown_finish` was applied.
5665                                         if let Some((ref mut shutdown_finish, _)) = shutdown_finish {
5666                                                 shutdown_finish.0.take();
5667                                         }
5668                                 }
5669                                 res.map(|_| ())
5670                         },
5671                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
5672                 }
5673         }
5674
5675         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
5676                 let per_peer_state = self.per_peer_state.read().unwrap();
5677                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5678                         .ok_or_else(|| {
5679                                 debug_assert!(false);
5680                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5681                         })?;
5682                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5683                 let peer_state = &mut *peer_state_lock;
5684                 match peer_state.channel_by_id.entry(msg.channel_id) {
5685                         hash_map::Entry::Occupied(mut chan) => {
5686                                 let announcement_sigs_opt = try_chan_entry!(self, chan.get_mut().channel_ready(&msg, &self.node_signer,
5687                                         self.genesis_hash.clone(), &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan);
5688                                 if let Some(announcement_sigs) = announcement_sigs_opt {
5689                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(chan.get().context.channel_id()));
5690                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5691                                                 node_id: counterparty_node_id.clone(),
5692                                                 msg: announcement_sigs,
5693                                         });
5694                                 } else if chan.get().context.is_usable() {
5695                                         // If we're sending an announcement_signatures, we'll send the (public)
5696                                         // channel_update after sending a channel_announcement when we receive our
5697                                         // counterparty's announcement_signatures. Thus, we only bother to send a
5698                                         // channel_update here if the channel is not public, i.e. we're not sending an
5699                                         // announcement_signatures.
5700                                         log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", log_bytes!(chan.get().context.channel_id()));
5701                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
5702                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
5703                                                         node_id: counterparty_node_id.clone(),
5704                                                         msg,
5705                                                 });
5706                                         }
5707                                 }
5708
5709                                 {
5710                                         let mut pending_events = self.pending_events.lock().unwrap();
5711                                         emit_channel_ready_event!(pending_events, chan.get_mut());
5712                                 }
5713
5714                                 Ok(())
5715                         },
5716                         hash_map::Entry::Vacant(_) => 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))
5717                 }
5718         }
5719
5720         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
5721                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)>;
5722                 let result: Result<(), _> = loop {
5723                         let per_peer_state = self.per_peer_state.read().unwrap();
5724                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5725                                 .ok_or_else(|| {
5726                                         debug_assert!(false);
5727                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5728                                 })?;
5729                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5730                         let peer_state = &mut *peer_state_lock;
5731                         // TODO(dunxen): Fix this duplication when we switch to a single map with enums as per
5732                         // https://github.com/lightningdevkit/rust-lightning/issues/2422
5733                         if let hash_map::Entry::Occupied(chan_entry) = peer_state.outbound_v1_channel_by_id.entry(msg.channel_id.clone()) {
5734                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", log_bytes!(&msg.channel_id[..]));
5735                                 self.issue_channel_close_events(&chan_entry.get().context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
5736                                 let mut chan = remove_channel!(self, chan_entry);
5737                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
5738                                 return Ok(());
5739                         } else if let hash_map::Entry::Occupied(chan_entry) = peer_state.inbound_v1_channel_by_id.entry(msg.channel_id.clone()) {
5740                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", log_bytes!(&msg.channel_id[..]));
5741                                 self.issue_channel_close_events(&chan_entry.get().context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
5742                                 let mut chan = remove_channel!(self, chan_entry);
5743                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
5744                                 return Ok(());
5745                         } else if let hash_map::Entry::Occupied(mut chan_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
5746                                 if !chan_entry.get().received_shutdown() {
5747                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
5748                                                 log_bytes!(msg.channel_id),
5749                                                 if chan_entry.get().sent_shutdown() { " after we initiated shutdown" } else { "" });
5750                                 }
5751
5752                                 let funding_txo_opt = chan_entry.get().context.get_funding_txo();
5753                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_entry!(self,
5754                                         chan_entry.get_mut().shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_entry);
5755                                 dropped_htlcs = htlcs;
5756
5757                                 if let Some(msg) = shutdown {
5758                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
5759                                         // here as we don't need the monitor update to complete until we send a
5760                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
5761                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
5762                                                 node_id: *counterparty_node_id,
5763                                                 msg,
5764                                         });
5765                                 }
5766
5767                                 // Update the monitor with the shutdown script if necessary.
5768                                 if let Some(monitor_update) = monitor_update_opt {
5769                                         break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
5770                                                 peer_state_lock, peer_state, per_peer_state, chan_entry).map(|_| ());
5771                                 }
5772                                 break Ok(());
5773                         } else {
5774                                 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))
5775                         }
5776                 };
5777                 for htlc_source in dropped_htlcs.drain(..) {
5778                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
5779                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
5780                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
5781                 }
5782
5783                 result
5784         }
5785
5786         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
5787                 let per_peer_state = self.per_peer_state.read().unwrap();
5788                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5789                         .ok_or_else(|| {
5790                                 debug_assert!(false);
5791                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5792                         })?;
5793                 let (tx, chan_option) = {
5794                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5795                         let peer_state = &mut *peer_state_lock;
5796                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
5797                                 hash_map::Entry::Occupied(mut chan_entry) => {
5798                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), chan_entry);
5799                                         if let Some(msg) = closing_signed {
5800                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
5801                                                         node_id: counterparty_node_id.clone(),
5802                                                         msg,
5803                                                 });
5804                                         }
5805                                         if tx.is_some() {
5806                                                 // We're done with this channel, we've got a signed closing transaction and
5807                                                 // will send the closing_signed back to the remote peer upon return. This
5808                                                 // also implies there are no pending HTLCs left on the channel, so we can
5809                                                 // fully delete it from tracking (the channel monitor is still around to
5810                                                 // watch for old state broadcasts)!
5811                                                 (tx, Some(remove_channel!(self, chan_entry)))
5812                                         } else { (tx, None) }
5813                                 },
5814                                 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))
5815                         }
5816                 };
5817                 if let Some(broadcast_tx) = tx {
5818                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
5819                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
5820                 }
5821                 if let Some(chan) = chan_option {
5822                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5823                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5824                                 let peer_state = &mut *peer_state_lock;
5825                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5826                                         msg: update
5827                                 });
5828                         }
5829                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
5830                 }
5831                 Ok(())
5832         }
5833
5834         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
5835                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
5836                 //determine the state of the payment based on our response/if we forward anything/the time
5837                 //we take to respond. We should take care to avoid allowing such an attack.
5838                 //
5839                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
5840                 //us repeatedly garbled in different ways, and compare our error messages, which are
5841                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
5842                 //but we should prevent it anyway.
5843
5844                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
5845                 let per_peer_state = self.per_peer_state.read().unwrap();
5846                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5847                         .ok_or_else(|| {
5848                                 debug_assert!(false);
5849                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5850                         })?;
5851                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5852                 let peer_state = &mut *peer_state_lock;
5853                 match peer_state.channel_by_id.entry(msg.channel_id) {
5854                         hash_map::Entry::Occupied(mut chan) => {
5855
5856                                 let pending_forward_info = match decoded_hop_res {
5857                                         Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
5858                                                 self.construct_pending_htlc_status(msg, shared_secret, next_hop,
5859                                                         chan.get().context.config().accept_underpaying_htlcs, next_packet_pk_opt),
5860                                         Err(e) => PendingHTLCStatus::Fail(e)
5861                                 };
5862                                 let create_pending_htlc_status = |chan: &Channel<<SP::Target as SignerProvider>::Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
5863                                         // If the update_add is completely bogus, the call will Err and we will close,
5864                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
5865                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
5866                                         match pending_forward_info {
5867                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
5868                                                         let reason = if (error_code & 0x1000) != 0 {
5869                                                                 let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
5870                                                                 HTLCFailReason::reason(real_code, error_data)
5871                                                         } else {
5872                                                                 HTLCFailReason::from_failure_code(error_code)
5873                                                         }.get_encrypted_failure_packet(incoming_shared_secret, &None);
5874                                                         let msg = msgs::UpdateFailHTLC {
5875                                                                 channel_id: msg.channel_id,
5876                                                                 htlc_id: msg.htlc_id,
5877                                                                 reason
5878                                                         };
5879                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
5880                                                 },
5881                                                 _ => pending_forward_info
5882                                         }
5883                                 };
5884                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &self.logger), chan);
5885                         },
5886                         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))
5887                 }
5888                 Ok(())
5889         }
5890
5891         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
5892                 let funding_txo;
5893                 let (htlc_source, forwarded_htlc_value) = {
5894                         let per_peer_state = self.per_peer_state.read().unwrap();
5895                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5896                                 .ok_or_else(|| {
5897                                         debug_assert!(false);
5898                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5899                                 })?;
5900                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5901                         let peer_state = &mut *peer_state_lock;
5902                         match peer_state.channel_by_id.entry(msg.channel_id) {
5903                                 hash_map::Entry::Occupied(mut chan) => {
5904                                         let res = try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), chan);
5905                                         funding_txo = chan.get().context.get_funding_txo().expect("We won't accept a fulfill until funded");
5906                                         res
5907                                 },
5908                                 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))
5909                         }
5910                 };
5911                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, funding_txo);
5912                 Ok(())
5913         }
5914
5915         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
5916                 let per_peer_state = self.per_peer_state.read().unwrap();
5917                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5918                         .ok_or_else(|| {
5919                                 debug_assert!(false);
5920                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5921                         })?;
5922                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5923                 let peer_state = &mut *peer_state_lock;
5924                 match peer_state.channel_by_id.entry(msg.channel_id) {
5925                         hash_map::Entry::Occupied(mut chan) => {
5926                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan);
5927                         },
5928                         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))
5929                 }
5930                 Ok(())
5931         }
5932
5933         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
5934                 let per_peer_state = self.per_peer_state.read().unwrap();
5935                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5936                         .ok_or_else(|| {
5937                                 debug_assert!(false);
5938                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5939                         })?;
5940                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5941                 let peer_state = &mut *peer_state_lock;
5942                 match peer_state.channel_by_id.entry(msg.channel_id) {
5943                         hash_map::Entry::Occupied(mut chan) => {
5944                                 if (msg.failure_code & 0x8000) == 0 {
5945                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
5946                                         try_chan_entry!(self, Err(chan_err), chan);
5947                                 }
5948                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan);
5949                                 Ok(())
5950                         },
5951                         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))
5952                 }
5953         }
5954
5955         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
5956                 let per_peer_state = self.per_peer_state.read().unwrap();
5957                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5958                         .ok_or_else(|| {
5959                                 debug_assert!(false);
5960                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5961                         })?;
5962                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5963                 let peer_state = &mut *peer_state_lock;
5964                 match peer_state.channel_by_id.entry(msg.channel_id) {
5965                         hash_map::Entry::Occupied(mut chan) => {
5966                                 let funding_txo = chan.get().context.get_funding_txo();
5967                                 let monitor_update_opt = try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &self.logger), chan);
5968                                 if let Some(monitor_update) = monitor_update_opt {
5969                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
5970                                                 peer_state, per_peer_state, chan).map(|_| ())
5971                                 } else { Ok(()) }
5972                         },
5973                         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))
5974                 }
5975         }
5976
5977         #[inline]
5978         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
5979                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
5980                         let mut push_forward_event = false;
5981                         let mut new_intercept_events = VecDeque::new();
5982                         let mut failed_intercept_forwards = Vec::new();
5983                         if !pending_forwards.is_empty() {
5984                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
5985                                         let scid = match forward_info.routing {
5986                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
5987                                                 PendingHTLCRouting::Receive { .. } => 0,
5988                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
5989                                         };
5990                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
5991                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
5992
5993                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5994                                         let forward_htlcs_empty = forward_htlcs.is_empty();
5995                                         match forward_htlcs.entry(scid) {
5996                                                 hash_map::Entry::Occupied(mut entry) => {
5997                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
5998                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
5999                                                 },
6000                                                 hash_map::Entry::Vacant(entry) => {
6001                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6002                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.genesis_hash)
6003                                                         {
6004                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6005                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6006                                                                 match pending_intercepts.entry(intercept_id) {
6007                                                                         hash_map::Entry::Vacant(entry) => {
6008                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6009                                                                                         requested_next_hop_scid: scid,
6010                                                                                         payment_hash: forward_info.payment_hash,
6011                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6012                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6013                                                                                         intercept_id
6014                                                                                 }, None));
6015                                                                                 entry.insert(PendingAddHTLCInfo {
6016                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6017                                                                         },
6018                                                                         hash_map::Entry::Occupied(_) => {
6019                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6020                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6021                                                                                         short_channel_id: prev_short_channel_id,
6022                                                                                         outpoint: prev_funding_outpoint,
6023                                                                                         htlc_id: prev_htlc_id,
6024                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6025                                                                                         phantom_shared_secret: None,
6026                                                                                 });
6027
6028                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6029                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6030                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6031                                                                                 ));
6032                                                                         }
6033                                                                 }
6034                                                         } else {
6035                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6036                                                                 // payments are being processed.
6037                                                                 if forward_htlcs_empty {
6038                                                                         push_forward_event = true;
6039                                                                 }
6040                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6041                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6042                                                         }
6043                                                 }
6044                                         }
6045                                 }
6046                         }
6047
6048                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6049                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6050                         }
6051
6052                         if !new_intercept_events.is_empty() {
6053                                 let mut events = self.pending_events.lock().unwrap();
6054                                 events.append(&mut new_intercept_events);
6055                         }
6056                         if push_forward_event { self.push_pending_forwards_ev() }
6057                 }
6058         }
6059
6060         fn push_pending_forwards_ev(&self) {
6061                 let mut pending_events = self.pending_events.lock().unwrap();
6062                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6063                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6064                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6065                 ).count();
6066                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6067                 // events is done in batches and they are not removed until we're done processing each
6068                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6069                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6070                 // payments will need an additional forwarding event before being claimed to make them look
6071                 // real by taking more time.
6072                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6073                         pending_events.push_back((Event::PendingHTLCsForwardable {
6074                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6075                         }, None));
6076                 }
6077         }
6078
6079         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6080         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6081         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6082         /// the [`ChannelMonitorUpdate`] in question.
6083         fn raa_monitor_updates_held(&self,
6084                 actions_blocking_raa_monitor_updates: &BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
6085                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6086         ) -> bool {
6087                 actions_blocking_raa_monitor_updates
6088                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6089                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6090                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6091                                 channel_funding_outpoint,
6092                                 counterparty_node_id,
6093                         })
6094                 })
6095         }
6096
6097         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6098                 let (htlcs_to_fail, res) = {
6099                         let per_peer_state = self.per_peer_state.read().unwrap();
6100                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6101                                 .ok_or_else(|| {
6102                                         debug_assert!(false);
6103                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6104                                 }).map(|mtx| mtx.lock().unwrap())?;
6105                         let peer_state = &mut *peer_state_lock;
6106                         match peer_state.channel_by_id.entry(msg.channel_id) {
6107                                 hash_map::Entry::Occupied(mut chan) => {
6108                                         let funding_txo_opt = chan.get().context.get_funding_txo();
6109                                         let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
6110                                                 self.raa_monitor_updates_held(
6111                                                         &peer_state.actions_blocking_raa_monitor_updates, funding_txo,
6112                                                         *counterparty_node_id)
6113                                         } else { false };
6114                                         let (htlcs_to_fail, monitor_update_opt) = try_chan_entry!(self,
6115                                                 chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger, mon_update_blocked), chan);
6116                                         let res = if let Some(monitor_update) = monitor_update_opt {
6117                                                 let funding_txo = funding_txo_opt
6118                                                         .expect("Funding outpoint must have been set for RAA handling to succeed");
6119                                                 handle_new_monitor_update!(self, funding_txo, monitor_update,
6120                                                         peer_state_lock, peer_state, per_peer_state, chan).map(|_| ())
6121                                         } else { Ok(()) };
6122                                         (htlcs_to_fail, res)
6123                                 },
6124                                 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))
6125                         }
6126                 };
6127                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6128                 res
6129         }
6130
6131         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6132                 let per_peer_state = self.per_peer_state.read().unwrap();
6133                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6134                         .ok_or_else(|| {
6135                                 debug_assert!(false);
6136                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6137                         })?;
6138                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6139                 let peer_state = &mut *peer_state_lock;
6140                 match peer_state.channel_by_id.entry(msg.channel_id) {
6141                         hash_map::Entry::Occupied(mut chan) => {
6142                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg, &self.logger), chan);
6143                         },
6144                         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))
6145                 }
6146                 Ok(())
6147         }
6148
6149         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6150                 let per_peer_state = self.per_peer_state.read().unwrap();
6151                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6152                         .ok_or_else(|| {
6153                                 debug_assert!(false);
6154                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6155                         })?;
6156                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6157                 let peer_state = &mut *peer_state_lock;
6158                 match peer_state.channel_by_id.entry(msg.channel_id) {
6159                         hash_map::Entry::Occupied(mut chan) => {
6160                                 if !chan.get().context.is_usable() {
6161                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6162                                 }
6163
6164                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6165                                         msg: try_chan_entry!(self, chan.get_mut().announcement_signatures(
6166                                                 &self.node_signer, self.genesis_hash.clone(), self.best_block.read().unwrap().height(),
6167                                                 msg, &self.default_configuration
6168                                         ), chan),
6169                                         // Note that announcement_signatures fails if the channel cannot be announced,
6170                                         // so get_channel_update_for_broadcast will never fail by the time we get here.
6171                                         update_msg: Some(self.get_channel_update_for_broadcast(chan.get()).unwrap()),
6172                                 });
6173                         },
6174                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6175                 }
6176                 Ok(())
6177         }
6178
6179         /// Returns ShouldPersist if anything changed, otherwise either SkipPersist or an Err.
6180         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6181                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6182                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6183                         None => {
6184                                 // It's not a local channel
6185                                 return Ok(NotifyOption::SkipPersist)
6186                         }
6187                 };
6188                 let per_peer_state = self.per_peer_state.read().unwrap();
6189                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6190                 if peer_state_mutex_opt.is_none() {
6191                         return Ok(NotifyOption::SkipPersist)
6192                 }
6193                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6194                 let peer_state = &mut *peer_state_lock;
6195                 match peer_state.channel_by_id.entry(chan_id) {
6196                         hash_map::Entry::Occupied(mut chan) => {
6197                                 if chan.get().context.get_counterparty_node_id() != *counterparty_node_id {
6198                                         if chan.get().context.should_announce() {
6199                                                 // If the announcement is about a channel of ours which is public, some
6200                                                 // other peer may simply be forwarding all its gossip to us. Don't provide
6201                                                 // a scary-looking error message and return Ok instead.
6202                                                 return Ok(NotifyOption::SkipPersist);
6203                                         }
6204                                         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));
6205                                 }
6206                                 let were_node_one = self.get_our_node_id().serialize()[..] < chan.get().context.get_counterparty_node_id().serialize()[..];
6207                                 let msg_from_node_one = msg.contents.flags & 1 == 0;
6208                                 if were_node_one == msg_from_node_one {
6209                                         return Ok(NotifyOption::SkipPersist);
6210                                 } else {
6211                                         log_debug!(self.logger, "Received channel_update for channel {}.", log_bytes!(chan_id));
6212                                         try_chan_entry!(self, chan.get_mut().channel_update(&msg), chan);
6213                                 }
6214                         },
6215                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersist)
6216                 }
6217                 Ok(NotifyOption::DoPersist)
6218         }
6219
6220         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
6221                 let htlc_forwards;
6222                 let need_lnd_workaround = {
6223                         let per_peer_state = self.per_peer_state.read().unwrap();
6224
6225                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6226                                 .ok_or_else(|| {
6227                                         debug_assert!(false);
6228                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6229                                 })?;
6230                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6231                         let peer_state = &mut *peer_state_lock;
6232                         match peer_state.channel_by_id.entry(msg.channel_id) {
6233                                 hash_map::Entry::Occupied(mut chan) => {
6234                                         // Currently, we expect all holding cell update_adds to be dropped on peer
6235                                         // disconnect, so Channel's reestablish will never hand us any holding cell
6236                                         // freed HTLCs to fail backwards. If in the future we no longer drop pending
6237                                         // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6238                                         let responses = try_chan_entry!(self, chan.get_mut().channel_reestablish(
6239                                                 msg, &self.logger, &self.node_signer, self.genesis_hash,
6240                                                 &self.default_configuration, &*self.best_block.read().unwrap()), chan);
6241                                         let mut channel_update = None;
6242                                         if let Some(msg) = responses.shutdown_msg {
6243                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6244                                                         node_id: counterparty_node_id.clone(),
6245                                                         msg,
6246                                                 });
6247                                         } else if chan.get().context.is_usable() {
6248                                                 // If the channel is in a usable state (ie the channel is not being shut
6249                                                 // down), send a unicast channel_update to our counterparty to make sure
6250                                                 // they have the latest channel parameters.
6251                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
6252                                                         channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
6253                                                                 node_id: chan.get().context.get_counterparty_node_id(),
6254                                                                 msg,
6255                                                         });
6256                                                 }
6257                                         }
6258                                         let need_lnd_workaround = chan.get_mut().context.workaround_lnd_bug_4006.take();
6259                                         htlc_forwards = self.handle_channel_resumption(
6260                                                 &mut peer_state.pending_msg_events, chan.get_mut(), responses.raa, responses.commitment_update, responses.order,
6261                                                 Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
6262                                         if let Some(upd) = channel_update {
6263                                                 peer_state.pending_msg_events.push(upd);
6264                                         }
6265                                         need_lnd_workaround
6266                                 },
6267                                 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))
6268                         }
6269                 };
6270
6271                 if let Some(forwards) = htlc_forwards {
6272                         self.forward_htlcs(&mut [forwards][..]);
6273                 }
6274
6275                 if let Some(channel_ready_msg) = need_lnd_workaround {
6276                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
6277                 }
6278                 Ok(())
6279         }
6280
6281         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
6282         fn process_pending_monitor_events(&self) -> bool {
6283                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
6284
6285                 let mut failed_channels = Vec::new();
6286                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
6287                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
6288                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
6289                         for monitor_event in monitor_events.drain(..) {
6290                                 match monitor_event {
6291                                         MonitorEvent::HTLCEvent(htlc_update) => {
6292                                                 if let Some(preimage) = htlc_update.payment_preimage {
6293                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
6294                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, funding_outpoint);
6295                                                 } else {
6296                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
6297                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
6298                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6299                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
6300                                                 }
6301                                         },
6302                                         MonitorEvent::CommitmentTxConfirmed(funding_outpoint) |
6303                                         MonitorEvent::UpdateFailed(funding_outpoint) => {
6304                                                 let counterparty_node_id_opt = match counterparty_node_id {
6305                                                         Some(cp_id) => Some(cp_id),
6306                                                         None => {
6307                                                                 // TODO: Once we can rely on the counterparty_node_id from the
6308                                                                 // monitor event, this and the id_to_peer map should be removed.
6309                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
6310                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
6311                                                         }
6312                                                 };
6313                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
6314                                                         let per_peer_state = self.per_peer_state.read().unwrap();
6315                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
6316                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6317                                                                 let peer_state = &mut *peer_state_lock;
6318                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6319                                                                 if let hash_map::Entry::Occupied(chan_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
6320                                                                         let mut chan = remove_channel!(self, chan_entry);
6321                                                                         failed_channels.push(chan.context.force_shutdown(false));
6322                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6323                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6324                                                                                         msg: update
6325                                                                                 });
6326                                                                         }
6327                                                                         let reason = if let MonitorEvent::UpdateFailed(_) = monitor_event {
6328                                                                                 ClosureReason::ProcessingError { err: "Failed to persist ChannelMonitor update during chain sync".to_string() }
6329                                                                         } else {
6330                                                                                 ClosureReason::CommitmentTxConfirmed
6331                                                                         };
6332                                                                         self.issue_channel_close_events(&chan.context, reason);
6333                                                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
6334                                                                                 node_id: chan.context.get_counterparty_node_id(),
6335                                                                                 action: msgs::ErrorAction::SendErrorMessage {
6336                                                                                         msg: msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() }
6337                                                                                 },
6338                                                                         });
6339                                                                 }
6340                                                         }
6341                                                 }
6342                                         },
6343                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
6344                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
6345                                         },
6346                                 }
6347                         }
6348                 }
6349
6350                 for failure in failed_channels.drain(..) {
6351                         self.finish_force_close_channel(failure);
6352                 }
6353
6354                 has_pending_monitor_events
6355         }
6356
6357         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
6358         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
6359         /// update events as a separate process method here.
6360         #[cfg(fuzzing)]
6361         pub fn process_monitor_events(&self) {
6362                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6363                 self.process_pending_monitor_events();
6364         }
6365
6366         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
6367         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
6368         /// update was applied.
6369         fn check_free_holding_cells(&self) -> bool {
6370                 let mut has_monitor_update = false;
6371                 let mut failed_htlcs = Vec::new();
6372                 let mut handle_errors = Vec::new();
6373
6374                 // Walk our list of channels and find any that need to update. Note that when we do find an
6375                 // update, if it includes actions that must be taken afterwards, we have to drop the
6376                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
6377                 // manage to go through all our peers without finding a single channel to update.
6378                 'peer_loop: loop {
6379                         let per_peer_state = self.per_peer_state.read().unwrap();
6380                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6381                                 'chan_loop: loop {
6382                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6383                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
6384                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut() {
6385                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
6386                                                 let funding_txo = chan.context.get_funding_txo();
6387                                                 let (monitor_opt, holding_cell_failed_htlcs) =
6388                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
6389                                                 if !holding_cell_failed_htlcs.is_empty() {
6390                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
6391                                                 }
6392                                                 if let Some(monitor_update) = monitor_opt {
6393                                                         has_monitor_update = true;
6394
6395                                                         let channel_id: [u8; 32] = *channel_id;
6396                                                         let res = handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
6397                                                                 peer_state_lock, peer_state, per_peer_state, chan, MANUALLY_REMOVING,
6398                                                                 peer_state.channel_by_id.remove(&channel_id));
6399                                                         if res.is_err() {
6400                                                                 handle_errors.push((counterparty_node_id, res));
6401                                                         }
6402                                                         continue 'peer_loop;
6403                                                 }
6404                                         }
6405                                         break 'chan_loop;
6406                                 }
6407                         }
6408                         break 'peer_loop;
6409                 }
6410
6411                 let has_update = has_monitor_update || !failed_htlcs.is_empty() || !handle_errors.is_empty();
6412                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
6413                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
6414                 }
6415
6416                 for (counterparty_node_id, err) in handle_errors.drain(..) {
6417                         let _ = handle_error!(self, err, counterparty_node_id);
6418                 }
6419
6420                 has_update
6421         }
6422
6423         /// Check whether any channels have finished removing all pending updates after a shutdown
6424         /// exchange and can now send a closing_signed.
6425         /// Returns whether any closing_signed messages were generated.
6426         fn maybe_generate_initial_closing_signed(&self) -> bool {
6427                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
6428                 let mut has_update = false;
6429                 {
6430                         let per_peer_state = self.per_peer_state.read().unwrap();
6431
6432                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6433                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6434                                 let peer_state = &mut *peer_state_lock;
6435                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6436                                 peer_state.channel_by_id.retain(|channel_id, chan| {
6437                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
6438                                                 Ok((msg_opt, tx_opt)) => {
6439                                                         if let Some(msg) = msg_opt {
6440                                                                 has_update = true;
6441                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6442                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
6443                                                                 });
6444                                                         }
6445                                                         if let Some(tx) = tx_opt {
6446                                                                 // We're done with this channel. We got a closing_signed and sent back
6447                                                                 // a closing_signed with a closing transaction to broadcast.
6448                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6449                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6450                                                                                 msg: update
6451                                                                         });
6452                                                                 }
6453
6454                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6455
6456                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
6457                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
6458                                                                 update_maps_on_chan_removal!(self, &chan.context);
6459                                                                 false
6460                                                         } else { true }
6461                                                 },
6462                                                 Err(e) => {
6463                                                         has_update = true;
6464                                                         let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
6465                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
6466                                                         !close_channel
6467                                                 }
6468                                         }
6469                                 });
6470                         }
6471                 }
6472
6473                 for (counterparty_node_id, err) in handle_errors.drain(..) {
6474                         let _ = handle_error!(self, err, counterparty_node_id);
6475                 }
6476
6477                 has_update
6478         }
6479
6480         /// Handle a list of channel failures during a block_connected or block_disconnected call,
6481         /// pushing the channel monitor update (if any) to the background events queue and removing the
6482         /// Channel object.
6483         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
6484                 for mut failure in failed_channels.drain(..) {
6485                         // Either a commitment transactions has been confirmed on-chain or
6486                         // Channel::block_disconnected detected that the funding transaction has been
6487                         // reorganized out of the main chain.
6488                         // We cannot broadcast our latest local state via monitor update (as
6489                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
6490                         // so we track the update internally and handle it when the user next calls
6491                         // timer_tick_occurred, guaranteeing we're running normally.
6492                         if let Some((counterparty_node_id, funding_txo, update)) = failure.0.take() {
6493                                 assert_eq!(update.updates.len(), 1);
6494                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
6495                                         assert!(should_broadcast);
6496                                 } else { unreachable!(); }
6497                                 self.pending_background_events.lock().unwrap().push(
6498                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
6499                                                 counterparty_node_id, funding_txo, update
6500                                         });
6501                         }
6502                         self.finish_force_close_channel(failure);
6503                 }
6504         }
6505
6506         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
6507         /// to pay us.
6508         ///
6509         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
6510         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
6511         ///
6512         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
6513         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
6514         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
6515         /// passed directly to [`claim_funds`].
6516         ///
6517         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
6518         ///
6519         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
6520         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
6521         ///
6522         /// # Note
6523         ///
6524         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
6525         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
6526         ///
6527         /// Errors if `min_value_msat` is greater than total bitcoin supply.
6528         ///
6529         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
6530         /// on versions of LDK prior to 0.0.114.
6531         ///
6532         /// [`claim_funds`]: Self::claim_funds
6533         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
6534         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
6535         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
6536         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
6537         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
6538         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
6539                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
6540                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
6541                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
6542                         min_final_cltv_expiry_delta)
6543         }
6544
6545         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
6546         /// stored external to LDK.
6547         ///
6548         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
6549         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
6550         /// the `min_value_msat` provided here, if one is provided.
6551         ///
6552         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
6553         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
6554         /// payments.
6555         ///
6556         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
6557         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
6558         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
6559         /// sender "proof-of-payment" unless they have paid the required amount.
6560         ///
6561         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
6562         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
6563         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
6564         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
6565         /// invoices when no timeout is set.
6566         ///
6567         /// Note that we use block header time to time-out pending inbound payments (with some margin
6568         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
6569         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
6570         /// If you need exact expiry semantics, you should enforce them upon receipt of
6571         /// [`PaymentClaimable`].
6572         ///
6573         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
6574         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
6575         ///
6576         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
6577         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
6578         ///
6579         /// # Note
6580         ///
6581         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
6582         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
6583         ///
6584         /// Errors if `min_value_msat` is greater than total bitcoin supply.
6585         ///
6586         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
6587         /// on versions of LDK prior to 0.0.114.
6588         ///
6589         /// [`create_inbound_payment`]: Self::create_inbound_payment
6590         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
6591         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
6592                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
6593                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
6594                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
6595                         min_final_cltv_expiry)
6596         }
6597
6598         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
6599         /// previously returned from [`create_inbound_payment`].
6600         ///
6601         /// [`create_inbound_payment`]: Self::create_inbound_payment
6602         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
6603                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
6604         }
6605
6606         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
6607         /// are used when constructing the phantom invoice's route hints.
6608         ///
6609         /// [phantom node payments]: crate::sign::PhantomKeysManager
6610         pub fn get_phantom_scid(&self) -> u64 {
6611                 let best_block_height = self.best_block.read().unwrap().height();
6612                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
6613                 loop {
6614                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
6615                         // Ensure the generated scid doesn't conflict with a real channel.
6616                         match short_to_chan_info.get(&scid_candidate) {
6617                                 Some(_) => continue,
6618                                 None => return scid_candidate
6619                         }
6620                 }
6621         }
6622
6623         /// Gets route hints for use in receiving [phantom node payments].
6624         ///
6625         /// [phantom node payments]: crate::sign::PhantomKeysManager
6626         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
6627                 PhantomRouteHints {
6628                         channels: self.list_usable_channels(),
6629                         phantom_scid: self.get_phantom_scid(),
6630                         real_node_pubkey: self.get_our_node_id(),
6631                 }
6632         }
6633
6634         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
6635         /// used when constructing the route hints for HTLCs intended to be intercepted. See
6636         /// [`ChannelManager::forward_intercepted_htlc`].
6637         ///
6638         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
6639         /// times to get a unique scid.
6640         pub fn get_intercept_scid(&self) -> u64 {
6641                 let best_block_height = self.best_block.read().unwrap().height();
6642                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
6643                 loop {
6644                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
6645                         // Ensure the generated scid doesn't conflict with a real channel.
6646                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
6647                         return scid_candidate
6648                 }
6649         }
6650
6651         /// Gets inflight HTLC information by processing pending outbound payments that are in
6652         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
6653         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
6654                 let mut inflight_htlcs = InFlightHtlcs::new();
6655
6656                 let per_peer_state = self.per_peer_state.read().unwrap();
6657                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6658                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6659                         let peer_state = &mut *peer_state_lock;
6660                         for chan in peer_state.channel_by_id.values() {
6661                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
6662                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
6663                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
6664                                         }
6665                                 }
6666                         }
6667                 }
6668
6669                 inflight_htlcs
6670         }
6671
6672         #[cfg(any(test, feature = "_test_utils"))]
6673         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
6674                 let events = core::cell::RefCell::new(Vec::new());
6675                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
6676                 self.process_pending_events(&event_handler);
6677                 events.into_inner()
6678         }
6679
6680         #[cfg(feature = "_test_utils")]
6681         pub fn push_pending_event(&self, event: events::Event) {
6682                 let mut events = self.pending_events.lock().unwrap();
6683                 events.push_back((event, None));
6684         }
6685
6686         #[cfg(test)]
6687         pub fn pop_pending_event(&self) -> Option<events::Event> {
6688                 let mut events = self.pending_events.lock().unwrap();
6689                 events.pop_front().map(|(e, _)| e)
6690         }
6691
6692         #[cfg(test)]
6693         pub fn has_pending_payments(&self) -> bool {
6694                 self.pending_outbound_payments.has_pending_payments()
6695         }
6696
6697         #[cfg(test)]
6698         pub fn clear_pending_payments(&self) {
6699                 self.pending_outbound_payments.clear_pending_payments()
6700         }
6701
6702         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
6703         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
6704         /// operation. It will double-check that nothing *else* is also blocking the same channel from
6705         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
6706         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
6707                 let mut errors = Vec::new();
6708                 loop {
6709                         let per_peer_state = self.per_peer_state.read().unwrap();
6710                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6711                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6712                                 let peer_state = &mut *peer_state_lck;
6713
6714                                 if let Some(blocker) = completed_blocker.take() {
6715                                         // Only do this on the first iteration of the loop.
6716                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
6717                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
6718                                         {
6719                                                 blockers.retain(|iter| iter != &blocker);
6720                                         }
6721                                 }
6722
6723                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6724                                         channel_funding_outpoint, counterparty_node_id) {
6725                                         // Check that, while holding the peer lock, we don't have anything else
6726                                         // blocking monitor updates for this channel. If we do, release the monitor
6727                                         // update(s) when those blockers complete.
6728                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
6729                                                 log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6730                                         break;
6731                                 }
6732
6733                                 if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
6734                                         debug_assert_eq!(chan.get().context.get_funding_txo().unwrap(), channel_funding_outpoint);
6735                                         if let Some((monitor_update, further_update_exists)) = chan.get_mut().unblock_next_blocked_monitor_update() {
6736                                                 log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
6737                                                         log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6738                                                 if let Err(e) = handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
6739                                                         peer_state_lck, peer_state, per_peer_state, chan)
6740                                                 {
6741                                                         errors.push((e, counterparty_node_id));
6742                                                 }
6743                                                 if further_update_exists {
6744                                                         // If there are more `ChannelMonitorUpdate`s to process, restart at the
6745                                                         // top of the loop.
6746                                                         continue;
6747                                                 }
6748                                         } else {
6749                                                 log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
6750                                                         log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6751                                         }
6752                                 }
6753                         } else {
6754                                 log_debug!(self.logger,
6755                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
6756                                         log_pubkey!(counterparty_node_id));
6757                         }
6758                         break;
6759                 }
6760                 for (err, counterparty_node_id) in errors {
6761                         let res = Err::<(), _>(err);
6762                         let _ = handle_error!(self, res, counterparty_node_id);
6763                 }
6764         }
6765
6766         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
6767                 for action in actions {
6768                         match action {
6769                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6770                                         channel_funding_outpoint, counterparty_node_id
6771                                 } => {
6772                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
6773                                 }
6774                         }
6775                 }
6776         }
6777
6778         /// Processes any events asynchronously in the order they were generated since the last call
6779         /// using the given event handler.
6780         ///
6781         /// See the trait-level documentation of [`EventsProvider`] for requirements.
6782         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
6783                 &self, handler: H
6784         ) {
6785                 let mut ev;
6786                 process_events_body!(self, ev, { handler(ev).await });
6787         }
6788 }
6789
6790 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>
6791 where
6792         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6793         T::Target: BroadcasterInterface,
6794         ES::Target: EntropySource,
6795         NS::Target: NodeSigner,
6796         SP::Target: SignerProvider,
6797         F::Target: FeeEstimator,
6798         R::Target: Router,
6799         L::Target: Logger,
6800 {
6801         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
6802         /// The returned array will contain `MessageSendEvent`s for different peers if
6803         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
6804         /// is always placed next to each other.
6805         ///
6806         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
6807         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
6808         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
6809         /// will randomly be placed first or last in the returned array.
6810         ///
6811         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
6812         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
6813         /// the `MessageSendEvent`s to the specific peer they were generated under.
6814         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
6815                 let events = RefCell::new(Vec::new());
6816                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
6817                         let mut result = self.process_background_events();
6818
6819                         // TODO: This behavior should be documented. It's unintuitive that we query
6820                         // ChannelMonitors when clearing other events.
6821                         if self.process_pending_monitor_events() {
6822                                 result = NotifyOption::DoPersist;
6823                         }
6824
6825                         if self.check_free_holding_cells() {
6826                                 result = NotifyOption::DoPersist;
6827                         }
6828                         if self.maybe_generate_initial_closing_signed() {
6829                                 result = NotifyOption::DoPersist;
6830                         }
6831
6832                         let mut pending_events = Vec::new();
6833                         let per_peer_state = self.per_peer_state.read().unwrap();
6834                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6835                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6836                                 let peer_state = &mut *peer_state_lock;
6837                                 if peer_state.pending_msg_events.len() > 0 {
6838                                         pending_events.append(&mut peer_state.pending_msg_events);
6839                                 }
6840                         }
6841
6842                         if !pending_events.is_empty() {
6843                                 events.replace(pending_events);
6844                         }
6845
6846                         result
6847                 });
6848                 events.into_inner()
6849         }
6850 }
6851
6852 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>
6853 where
6854         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6855         T::Target: BroadcasterInterface,
6856         ES::Target: EntropySource,
6857         NS::Target: NodeSigner,
6858         SP::Target: SignerProvider,
6859         F::Target: FeeEstimator,
6860         R::Target: Router,
6861         L::Target: Logger,
6862 {
6863         /// Processes events that must be periodically handled.
6864         ///
6865         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
6866         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
6867         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
6868                 let mut ev;
6869                 process_events_body!(self, ev, handler.handle_event(ev));
6870         }
6871 }
6872
6873 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>
6874 where
6875         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6876         T::Target: BroadcasterInterface,
6877         ES::Target: EntropySource,
6878         NS::Target: NodeSigner,
6879         SP::Target: SignerProvider,
6880         F::Target: FeeEstimator,
6881         R::Target: Router,
6882         L::Target: Logger,
6883 {
6884         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
6885                 {
6886                         let best_block = self.best_block.read().unwrap();
6887                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
6888                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
6889                         assert_eq!(best_block.height(), height - 1,
6890                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
6891                 }
6892
6893                 self.transactions_confirmed(header, txdata, height);
6894                 self.best_block_updated(header, height);
6895         }
6896
6897         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
6898                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6899                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6900                 let new_height = height - 1;
6901                 {
6902                         let mut best_block = self.best_block.write().unwrap();
6903                         assert_eq!(best_block.block_hash(), header.block_hash(),
6904                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
6905                         assert_eq!(best_block.height(), height,
6906                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
6907                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
6908                 }
6909
6910                 self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
6911         }
6912 }
6913
6914 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>
6915 where
6916         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6917         T::Target: BroadcasterInterface,
6918         ES::Target: EntropySource,
6919         NS::Target: NodeSigner,
6920         SP::Target: SignerProvider,
6921         F::Target: FeeEstimator,
6922         R::Target: Router,
6923         L::Target: Logger,
6924 {
6925         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
6926                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
6927                 // during initialization prior to the chain_monitor being fully configured in some cases.
6928                 // See the docs for `ChannelManagerReadArgs` for more.
6929
6930                 let block_hash = header.block_hash();
6931                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
6932
6933                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6934                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6935                 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger)
6936                         .map(|(a, b)| (a, Vec::new(), b)));
6937
6938                 let last_best_block_height = self.best_block.read().unwrap().height();
6939                 if height < last_best_block_height {
6940                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
6941                         self.do_chain_event(Some(last_best_block_height), |channel| channel.best_block_updated(last_best_block_height, timestamp as u32, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
6942                 }
6943         }
6944
6945         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
6946                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
6947                 // during initialization prior to the chain_monitor being fully configured in some cases.
6948                 // See the docs for `ChannelManagerReadArgs` for more.
6949
6950                 let block_hash = header.block_hash();
6951                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
6952
6953                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6954                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6955                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
6956
6957                 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
6958
6959                 macro_rules! max_time {
6960                         ($timestamp: expr) => {
6961                                 loop {
6962                                         // Update $timestamp to be the max of its current value and the block
6963                                         // timestamp. This should keep us close to the current time without relying on
6964                                         // having an explicit local time source.
6965                                         // Just in case we end up in a race, we loop until we either successfully
6966                                         // update $timestamp or decide we don't need to.
6967                                         let old_serial = $timestamp.load(Ordering::Acquire);
6968                                         if old_serial >= header.time as usize { break; }
6969                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
6970                                                 break;
6971                                         }
6972                                 }
6973                         }
6974                 }
6975                 max_time!(self.highest_seen_timestamp);
6976                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
6977                 payment_secrets.retain(|_, inbound_payment| {
6978                         inbound_payment.expiry_time > header.time as u64
6979                 });
6980         }
6981
6982         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
6983                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
6984                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
6985                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6986                         let peer_state = &mut *peer_state_lock;
6987                         for chan in peer_state.channel_by_id.values() {
6988                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
6989                                         res.push((funding_txo.txid, Some(block_hash)));
6990                                 }
6991                         }
6992                 }
6993                 res
6994         }
6995
6996         fn transaction_unconfirmed(&self, txid: &Txid) {
6997                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6998                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6999                 self.do_chain_event(None, |channel| {
7000                         if let Some(funding_txo) = channel.context.get_funding_txo() {
7001                                 if funding_txo.txid == *txid {
7002                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
7003                                 } else { Ok((None, Vec::new(), None)) }
7004                         } else { Ok((None, Vec::new(), None)) }
7005                 });
7006         }
7007 }
7008
7009 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>
7010 where
7011         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7012         T::Target: BroadcasterInterface,
7013         ES::Target: EntropySource,
7014         NS::Target: NodeSigner,
7015         SP::Target: SignerProvider,
7016         F::Target: FeeEstimator,
7017         R::Target: Router,
7018         L::Target: Logger,
7019 {
7020         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
7021         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
7022         /// the function.
7023         fn do_chain_event<FN: Fn(&mut Channel<<SP::Target as SignerProvider>::Signer>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
7024                         (&self, height_opt: Option<u32>, f: FN) {
7025                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7026                 // during initialization prior to the chain_monitor being fully configured in some cases.
7027                 // See the docs for `ChannelManagerReadArgs` for more.
7028
7029                 let mut failed_channels = Vec::new();
7030                 let mut timed_out_htlcs = Vec::new();
7031                 {
7032                         let per_peer_state = self.per_peer_state.read().unwrap();
7033                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7034                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7035                                 let peer_state = &mut *peer_state_lock;
7036                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7037                                 peer_state.channel_by_id.retain(|_, channel| {
7038                                         let res = f(channel);
7039                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
7040                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
7041                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
7042                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
7043                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
7044                                                 }
7045                                                 if let Some(channel_ready) = channel_ready_opt {
7046                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
7047                                                         if channel.context.is_usable() {
7048                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", log_bytes!(channel.context.channel_id()));
7049                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
7050                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
7051                                                                                 node_id: channel.context.get_counterparty_node_id(),
7052                                                                                 msg,
7053                                                                         });
7054                                                                 }
7055                                                         } else {
7056                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", log_bytes!(channel.context.channel_id()));
7057                                                         }
7058                                                 }
7059
7060                                                 {
7061                                                         let mut pending_events = self.pending_events.lock().unwrap();
7062                                                         emit_channel_ready_event!(pending_events, channel);
7063                                                 }
7064
7065                                                 if let Some(announcement_sigs) = announcement_sigs {
7066                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(channel.context.channel_id()));
7067                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
7068                                                                 node_id: channel.context.get_counterparty_node_id(),
7069                                                                 msg: announcement_sigs,
7070                                                         });
7071                                                         if let Some(height) = height_opt {
7072                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.genesis_hash, height, &self.default_configuration) {
7073                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7074                                                                                 msg: announcement,
7075                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7076                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7077                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
7078                                                                         });
7079                                                                 }
7080                                                         }
7081                                                 }
7082                                                 if channel.is_our_channel_ready() {
7083                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
7084                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
7085                                                                 // to the short_to_chan_info map here. Note that we check whether we
7086                                                                 // can relay using the real SCID at relay-time (i.e.
7087                                                                 // enforce option_scid_alias then), and if the funding tx is ever
7088                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
7089                                                                 // is always consistent.
7090                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
7091                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
7092                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
7093                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
7094                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
7095                                                         }
7096                                                 }
7097                                         } else if let Err(reason) = res {
7098                                                 update_maps_on_chan_removal!(self, &channel.context);
7099                                                 // It looks like our counterparty went on-chain or funding transaction was
7100                                                 // reorged out of the main chain. Close the channel.
7101                                                 failed_channels.push(channel.context.force_shutdown(true));
7102                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
7103                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7104                                                                 msg: update
7105                                                         });
7106                                                 }
7107                                                 let reason_message = format!("{}", reason);
7108                                                 self.issue_channel_close_events(&channel.context, reason);
7109                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7110                                                         node_id: channel.context.get_counterparty_node_id(),
7111                                                         action: msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage {
7112                                                                 channel_id: channel.context.channel_id(),
7113                                                                 data: reason_message,
7114                                                         } },
7115                                                 });
7116                                                 return false;
7117                                         }
7118                                         true
7119                                 });
7120                         }
7121                 }
7122
7123                 if let Some(height) = height_opt {
7124                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
7125                                 payment.htlcs.retain(|htlc| {
7126                                         // If height is approaching the number of blocks we think it takes us to get
7127                                         // our commitment transaction confirmed before the HTLC expires, plus the
7128                                         // number of blocks we generally consider it to take to do a commitment update,
7129                                         // just give up on it and fail the HTLC.
7130                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
7131                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
7132                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
7133
7134                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
7135                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
7136                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
7137                                                 false
7138                                         } else { true }
7139                                 });
7140                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
7141                         });
7142
7143                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
7144                         intercepted_htlcs.retain(|_, htlc| {
7145                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
7146                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
7147                                                 short_channel_id: htlc.prev_short_channel_id,
7148                                                 htlc_id: htlc.prev_htlc_id,
7149                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
7150                                                 phantom_shared_secret: None,
7151                                                 outpoint: htlc.prev_funding_outpoint,
7152                                         });
7153
7154                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
7155                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
7156                                                 _ => unreachable!(),
7157                                         };
7158                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
7159                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
7160                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
7161                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
7162                                         false
7163                                 } else { true }
7164                         });
7165                 }
7166
7167                 self.handle_init_event_channel_failures(failed_channels);
7168
7169                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
7170                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
7171                 }
7172         }
7173
7174         /// Gets a [`Future`] that completes when this [`ChannelManager`] needs to be persisted.
7175         ///
7176         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
7177         /// [`ChannelManager`] and should instead register actions to be taken later.
7178         ///
7179         pub fn get_persistable_update_future(&self) -> Future {
7180                 self.persistence_notifier.get_future()
7181         }
7182
7183         #[cfg(any(test, feature = "_test_utils"))]
7184         pub fn get_persistence_condvar_value(&self) -> bool {
7185                 self.persistence_notifier.notify_pending()
7186         }
7187
7188         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
7189         /// [`chain::Confirm`] interfaces.
7190         pub fn current_best_block(&self) -> BestBlock {
7191                 self.best_block.read().unwrap().clone()
7192         }
7193
7194         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
7195         /// [`ChannelManager`].
7196         pub fn node_features(&self) -> NodeFeatures {
7197                 provided_node_features(&self.default_configuration)
7198         }
7199
7200         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
7201         /// [`ChannelManager`].
7202         ///
7203         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
7204         /// or not. Thus, this method is not public.
7205         #[cfg(any(feature = "_test_utils", test))]
7206         pub fn invoice_features(&self) -> Bolt11InvoiceFeatures {
7207                 provided_invoice_features(&self.default_configuration)
7208         }
7209
7210         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
7211         /// [`ChannelManager`].
7212         pub fn channel_features(&self) -> ChannelFeatures {
7213                 provided_channel_features(&self.default_configuration)
7214         }
7215
7216         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
7217         /// [`ChannelManager`].
7218         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
7219                 provided_channel_type_features(&self.default_configuration)
7220         }
7221
7222         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
7223         /// [`ChannelManager`].
7224         pub fn init_features(&self) -> InitFeatures {
7225                 provided_init_features(&self.default_configuration)
7226         }
7227 }
7228
7229 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7230         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
7231 where
7232         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7233         T::Target: BroadcasterInterface,
7234         ES::Target: EntropySource,
7235         NS::Target: NodeSigner,
7236         SP::Target: SignerProvider,
7237         F::Target: FeeEstimator,
7238         R::Target: Router,
7239         L::Target: Logger,
7240 {
7241         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
7242                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7243                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, msg), *counterparty_node_id);
7244         }
7245
7246         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
7247                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7248                         "Dual-funded channels not supported".to_owned(),
7249                          msg.temporary_channel_id.clone())), *counterparty_node_id);
7250         }
7251
7252         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
7253                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7254                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
7255         }
7256
7257         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
7258                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7259                         "Dual-funded channels not supported".to_owned(),
7260                          msg.temporary_channel_id.clone())), *counterparty_node_id);
7261         }
7262
7263         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
7264                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7265                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
7266         }
7267
7268         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
7269                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7270                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
7271         }
7272
7273         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
7274                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7275                 let _ = handle_error!(self, self.internal_channel_ready(counterparty_node_id, msg), *counterparty_node_id);
7276         }
7277
7278         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
7279                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7280                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
7281         }
7282
7283         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
7284                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7285                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
7286         }
7287
7288         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
7289                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7290                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
7291         }
7292
7293         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
7294                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7295                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
7296         }
7297
7298         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
7299                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7300                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
7301         }
7302
7303         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
7304                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7305                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
7306         }
7307
7308         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
7309                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7310                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
7311         }
7312
7313         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
7314                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7315                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
7316         }
7317
7318         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
7319                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7320                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
7321         }
7322
7323         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
7324                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7325                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
7326         }
7327
7328         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
7329                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
7330                         let force_persist = self.process_background_events();
7331                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
7332                                 if force_persist == NotifyOption::DoPersist { NotifyOption::DoPersist } else { persist }
7333                         } else {
7334                                 NotifyOption::SkipPersist
7335                         }
7336                 });
7337         }
7338
7339         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
7340                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7341                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
7342         }
7343
7344         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
7345                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7346                 let mut failed_channels = Vec::new();
7347                 let mut per_peer_state = self.per_peer_state.write().unwrap();
7348                 let remove_peer = {
7349                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
7350                                 log_pubkey!(counterparty_node_id));
7351                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
7352                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7353                                 let peer_state = &mut *peer_state_lock;
7354                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7355                                 peer_state.channel_by_id.retain(|_, chan| {
7356                                         chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
7357                                         if chan.is_shutdown() {
7358                                                 update_maps_on_chan_removal!(self, &chan.context);
7359                                                 self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7360                                                 return false;
7361                                         }
7362                                         true
7363                                 });
7364                                 peer_state.inbound_v1_channel_by_id.retain(|_, chan| {
7365                                         update_maps_on_chan_removal!(self, &chan.context);
7366                                         self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7367                                         false
7368                                 });
7369                                 peer_state.outbound_v1_channel_by_id.retain(|_, chan| {
7370                                         update_maps_on_chan_removal!(self, &chan.context);
7371                                         self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7372                                         false
7373                                 });
7374                                 // Note that we don't bother generating any events for pre-accept channels -
7375                                 // they're not considered "channels" yet from the PoV of our events interface.
7376                                 peer_state.inbound_channel_request_by_id.clear();
7377                                 pending_msg_events.retain(|msg| {
7378                                         match msg {
7379                                                 // V1 Channel Establishment
7380                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
7381                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
7382                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
7383                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
7384                                                 // V2 Channel Establishment
7385                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
7386                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
7387                                                 // Common Channel Establishment
7388                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
7389                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
7390                                                 // Interactive Transaction Construction
7391                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
7392                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
7393                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
7394                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
7395                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
7396                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
7397                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
7398                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
7399                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
7400                                                 // Channel Operations
7401                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
7402                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
7403                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
7404                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
7405                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
7406                                                 &events::MessageSendEvent::HandleError { .. } => false,
7407                                                 // Gossip
7408                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
7409                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
7410                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
7411                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
7412                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
7413                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
7414                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
7415                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
7416                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
7417                                         }
7418                                 });
7419                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
7420                                 peer_state.is_connected = false;
7421                                 peer_state.ok_to_remove(true)
7422                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
7423                 };
7424                 if remove_peer {
7425                         per_peer_state.remove(counterparty_node_id);
7426                 }
7427                 mem::drop(per_peer_state);
7428
7429                 for failure in failed_channels.drain(..) {
7430                         self.finish_force_close_channel(failure);
7431                 }
7432         }
7433
7434         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
7435                 if !init_msg.features.supports_static_remote_key() {
7436                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
7437                         return Err(());
7438                 }
7439
7440                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7441
7442                 // If we have too many peers connected which don't have funded channels, disconnect the
7443                 // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
7444                 // unfunded channels taking up space in memory for disconnected peers, we still let new
7445                 // peers connect, but we'll reject new channels from them.
7446                 let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
7447                 let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
7448
7449                 {
7450                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
7451                         match peer_state_lock.entry(counterparty_node_id.clone()) {
7452                                 hash_map::Entry::Vacant(e) => {
7453                                         if inbound_peer_limited {
7454                                                 return Err(());
7455                                         }
7456                                         e.insert(Mutex::new(PeerState {
7457                                                 channel_by_id: HashMap::new(),
7458                                                 outbound_v1_channel_by_id: HashMap::new(),
7459                                                 inbound_v1_channel_by_id: HashMap::new(),
7460                                                 inbound_channel_request_by_id: HashMap::new(),
7461                                                 latest_features: init_msg.features.clone(),
7462                                                 pending_msg_events: Vec::new(),
7463                                                 in_flight_monitor_updates: BTreeMap::new(),
7464                                                 monitor_update_blocked_actions: BTreeMap::new(),
7465                                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
7466                                                 is_connected: true,
7467                                         }));
7468                                 },
7469                                 hash_map::Entry::Occupied(e) => {
7470                                         let mut peer_state = e.get().lock().unwrap();
7471                                         peer_state.latest_features = init_msg.features.clone();
7472
7473                                         let best_block_height = self.best_block.read().unwrap().height();
7474                                         if inbound_peer_limited &&
7475                                                 Self::unfunded_channel_count(&*peer_state, best_block_height) ==
7476                                                 peer_state.channel_by_id.len()
7477                                         {
7478                                                 return Err(());
7479                                         }
7480
7481                                         debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
7482                                         peer_state.is_connected = true;
7483                                 },
7484                         }
7485                 }
7486
7487                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
7488
7489                 let per_peer_state = self.per_peer_state.read().unwrap();
7490                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
7491                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7492                         let peer_state = &mut *peer_state_lock;
7493                         let pending_msg_events = &mut peer_state.pending_msg_events;
7494
7495                         // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
7496                         // (so won't be recovered after a crash) we don't need to bother closing unfunded channels and
7497                         // clearing their maps here. Instead we can just send queue channel_reestablish messages for
7498                         // channels in the channel_by_id map.
7499                         peer_state.channel_by_id.iter_mut().for_each(|(_, chan)| {
7500                                 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
7501                                         node_id: chan.context.get_counterparty_node_id(),
7502                                         msg: chan.get_channel_reestablish(&self.logger),
7503                                 });
7504                         });
7505                 }
7506                 //TODO: Also re-broadcast announcement_signatures
7507                 Ok(())
7508         }
7509
7510         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
7511                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7512
7513                 if msg.channel_id == [0; 32] {
7514                         let channel_ids: Vec<[u8; 32]> = {
7515                                 let per_peer_state = self.per_peer_state.read().unwrap();
7516                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
7517                                 if peer_state_mutex_opt.is_none() { return; }
7518                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7519                                 let peer_state = &mut *peer_state_lock;
7520                                 // Note that we don't bother generating any events for pre-accept channels -
7521                                 // they're not considered "channels" yet from the PoV of our events interface.
7522                                 peer_state.inbound_channel_request_by_id.clear();
7523                                 peer_state.channel_by_id.keys().cloned()
7524                                         .chain(peer_state.outbound_v1_channel_by_id.keys().cloned())
7525                                         .chain(peer_state.inbound_v1_channel_by_id.keys().cloned()).collect()
7526                         };
7527                         for channel_id in channel_ids {
7528                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
7529                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
7530                         }
7531                 } else {
7532                         {
7533                                 // First check if we can advance the channel type and try again.
7534                                 let per_peer_state = self.per_peer_state.read().unwrap();
7535                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
7536                                 if peer_state_mutex_opt.is_none() { return; }
7537                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7538                                 let peer_state = &mut *peer_state_lock;
7539                                 if let Some(chan) = peer_state.outbound_v1_channel_by_id.get_mut(&msg.channel_id) {
7540                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.genesis_hash, &self.fee_estimator) {
7541                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
7542                                                         node_id: *counterparty_node_id,
7543                                                         msg,
7544                                                 });
7545                                                 return;
7546                                         }
7547                                 }
7548                         }
7549
7550                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
7551                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
7552                 }
7553         }
7554
7555         fn provided_node_features(&self) -> NodeFeatures {
7556                 provided_node_features(&self.default_configuration)
7557         }
7558
7559         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
7560                 provided_init_features(&self.default_configuration)
7561         }
7562
7563         fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
7564                 Some(vec![ChainHash::from(&self.genesis_hash[..])])
7565         }
7566
7567         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
7568                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7569                         "Dual-funded channels not supported".to_owned(),
7570                          msg.channel_id.clone())), *counterparty_node_id);
7571         }
7572
7573         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
7574                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7575                         "Dual-funded channels not supported".to_owned(),
7576                          msg.channel_id.clone())), *counterparty_node_id);
7577         }
7578
7579         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
7580                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7581                         "Dual-funded channels not supported".to_owned(),
7582                          msg.channel_id.clone())), *counterparty_node_id);
7583         }
7584
7585         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
7586                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7587                         "Dual-funded channels not supported".to_owned(),
7588                          msg.channel_id.clone())), *counterparty_node_id);
7589         }
7590
7591         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
7592                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7593                         "Dual-funded channels not supported".to_owned(),
7594                          msg.channel_id.clone())), *counterparty_node_id);
7595         }
7596
7597         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
7598                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7599                         "Dual-funded channels not supported".to_owned(),
7600                          msg.channel_id.clone())), *counterparty_node_id);
7601         }
7602
7603         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
7604                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7605                         "Dual-funded channels not supported".to_owned(),
7606                          msg.channel_id.clone())), *counterparty_node_id);
7607         }
7608
7609         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
7610                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7611                         "Dual-funded channels not supported".to_owned(),
7612                          msg.channel_id.clone())), *counterparty_node_id);
7613         }
7614
7615         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
7616                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7617                         "Dual-funded channels not supported".to_owned(),
7618                          msg.channel_id.clone())), *counterparty_node_id);
7619         }
7620 }
7621
7622 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
7623 /// [`ChannelManager`].
7624 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
7625         let mut node_features = provided_init_features(config).to_context();
7626         node_features.set_keysend_optional();
7627         node_features
7628 }
7629
7630 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
7631 /// [`ChannelManager`].
7632 ///
7633 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
7634 /// or not. Thus, this method is not public.
7635 #[cfg(any(feature = "_test_utils", test))]
7636 pub(crate) fn provided_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
7637         provided_init_features(config).to_context()
7638 }
7639
7640 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
7641 /// [`ChannelManager`].
7642 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
7643         provided_init_features(config).to_context()
7644 }
7645
7646 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
7647 /// [`ChannelManager`].
7648 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
7649         ChannelTypeFeatures::from_init(&provided_init_features(config))
7650 }
7651
7652 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
7653 /// [`ChannelManager`].
7654 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
7655         // Note that if new features are added here which other peers may (eventually) require, we
7656         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
7657         // [`ErroringMessageHandler`].
7658         let mut features = InitFeatures::empty();
7659         features.set_data_loss_protect_required();
7660         features.set_upfront_shutdown_script_optional();
7661         features.set_variable_length_onion_required();
7662         features.set_static_remote_key_required();
7663         features.set_payment_secret_required();
7664         features.set_basic_mpp_optional();
7665         features.set_wumbo_optional();
7666         features.set_shutdown_any_segwit_optional();
7667         features.set_channel_type_optional();
7668         features.set_scid_privacy_optional();
7669         features.set_zero_conf_optional();
7670         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
7671                 features.set_anchors_zero_fee_htlc_tx_optional();
7672         }
7673         features
7674 }
7675
7676 const SERIALIZATION_VERSION: u8 = 1;
7677 const MIN_SERIALIZATION_VERSION: u8 = 1;
7678
7679 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
7680         (2, fee_base_msat, required),
7681         (4, fee_proportional_millionths, required),
7682         (6, cltv_expiry_delta, required),
7683 });
7684
7685 impl_writeable_tlv_based!(ChannelCounterparty, {
7686         (2, node_id, required),
7687         (4, features, required),
7688         (6, unspendable_punishment_reserve, required),
7689         (8, forwarding_info, option),
7690         (9, outbound_htlc_minimum_msat, option),
7691         (11, outbound_htlc_maximum_msat, option),
7692 });
7693
7694 impl Writeable for ChannelDetails {
7695         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7696                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
7697                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
7698                 let user_channel_id_low = self.user_channel_id as u64;
7699                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
7700                 write_tlv_fields!(writer, {
7701                         (1, self.inbound_scid_alias, option),
7702                         (2, self.channel_id, required),
7703                         (3, self.channel_type, option),
7704                         (4, self.counterparty, required),
7705                         (5, self.outbound_scid_alias, option),
7706                         (6, self.funding_txo, option),
7707                         (7, self.config, option),
7708                         (8, self.short_channel_id, option),
7709                         (9, self.confirmations, option),
7710                         (10, self.channel_value_satoshis, required),
7711                         (12, self.unspendable_punishment_reserve, option),
7712                         (14, user_channel_id_low, required),
7713                         (16, self.next_outbound_htlc_limit_msat, required),  // Forwards compatibility for removed balance_msat field.
7714                         (18, self.outbound_capacity_msat, required),
7715                         (19, self.next_outbound_htlc_limit_msat, required),
7716                         (20, self.inbound_capacity_msat, required),
7717                         (21, self.next_outbound_htlc_minimum_msat, required),
7718                         (22, self.confirmations_required, option),
7719                         (24, self.force_close_spend_delay, option),
7720                         (26, self.is_outbound, required),
7721                         (28, self.is_channel_ready, required),
7722                         (30, self.is_usable, required),
7723                         (32, self.is_public, required),
7724                         (33, self.inbound_htlc_minimum_msat, option),
7725                         (35, self.inbound_htlc_maximum_msat, option),
7726                         (37, user_channel_id_high_opt, option),
7727                         (39, self.feerate_sat_per_1000_weight, option),
7728                         (41, self.channel_shutdown_state, option),
7729                 });
7730                 Ok(())
7731         }
7732 }
7733
7734 impl Readable for ChannelDetails {
7735         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7736                 _init_and_read_tlv_fields!(reader, {
7737                         (1, inbound_scid_alias, option),
7738                         (2, channel_id, required),
7739                         (3, channel_type, option),
7740                         (4, counterparty, required),
7741                         (5, outbound_scid_alias, option),
7742                         (6, funding_txo, option),
7743                         (7, config, option),
7744                         (8, short_channel_id, option),
7745                         (9, confirmations, option),
7746                         (10, channel_value_satoshis, required),
7747                         (12, unspendable_punishment_reserve, option),
7748                         (14, user_channel_id_low, required),
7749                         (16, _balance_msat, option),  // Backwards compatibility for removed balance_msat field.
7750                         (18, outbound_capacity_msat, required),
7751                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
7752                         // filled in, so we can safely unwrap it here.
7753                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
7754                         (20, inbound_capacity_msat, required),
7755                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
7756                         (22, confirmations_required, option),
7757                         (24, force_close_spend_delay, option),
7758                         (26, is_outbound, required),
7759                         (28, is_channel_ready, required),
7760                         (30, is_usable, required),
7761                         (32, is_public, required),
7762                         (33, inbound_htlc_minimum_msat, option),
7763                         (35, inbound_htlc_maximum_msat, option),
7764                         (37, user_channel_id_high_opt, option),
7765                         (39, feerate_sat_per_1000_weight, option),
7766                         (41, channel_shutdown_state, option),
7767                 });
7768
7769                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
7770                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
7771                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
7772                 let user_channel_id = user_channel_id_low as u128 +
7773                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
7774
7775                 let _balance_msat: Option<u64> = _balance_msat;
7776
7777                 Ok(Self {
7778                         inbound_scid_alias,
7779                         channel_id: channel_id.0.unwrap(),
7780                         channel_type,
7781                         counterparty: counterparty.0.unwrap(),
7782                         outbound_scid_alias,
7783                         funding_txo,
7784                         config,
7785                         short_channel_id,
7786                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
7787                         unspendable_punishment_reserve,
7788                         user_channel_id,
7789                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
7790                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
7791                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
7792                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
7793                         confirmations_required,
7794                         confirmations,
7795                         force_close_spend_delay,
7796                         is_outbound: is_outbound.0.unwrap(),
7797                         is_channel_ready: is_channel_ready.0.unwrap(),
7798                         is_usable: is_usable.0.unwrap(),
7799                         is_public: is_public.0.unwrap(),
7800                         inbound_htlc_minimum_msat,
7801                         inbound_htlc_maximum_msat,
7802                         feerate_sat_per_1000_weight,
7803                         channel_shutdown_state,
7804                 })
7805         }
7806 }
7807
7808 impl_writeable_tlv_based!(PhantomRouteHints, {
7809         (2, channels, required_vec),
7810         (4, phantom_scid, required),
7811         (6, real_node_pubkey, required),
7812 });
7813
7814 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
7815         (0, Forward) => {
7816                 (0, onion_packet, required),
7817                 (2, short_channel_id, required),
7818         },
7819         (1, Receive) => {
7820                 (0, payment_data, required),
7821                 (1, phantom_shared_secret, option),
7822                 (2, incoming_cltv_expiry, required),
7823                 (3, payment_metadata, option),
7824                 (5, custom_tlvs, optional_vec),
7825         },
7826         (2, ReceiveKeysend) => {
7827                 (0, payment_preimage, required),
7828                 (2, incoming_cltv_expiry, required),
7829                 (3, payment_metadata, option),
7830                 (4, payment_data, option), // Added in 0.0.116
7831                 (5, custom_tlvs, optional_vec),
7832         },
7833 ;);
7834
7835 impl_writeable_tlv_based!(PendingHTLCInfo, {
7836         (0, routing, required),
7837         (2, incoming_shared_secret, required),
7838         (4, payment_hash, required),
7839         (6, outgoing_amt_msat, required),
7840         (8, outgoing_cltv_value, required),
7841         (9, incoming_amt_msat, option),
7842         (10, skimmed_fee_msat, option),
7843 });
7844
7845
7846 impl Writeable for HTLCFailureMsg {
7847         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7848                 match self {
7849                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
7850                                 0u8.write(writer)?;
7851                                 channel_id.write(writer)?;
7852                                 htlc_id.write(writer)?;
7853                                 reason.write(writer)?;
7854                         },
7855                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7856                                 channel_id, htlc_id, sha256_of_onion, failure_code
7857                         }) => {
7858                                 1u8.write(writer)?;
7859                                 channel_id.write(writer)?;
7860                                 htlc_id.write(writer)?;
7861                                 sha256_of_onion.write(writer)?;
7862                                 failure_code.write(writer)?;
7863                         },
7864                 }
7865                 Ok(())
7866         }
7867 }
7868
7869 impl Readable for HTLCFailureMsg {
7870         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7871                 let id: u8 = Readable::read(reader)?;
7872                 match id {
7873                         0 => {
7874                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
7875                                         channel_id: Readable::read(reader)?,
7876                                         htlc_id: Readable::read(reader)?,
7877                                         reason: Readable::read(reader)?,
7878                                 }))
7879                         },
7880                         1 => {
7881                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7882                                         channel_id: Readable::read(reader)?,
7883                                         htlc_id: Readable::read(reader)?,
7884                                         sha256_of_onion: Readable::read(reader)?,
7885                                         failure_code: Readable::read(reader)?,
7886                                 }))
7887                         },
7888                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
7889                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
7890                         // messages contained in the variants.
7891                         // In version 0.0.101, support for reading the variants with these types was added, and
7892                         // we should migrate to writing these variants when UpdateFailHTLC or
7893                         // UpdateFailMalformedHTLC get TLV fields.
7894                         2 => {
7895                                 let length: BigSize = Readable::read(reader)?;
7896                                 let mut s = FixedLengthReader::new(reader, length.0);
7897                                 let res = Readable::read(&mut s)?;
7898                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
7899                                 Ok(HTLCFailureMsg::Relay(res))
7900                         },
7901                         3 => {
7902                                 let length: BigSize = Readable::read(reader)?;
7903                                 let mut s = FixedLengthReader::new(reader, length.0);
7904                                 let res = Readable::read(&mut s)?;
7905                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
7906                                 Ok(HTLCFailureMsg::Malformed(res))
7907                         },
7908                         _ => Err(DecodeError::UnknownRequiredFeature),
7909                 }
7910         }
7911 }
7912
7913 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
7914         (0, Forward),
7915         (1, Fail),
7916 );
7917
7918 impl_writeable_tlv_based!(HTLCPreviousHopData, {
7919         (0, short_channel_id, required),
7920         (1, phantom_shared_secret, option),
7921         (2, outpoint, required),
7922         (4, htlc_id, required),
7923         (6, incoming_packet_shared_secret, required)
7924 });
7925
7926 impl Writeable for ClaimableHTLC {
7927         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7928                 let (payment_data, keysend_preimage) = match &self.onion_payload {
7929                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
7930                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
7931                 };
7932                 write_tlv_fields!(writer, {
7933                         (0, self.prev_hop, required),
7934                         (1, self.total_msat, required),
7935                         (2, self.value, required),
7936                         (3, self.sender_intended_value, required),
7937                         (4, payment_data, option),
7938                         (5, self.total_value_received, option),
7939                         (6, self.cltv_expiry, required),
7940                         (8, keysend_preimage, option),
7941                         (10, self.counterparty_skimmed_fee_msat, option),
7942                 });
7943                 Ok(())
7944         }
7945 }
7946
7947 impl Readable for ClaimableHTLC {
7948         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7949                 _init_and_read_tlv_fields!(reader, {
7950                         (0, prev_hop, required),
7951                         (1, total_msat, option),
7952                         (2, value_ser, required),
7953                         (3, sender_intended_value, option),
7954                         (4, payment_data_opt, option),
7955                         (5, total_value_received, option),
7956                         (6, cltv_expiry, required),
7957                         (8, keysend_preimage, option),
7958                         (10, counterparty_skimmed_fee_msat, option),
7959                 });
7960                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
7961                 let value = value_ser.0.unwrap();
7962                 let onion_payload = match keysend_preimage {
7963                         Some(p) => {
7964                                 if payment_data.is_some() {
7965                                         return Err(DecodeError::InvalidValue)
7966                                 }
7967                                 if total_msat.is_none() {
7968                                         total_msat = Some(value);
7969                                 }
7970                                 OnionPayload::Spontaneous(p)
7971                         },
7972                         None => {
7973                                 if total_msat.is_none() {
7974                                         if payment_data.is_none() {
7975                                                 return Err(DecodeError::InvalidValue)
7976                                         }
7977                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
7978                                 }
7979                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
7980                         },
7981                 };
7982                 Ok(Self {
7983                         prev_hop: prev_hop.0.unwrap(),
7984                         timer_ticks: 0,
7985                         value,
7986                         sender_intended_value: sender_intended_value.unwrap_or(value),
7987                         total_value_received,
7988                         total_msat: total_msat.unwrap(),
7989                         onion_payload,
7990                         cltv_expiry: cltv_expiry.0.unwrap(),
7991                         counterparty_skimmed_fee_msat,
7992                 })
7993         }
7994 }
7995
7996 impl Readable for HTLCSource {
7997         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7998                 let id: u8 = Readable::read(reader)?;
7999                 match id {
8000                         0 => {
8001                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
8002                                 let mut first_hop_htlc_msat: u64 = 0;
8003                                 let mut path_hops = Vec::new();
8004                                 let mut payment_id = None;
8005                                 let mut payment_params: Option<PaymentParameters> = None;
8006                                 let mut blinded_tail: Option<BlindedTail> = None;
8007                                 read_tlv_fields!(reader, {
8008                                         (0, session_priv, required),
8009                                         (1, payment_id, option),
8010                                         (2, first_hop_htlc_msat, required),
8011                                         (4, path_hops, required_vec),
8012                                         (5, payment_params, (option: ReadableArgs, 0)),
8013                                         (6, blinded_tail, option),
8014                                 });
8015                                 if payment_id.is_none() {
8016                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
8017                                         // instead.
8018                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
8019                                 }
8020                                 let path = Path { hops: path_hops, blinded_tail };
8021                                 if path.hops.len() == 0 {
8022                                         return Err(DecodeError::InvalidValue);
8023                                 }
8024                                 if let Some(params) = payment_params.as_mut() {
8025                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
8026                                                 if final_cltv_expiry_delta == &0 {
8027                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
8028                                                 }
8029                                         }
8030                                 }
8031                                 Ok(HTLCSource::OutboundRoute {
8032                                         session_priv: session_priv.0.unwrap(),
8033                                         first_hop_htlc_msat,
8034                                         path,
8035                                         payment_id: payment_id.unwrap(),
8036                                 })
8037                         }
8038                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
8039                         _ => Err(DecodeError::UnknownRequiredFeature),
8040                 }
8041         }
8042 }
8043
8044 impl Writeable for HTLCSource {
8045         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
8046                 match self {
8047                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
8048                                 0u8.write(writer)?;
8049                                 let payment_id_opt = Some(payment_id);
8050                                 write_tlv_fields!(writer, {
8051                                         (0, session_priv, required),
8052                                         (1, payment_id_opt, option),
8053                                         (2, first_hop_htlc_msat, required),
8054                                         // 3 was previously used to write a PaymentSecret for the payment.
8055                                         (4, path.hops, required_vec),
8056                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
8057                                         (6, path.blinded_tail, option),
8058                                  });
8059                         }
8060                         HTLCSource::PreviousHopData(ref field) => {
8061                                 1u8.write(writer)?;
8062                                 field.write(writer)?;
8063                         }
8064                 }
8065                 Ok(())
8066         }
8067 }
8068
8069 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
8070         (0, forward_info, required),
8071         (1, prev_user_channel_id, (default_value, 0)),
8072         (2, prev_short_channel_id, required),
8073         (4, prev_htlc_id, required),
8074         (6, prev_funding_outpoint, required),
8075 });
8076
8077 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
8078         (1, FailHTLC) => {
8079                 (0, htlc_id, required),
8080                 (2, err_packet, required),
8081         };
8082         (0, AddHTLC)
8083 );
8084
8085 impl_writeable_tlv_based!(PendingInboundPayment, {
8086         (0, payment_secret, required),
8087         (2, expiry_time, required),
8088         (4, user_payment_id, required),
8089         (6, payment_preimage, required),
8090         (8, min_value_msat, required),
8091 });
8092
8093 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>
8094 where
8095         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8096         T::Target: BroadcasterInterface,
8097         ES::Target: EntropySource,
8098         NS::Target: NodeSigner,
8099         SP::Target: SignerProvider,
8100         F::Target: FeeEstimator,
8101         R::Target: Router,
8102         L::Target: Logger,
8103 {
8104         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8105                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
8106
8107                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
8108
8109                 self.genesis_hash.write(writer)?;
8110                 {
8111                         let best_block = self.best_block.read().unwrap();
8112                         best_block.height().write(writer)?;
8113                         best_block.block_hash().write(writer)?;
8114                 }
8115
8116                 let mut serializable_peer_count: u64 = 0;
8117                 {
8118                         let per_peer_state = self.per_peer_state.read().unwrap();
8119                         let mut unfunded_channels = 0;
8120                         let mut number_of_channels = 0;
8121                         for (_, peer_state_mutex) in per_peer_state.iter() {
8122                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8123                                 let peer_state = &mut *peer_state_lock;
8124                                 if !peer_state.ok_to_remove(false) {
8125                                         serializable_peer_count += 1;
8126                                 }
8127                                 number_of_channels += peer_state.channel_by_id.len();
8128                                 for (_, channel) in peer_state.channel_by_id.iter() {
8129                                         if !channel.context.is_funding_initiated() {
8130                                                 unfunded_channels += 1;
8131                                         }
8132                                 }
8133                         }
8134
8135                         ((number_of_channels - unfunded_channels) as u64).write(writer)?;
8136
8137                         for (_, peer_state_mutex) in per_peer_state.iter() {
8138                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8139                                 let peer_state = &mut *peer_state_lock;
8140                                 for (_, channel) in peer_state.channel_by_id.iter() {
8141                                         if channel.context.is_funding_initiated() {
8142                                                 channel.write(writer)?;
8143                                         }
8144                                 }
8145                         }
8146                 }
8147
8148                 {
8149                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
8150                         (forward_htlcs.len() as u64).write(writer)?;
8151                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
8152                                 short_channel_id.write(writer)?;
8153                                 (pending_forwards.len() as u64).write(writer)?;
8154                                 for forward in pending_forwards {
8155                                         forward.write(writer)?;
8156                                 }
8157                         }
8158                 }
8159
8160                 let per_peer_state = self.per_peer_state.write().unwrap();
8161
8162                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
8163                 let claimable_payments = self.claimable_payments.lock().unwrap();
8164                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
8165
8166                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
8167                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
8168                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
8169                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
8170                         payment_hash.write(writer)?;
8171                         (payment.htlcs.len() as u64).write(writer)?;
8172                         for htlc in payment.htlcs.iter() {
8173                                 htlc.write(writer)?;
8174                         }
8175                         htlc_purposes.push(&payment.purpose);
8176                         htlc_onion_fields.push(&payment.onion_fields);
8177                 }
8178
8179                 let mut monitor_update_blocked_actions_per_peer = None;
8180                 let mut peer_states = Vec::new();
8181                 for (_, peer_state_mutex) in per_peer_state.iter() {
8182                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
8183                         // of a lockorder violation deadlock - no other thread can be holding any
8184                         // per_peer_state lock at all.
8185                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
8186                 }
8187
8188                 (serializable_peer_count).write(writer)?;
8189                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
8190                         // Peers which we have no channels to should be dropped once disconnected. As we
8191                         // disconnect all peers when shutting down and serializing the ChannelManager, we
8192                         // consider all peers as disconnected here. There's therefore no need write peers with
8193                         // no channels.
8194                         if !peer_state.ok_to_remove(false) {
8195                                 peer_pubkey.write(writer)?;
8196                                 peer_state.latest_features.write(writer)?;
8197                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
8198                                         monitor_update_blocked_actions_per_peer
8199                                                 .get_or_insert_with(Vec::new)
8200                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
8201                                 }
8202                         }
8203                 }
8204
8205                 let events = self.pending_events.lock().unwrap();
8206                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
8207                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
8208                 // refuse to read the new ChannelManager.
8209                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
8210                 if events_not_backwards_compatible {
8211                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
8212                         // well save the space and not write any events here.
8213                         0u64.write(writer)?;
8214                 } else {
8215                         (events.len() as u64).write(writer)?;
8216                         for (event, _) in events.iter() {
8217                                 event.write(writer)?;
8218                         }
8219                 }
8220
8221                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
8222                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
8223                 // the closing monitor updates were always effectively replayed on startup (either directly
8224                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
8225                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
8226                 0u64.write(writer)?;
8227
8228                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
8229                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
8230                 // likely to be identical.
8231                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
8232                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
8233
8234                 (pending_inbound_payments.len() as u64).write(writer)?;
8235                 for (hash, pending_payment) in pending_inbound_payments.iter() {
8236                         hash.write(writer)?;
8237                         pending_payment.write(writer)?;
8238                 }
8239
8240                 // For backwards compat, write the session privs and their total length.
8241                 let mut num_pending_outbounds_compat: u64 = 0;
8242                 for (_, outbound) in pending_outbound_payments.iter() {
8243                         if !outbound.is_fulfilled() && !outbound.abandoned() {
8244                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
8245                         }
8246                 }
8247                 num_pending_outbounds_compat.write(writer)?;
8248                 for (_, outbound) in pending_outbound_payments.iter() {
8249                         match outbound {
8250                                 PendingOutboundPayment::Legacy { session_privs } |
8251                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
8252                                         for session_priv in session_privs.iter() {
8253                                                 session_priv.write(writer)?;
8254                                         }
8255                                 }
8256                                 PendingOutboundPayment::Fulfilled { .. } => {},
8257                                 PendingOutboundPayment::Abandoned { .. } => {},
8258                         }
8259                 }
8260
8261                 // Encode without retry info for 0.0.101 compatibility.
8262                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
8263                 for (id, outbound) in pending_outbound_payments.iter() {
8264                         match outbound {
8265                                 PendingOutboundPayment::Legacy { session_privs } |
8266                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
8267                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
8268                                 },
8269                                 _ => {},
8270                         }
8271                 }
8272
8273                 let mut pending_intercepted_htlcs = None;
8274                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
8275                 if our_pending_intercepts.len() != 0 {
8276                         pending_intercepted_htlcs = Some(our_pending_intercepts);
8277                 }
8278
8279                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
8280                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
8281                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
8282                         // map. Thus, if there are no entries we skip writing a TLV for it.
8283                         pending_claiming_payments = None;
8284                 }
8285
8286                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
8287                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
8288                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
8289                                 if !updates.is_empty() {
8290                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
8291                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
8292                                 }
8293                         }
8294                 }
8295
8296                 write_tlv_fields!(writer, {
8297                         (1, pending_outbound_payments_no_retry, required),
8298                         (2, pending_intercepted_htlcs, option),
8299                         (3, pending_outbound_payments, required),
8300                         (4, pending_claiming_payments, option),
8301                         (5, self.our_network_pubkey, required),
8302                         (6, monitor_update_blocked_actions_per_peer, option),
8303                         (7, self.fake_scid_rand_bytes, required),
8304                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
8305                         (9, htlc_purposes, required_vec),
8306                         (10, in_flight_monitor_updates, option),
8307                         (11, self.probing_cookie_secret, required),
8308                         (13, htlc_onion_fields, optional_vec),
8309                 });
8310
8311                 Ok(())
8312         }
8313 }
8314
8315 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
8316         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
8317                 (self.len() as u64).write(w)?;
8318                 for (event, action) in self.iter() {
8319                         event.write(w)?;
8320                         action.write(w)?;
8321                         #[cfg(debug_assertions)] {
8322                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
8323                                 // be persisted and are regenerated on restart. However, if such an event has a
8324                                 // post-event-handling action we'll write nothing for the event and would have to
8325                                 // either forget the action or fail on deserialization (which we do below). Thus,
8326                                 // check that the event is sane here.
8327                                 let event_encoded = event.encode();
8328                                 let event_read: Option<Event> =
8329                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
8330                                 if action.is_some() { assert!(event_read.is_some()); }
8331                         }
8332                 }
8333                 Ok(())
8334         }
8335 }
8336 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
8337         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8338                 let len: u64 = Readable::read(reader)?;
8339                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
8340                 let mut events: Self = VecDeque::with_capacity(cmp::min(
8341                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
8342                         len) as usize);
8343                 for _ in 0..len {
8344                         let ev_opt = MaybeReadable::read(reader)?;
8345                         let action = Readable::read(reader)?;
8346                         if let Some(ev) = ev_opt {
8347                                 events.push_back((ev, action));
8348                         } else if action.is_some() {
8349                                 return Err(DecodeError::InvalidValue);
8350                         }
8351                 }
8352                 Ok(events)
8353         }
8354 }
8355
8356 impl_writeable_tlv_based_enum!(ChannelShutdownState,
8357         (0, NotShuttingDown) => {},
8358         (2, ShutdownInitiated) => {},
8359         (4, ResolvingHTLCs) => {},
8360         (6, NegotiatingClosingFee) => {},
8361         (8, ShutdownComplete) => {}, ;
8362 );
8363
8364 /// Arguments for the creation of a ChannelManager that are not deserialized.
8365 ///
8366 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
8367 /// is:
8368 /// 1) Deserialize all stored [`ChannelMonitor`]s.
8369 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
8370 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
8371 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
8372 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
8373 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
8374 ///    same way you would handle a [`chain::Filter`] call using
8375 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
8376 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
8377 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
8378 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
8379 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
8380 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
8381 ///    the next step.
8382 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
8383 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
8384 ///
8385 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
8386 /// call any other methods on the newly-deserialized [`ChannelManager`].
8387 ///
8388 /// Note that because some channels may be closed during deserialization, it is critical that you
8389 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
8390 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
8391 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
8392 /// not force-close the same channels but consider them live), you may end up revoking a state for
8393 /// which you've already broadcasted the transaction.
8394 ///
8395 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
8396 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8397 where
8398         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8399         T::Target: BroadcasterInterface,
8400         ES::Target: EntropySource,
8401         NS::Target: NodeSigner,
8402         SP::Target: SignerProvider,
8403         F::Target: FeeEstimator,
8404         R::Target: Router,
8405         L::Target: Logger,
8406 {
8407         /// A cryptographically secure source of entropy.
8408         pub entropy_source: ES,
8409
8410         /// A signer that is able to perform node-scoped cryptographic operations.
8411         pub node_signer: NS,
8412
8413         /// The keys provider which will give us relevant keys. Some keys will be loaded during
8414         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
8415         /// signing data.
8416         pub signer_provider: SP,
8417
8418         /// The fee_estimator for use in the ChannelManager in the future.
8419         ///
8420         /// No calls to the FeeEstimator will be made during deserialization.
8421         pub fee_estimator: F,
8422         /// The chain::Watch for use in the ChannelManager in the future.
8423         ///
8424         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
8425         /// you have deserialized ChannelMonitors separately and will add them to your
8426         /// chain::Watch after deserializing this ChannelManager.
8427         pub chain_monitor: M,
8428
8429         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
8430         /// used to broadcast the latest local commitment transactions of channels which must be
8431         /// force-closed during deserialization.
8432         pub tx_broadcaster: T,
8433         /// The router which will be used in the ChannelManager in the future for finding routes
8434         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
8435         ///
8436         /// No calls to the router will be made during deserialization.
8437         pub router: R,
8438         /// The Logger for use in the ChannelManager and which may be used to log information during
8439         /// deserialization.
8440         pub logger: L,
8441         /// Default settings used for new channels. Any existing channels will continue to use the
8442         /// runtime settings which were stored when the ChannelManager was serialized.
8443         pub default_config: UserConfig,
8444
8445         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
8446         /// value.context.get_funding_txo() should be the key).
8447         ///
8448         /// If a monitor is inconsistent with the channel state during deserialization the channel will
8449         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
8450         /// is true for missing channels as well. If there is a monitor missing for which we find
8451         /// channel data Err(DecodeError::InvalidValue) will be returned.
8452         ///
8453         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
8454         /// this struct.
8455         ///
8456         /// This is not exported to bindings users because we have no HashMap bindings
8457         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
8458 }
8459
8460 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8461                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
8462 where
8463         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8464         T::Target: BroadcasterInterface,
8465         ES::Target: EntropySource,
8466         NS::Target: NodeSigner,
8467         SP::Target: SignerProvider,
8468         F::Target: FeeEstimator,
8469         R::Target: Router,
8470         L::Target: Logger,
8471 {
8472         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
8473         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
8474         /// populate a HashMap directly from C.
8475         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,
8476                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
8477                 Self {
8478                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
8479                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
8480                 }
8481         }
8482 }
8483
8484 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
8485 // SipmleArcChannelManager type:
8486 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8487         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
8488 where
8489         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8490         T::Target: BroadcasterInterface,
8491         ES::Target: EntropySource,
8492         NS::Target: NodeSigner,
8493         SP::Target: SignerProvider,
8494         F::Target: FeeEstimator,
8495         R::Target: Router,
8496         L::Target: Logger,
8497 {
8498         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
8499                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
8500                 Ok((blockhash, Arc::new(chan_manager)))
8501         }
8502 }
8503
8504 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8505         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
8506 where
8507         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8508         T::Target: BroadcasterInterface,
8509         ES::Target: EntropySource,
8510         NS::Target: NodeSigner,
8511         SP::Target: SignerProvider,
8512         F::Target: FeeEstimator,
8513         R::Target: Router,
8514         L::Target: Logger,
8515 {
8516         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
8517                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
8518
8519                 let genesis_hash: BlockHash = Readable::read(reader)?;
8520                 let best_block_height: u32 = Readable::read(reader)?;
8521                 let best_block_hash: BlockHash = Readable::read(reader)?;
8522
8523                 let mut failed_htlcs = Vec::new();
8524
8525                 let channel_count: u64 = Readable::read(reader)?;
8526                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
8527                 let mut peer_channels: HashMap<PublicKey, HashMap<[u8; 32], Channel<<SP::Target as SignerProvider>::Signer>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
8528                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
8529                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
8530                 let mut channel_closures = VecDeque::new();
8531                 let mut close_background_events = Vec::new();
8532                 for _ in 0..channel_count {
8533                         let mut channel: Channel<<SP::Target as SignerProvider>::Signer> = Channel::read(reader, (
8534                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
8535                         ))?;
8536                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
8537                         funding_txo_set.insert(funding_txo.clone());
8538                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
8539                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
8540                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
8541                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
8542                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
8543                                         // But if the channel is behind of the monitor, close the channel:
8544                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
8545                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
8546                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
8547                                                 log_bytes!(channel.context.channel_id()), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
8548                                         let (monitor_update, mut new_failed_htlcs) = channel.context.force_shutdown(true);
8549                                         if let Some((counterparty_node_id, funding_txo, update)) = monitor_update {
8550                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
8551                                                         counterparty_node_id, funding_txo, update
8552                                                 });
8553                                         }
8554                                         failed_htlcs.append(&mut new_failed_htlcs);
8555                                         channel_closures.push_back((events::Event::ChannelClosed {
8556                                                 channel_id: channel.context.channel_id(),
8557                                                 user_channel_id: channel.context.get_user_id(),
8558                                                 reason: ClosureReason::OutdatedChannelManager,
8559                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
8560                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
8561                                         }, None));
8562                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
8563                                                 let mut found_htlc = false;
8564                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
8565                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
8566                                                 }
8567                                                 if !found_htlc {
8568                                                         // If we have some HTLCs in the channel which are not present in the newer
8569                                                         // ChannelMonitor, they have been removed and should be failed back to
8570                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
8571                                                         // were actually claimed we'd have generated and ensured the previous-hop
8572                                                         // claim update ChannelMonitor updates were persisted prior to persising
8573                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
8574                                                         // backwards leg of the HTLC will simply be rejected.
8575                                                         log_info!(args.logger,
8576                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
8577                                                                 log_bytes!(channel.context.channel_id()), log_bytes!(payment_hash.0));
8578                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8579                                                 }
8580                                         }
8581                                 } else {
8582                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
8583                                                 log_bytes!(channel.context.channel_id()), channel.context.get_latest_monitor_update_id(),
8584                                                 monitor.get_latest_update_id());
8585                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
8586                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8587                                         }
8588                                         if channel.context.is_funding_initiated() {
8589                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
8590                                         }
8591                                         match peer_channels.entry(channel.context.get_counterparty_node_id()) {
8592                                                 hash_map::Entry::Occupied(mut entry) => {
8593                                                         let by_id_map = entry.get_mut();
8594                                                         by_id_map.insert(channel.context.channel_id(), channel);
8595                                                 },
8596                                                 hash_map::Entry::Vacant(entry) => {
8597                                                         let mut by_id_map = HashMap::new();
8598                                                         by_id_map.insert(channel.context.channel_id(), channel);
8599                                                         entry.insert(by_id_map);
8600                                                 }
8601                                         }
8602                                 }
8603                         } else if channel.is_awaiting_initial_mon_persist() {
8604                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
8605                                 // was in-progress, we never broadcasted the funding transaction and can still
8606                                 // safely discard the channel.
8607                                 let _ = channel.context.force_shutdown(false);
8608                                 channel_closures.push_back((events::Event::ChannelClosed {
8609                                         channel_id: channel.context.channel_id(),
8610                                         user_channel_id: channel.context.get_user_id(),
8611                                         reason: ClosureReason::DisconnectedPeer,
8612                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
8613                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
8614                                 }, None));
8615                         } else {
8616                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", log_bytes!(channel.context.channel_id()));
8617                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8618                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8619                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
8620                                 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");
8621                                 return Err(DecodeError::InvalidValue);
8622                         }
8623                 }
8624
8625                 for (funding_txo, _) in args.channel_monitors.iter() {
8626                         if !funding_txo_set.contains(funding_txo) {
8627                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
8628                                         log_bytes!(funding_txo.to_channel_id()));
8629                                 let monitor_update = ChannelMonitorUpdate {
8630                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
8631                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
8632                                 };
8633                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
8634                         }
8635                 }
8636
8637                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
8638                 let forward_htlcs_count: u64 = Readable::read(reader)?;
8639                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
8640                 for _ in 0..forward_htlcs_count {
8641                         let short_channel_id = Readable::read(reader)?;
8642                         let pending_forwards_count: u64 = Readable::read(reader)?;
8643                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
8644                         for _ in 0..pending_forwards_count {
8645                                 pending_forwards.push(Readable::read(reader)?);
8646                         }
8647                         forward_htlcs.insert(short_channel_id, pending_forwards);
8648                 }
8649
8650                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
8651                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
8652                 for _ in 0..claimable_htlcs_count {
8653                         let payment_hash = Readable::read(reader)?;
8654                         let previous_hops_len: u64 = Readable::read(reader)?;
8655                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
8656                         for _ in 0..previous_hops_len {
8657                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
8658                         }
8659                         claimable_htlcs_list.push((payment_hash, previous_hops));
8660                 }
8661
8662                 let peer_state_from_chans = |channel_by_id| {
8663                         PeerState {
8664                                 channel_by_id,
8665                                 outbound_v1_channel_by_id: HashMap::new(),
8666                                 inbound_v1_channel_by_id: HashMap::new(),
8667                                 inbound_channel_request_by_id: HashMap::new(),
8668                                 latest_features: InitFeatures::empty(),
8669                                 pending_msg_events: Vec::new(),
8670                                 in_flight_monitor_updates: BTreeMap::new(),
8671                                 monitor_update_blocked_actions: BTreeMap::new(),
8672                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
8673                                 is_connected: false,
8674                         }
8675                 };
8676
8677                 let peer_count: u64 = Readable::read(reader)?;
8678                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>)>()));
8679                 for _ in 0..peer_count {
8680                         let peer_pubkey = Readable::read(reader)?;
8681                         let peer_chans = peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
8682                         let mut peer_state = peer_state_from_chans(peer_chans);
8683                         peer_state.latest_features = Readable::read(reader)?;
8684                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
8685                 }
8686
8687                 let event_count: u64 = Readable::read(reader)?;
8688                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
8689                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
8690                 for _ in 0..event_count {
8691                         match MaybeReadable::read(reader)? {
8692                                 Some(event) => pending_events_read.push_back((event, None)),
8693                                 None => continue,
8694                         }
8695                 }
8696
8697                 let background_event_count: u64 = Readable::read(reader)?;
8698                 for _ in 0..background_event_count {
8699                         match <u8 as Readable>::read(reader)? {
8700                                 0 => {
8701                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
8702                                         // however we really don't (and never did) need them - we regenerate all
8703                                         // on-startup monitor updates.
8704                                         let _: OutPoint = Readable::read(reader)?;
8705                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
8706                                 }
8707                                 _ => return Err(DecodeError::InvalidValue),
8708                         }
8709                 }
8710
8711                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
8712                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
8713
8714                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
8715                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
8716                 for _ in 0..pending_inbound_payment_count {
8717                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
8718                                 return Err(DecodeError::InvalidValue);
8719                         }
8720                 }
8721
8722                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
8723                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
8724                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
8725                 for _ in 0..pending_outbound_payments_count_compat {
8726                         let session_priv = Readable::read(reader)?;
8727                         let payment = PendingOutboundPayment::Legacy {
8728                                 session_privs: [session_priv].iter().cloned().collect()
8729                         };
8730                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
8731                                 return Err(DecodeError::InvalidValue)
8732                         };
8733                 }
8734
8735                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
8736                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
8737                 let mut pending_outbound_payments = None;
8738                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
8739                 let mut received_network_pubkey: Option<PublicKey> = None;
8740                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
8741                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
8742                 let mut claimable_htlc_purposes = None;
8743                 let mut claimable_htlc_onion_fields = None;
8744                 let mut pending_claiming_payments = Some(HashMap::new());
8745                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
8746                 let mut events_override = None;
8747                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
8748                 read_tlv_fields!(reader, {
8749                         (1, pending_outbound_payments_no_retry, option),
8750                         (2, pending_intercepted_htlcs, option),
8751                         (3, pending_outbound_payments, option),
8752                         (4, pending_claiming_payments, option),
8753                         (5, received_network_pubkey, option),
8754                         (6, monitor_update_blocked_actions_per_peer, option),
8755                         (7, fake_scid_rand_bytes, option),
8756                         (8, events_override, option),
8757                         (9, claimable_htlc_purposes, optional_vec),
8758                         (10, in_flight_monitor_updates, option),
8759                         (11, probing_cookie_secret, option),
8760                         (13, claimable_htlc_onion_fields, optional_vec),
8761                 });
8762                 if fake_scid_rand_bytes.is_none() {
8763                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
8764                 }
8765
8766                 if probing_cookie_secret.is_none() {
8767                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
8768                 }
8769
8770                 if let Some(events) = events_override {
8771                         pending_events_read = events;
8772                 }
8773
8774                 if !channel_closures.is_empty() {
8775                         pending_events_read.append(&mut channel_closures);
8776                 }
8777
8778                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
8779                         pending_outbound_payments = Some(pending_outbound_payments_compat);
8780                 } else if pending_outbound_payments.is_none() {
8781                         let mut outbounds = HashMap::new();
8782                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
8783                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
8784                         }
8785                         pending_outbound_payments = Some(outbounds);
8786                 }
8787                 let pending_outbounds = OutboundPayments {
8788                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
8789                         retry_lock: Mutex::new(())
8790                 };
8791
8792                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
8793                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
8794                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
8795                 // replayed, and for each monitor update we have to replay we have to ensure there's a
8796                 // `ChannelMonitor` for it.
8797                 //
8798                 // In order to do so we first walk all of our live channels (so that we can check their
8799                 // state immediately after doing the update replays, when we have the `update_id`s
8800                 // available) and then walk any remaining in-flight updates.
8801                 //
8802                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
8803                 let mut pending_background_events = Vec::new();
8804                 macro_rules! handle_in_flight_updates {
8805                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
8806                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
8807                         ) => { {
8808                                 let mut max_in_flight_update_id = 0;
8809                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
8810                                 for update in $chan_in_flight_upds.iter() {
8811                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
8812                                                 update.update_id, $channel_info_log, log_bytes!($funding_txo.to_channel_id()));
8813                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
8814                                         pending_background_events.push(
8815                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
8816                                                         counterparty_node_id: $counterparty_node_id,
8817                                                         funding_txo: $funding_txo,
8818                                                         update: update.clone(),
8819                                                 });
8820                                 }
8821                                 if $chan_in_flight_upds.is_empty() {
8822                                         // We had some updates to apply, but it turns out they had completed before we
8823                                         // were serialized, we just weren't notified of that. Thus, we may have to run
8824                                         // the completion actions for any monitor updates, but otherwise are done.
8825                                         pending_background_events.push(
8826                                                 BackgroundEvent::MonitorUpdatesComplete {
8827                                                         counterparty_node_id: $counterparty_node_id,
8828                                                         channel_id: $funding_txo.to_channel_id(),
8829                                                 });
8830                                 }
8831                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
8832                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
8833                                         return Err(DecodeError::InvalidValue);
8834                                 }
8835                                 max_in_flight_update_id
8836                         } }
8837                 }
8838
8839                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
8840                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
8841                         let peer_state = &mut *peer_state_lock;
8842                         for (_, chan) in peer_state.channel_by_id.iter() {
8843                                 // Channels that were persisted have to be funded, otherwise they should have been
8844                                 // discarded.
8845                                 let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
8846                                 let monitor = args.channel_monitors.get(&funding_txo)
8847                                         .expect("We already checked for monitor presence when loading channels");
8848                                 let mut max_in_flight_update_id = monitor.get_latest_update_id();
8849                                 if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
8850                                         if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
8851                                                 max_in_flight_update_id = cmp::max(max_in_flight_update_id,
8852                                                         handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
8853                                                                 funding_txo, monitor, peer_state, ""));
8854                                         }
8855                                 }
8856                                 if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
8857                                         // If the channel is ahead of the monitor, return InvalidValue:
8858                                         log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
8859                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
8860                                                 log_bytes!(chan.context.channel_id()), monitor.get_latest_update_id(), max_in_flight_update_id);
8861                                         log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
8862                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8863                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8864                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
8865                                         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");
8866                                         return Err(DecodeError::InvalidValue);
8867                                 }
8868                         }
8869                 }
8870
8871                 if let Some(in_flight_upds) = in_flight_monitor_updates {
8872                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
8873                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
8874                                         // Now that we've removed all the in-flight monitor updates for channels that are
8875                                         // still open, we need to replay any monitor updates that are for closed channels,
8876                                         // creating the neccessary peer_state entries as we go.
8877                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
8878                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
8879                                         });
8880                                         let mut peer_state = peer_state_mutex.lock().unwrap();
8881                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
8882                                                 funding_txo, monitor, peer_state, "closed ");
8883                                 } else {
8884                                         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!");
8885                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
8886                                                 log_bytes!(funding_txo.to_channel_id()));
8887                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8888                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8889                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
8890                                         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");
8891                                         return Err(DecodeError::InvalidValue);
8892                                 }
8893                         }
8894                 }
8895
8896                 // Note that we have to do the above replays before we push new monitor updates.
8897                 pending_background_events.append(&mut close_background_events);
8898
8899                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
8900                 // should ensure we try them again on the inbound edge. We put them here and do so after we
8901                 // have a fully-constructed `ChannelManager` at the end.
8902                 let mut pending_claims_to_replay = Vec::new();
8903
8904                 {
8905                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
8906                         // ChannelMonitor data for any channels for which we do not have authorative state
8907                         // (i.e. those for which we just force-closed above or we otherwise don't have a
8908                         // corresponding `Channel` at all).
8909                         // This avoids several edge-cases where we would otherwise "forget" about pending
8910                         // payments which are still in-flight via their on-chain state.
8911                         // We only rebuild the pending payments map if we were most recently serialized by
8912                         // 0.0.102+
8913                         for (_, monitor) in args.channel_monitors.iter() {
8914                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
8915                                 if counterparty_opt.is_none() {
8916                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
8917                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
8918                                                         if path.hops.is_empty() {
8919                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
8920                                                                 return Err(DecodeError::InvalidValue);
8921                                                         }
8922
8923                                                         let path_amt = path.final_value_msat();
8924                                                         let mut session_priv_bytes = [0; 32];
8925                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
8926                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
8927                                                                 hash_map::Entry::Occupied(mut entry) => {
8928                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
8929                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
8930                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), log_bytes!(htlc.payment_hash.0));
8931                                                                 },
8932                                                                 hash_map::Entry::Vacant(entry) => {
8933                                                                         let path_fee = path.fee_msat();
8934                                                                         entry.insert(PendingOutboundPayment::Retryable {
8935                                                                                 retry_strategy: None,
8936                                                                                 attempts: PaymentAttempts::new(),
8937                                                                                 payment_params: None,
8938                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
8939                                                                                 payment_hash: htlc.payment_hash,
8940                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
8941                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
8942                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
8943                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
8944                                                                                 pending_amt_msat: path_amt,
8945                                                                                 pending_fee_msat: Some(path_fee),
8946                                                                                 total_msat: path_amt,
8947                                                                                 starting_block_height: best_block_height,
8948                                                                         });
8949                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
8950                                                                                 path_amt, log_bytes!(htlc.payment_hash.0),  log_bytes!(session_priv_bytes));
8951                                                                 }
8952                                                         }
8953                                                 }
8954                                         }
8955                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
8956                                                 match htlc_source {
8957                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
8958                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
8959                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
8960                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
8961                                                                 };
8962                                                                 // The ChannelMonitor is now responsible for this HTLC's
8963                                                                 // failure/success and will let us know what its outcome is. If we
8964                                                                 // still have an entry for this HTLC in `forward_htlcs` or
8965                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
8966                                                                 // the monitor was when forwarding the payment.
8967                                                                 forward_htlcs.retain(|_, forwards| {
8968                                                                         forwards.retain(|forward| {
8969                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
8970                                                                                         if pending_forward_matches_htlc(&htlc_info) {
8971                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
8972                                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
8973                                                                                                 false
8974                                                                                         } else { true }
8975                                                                                 } else { true }
8976                                                                         });
8977                                                                         !forwards.is_empty()
8978                                                                 });
8979                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
8980                                                                         if pending_forward_matches_htlc(&htlc_info) {
8981                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
8982                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
8983                                                                                 pending_events_read.retain(|(event, _)| {
8984                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
8985                                                                                                 intercepted_id != ev_id
8986                                                                                         } else { true }
8987                                                                                 });
8988                                                                                 false
8989                                                                         } else { true }
8990                                                                 });
8991                                                         },
8992                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
8993                                                                 if let Some(preimage) = preimage_opt {
8994                                                                         let pending_events = Mutex::new(pending_events_read);
8995                                                                         // Note that we set `from_onchain` to "false" here,
8996                                                                         // deliberately keeping the pending payment around forever.
8997                                                                         // Given it should only occur when we have a channel we're
8998                                                                         // force-closing for being stale that's okay.
8999                                                                         // The alternative would be to wipe the state when claiming,
9000                                                                         // generating a `PaymentPathSuccessful` event but regenerating
9001                                                                         // it and the `PaymentSent` on every restart until the
9002                                                                         // `ChannelMonitor` is removed.
9003                                                                         let compl_action =
9004                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
9005                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
9006                                                                                         counterparty_node_id: path.hops[0].pubkey,
9007                                                                                 };
9008                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
9009                                                                                 path, false, compl_action, &pending_events, &args.logger);
9010                                                                         pending_events_read = pending_events.into_inner().unwrap();
9011                                                                 }
9012                                                         },
9013                                                 }
9014                                         }
9015                                 }
9016
9017                                 // Whether the downstream channel was closed or not, try to re-apply any payment
9018                                 // preimages from it which may be needed in upstream channels for forwarded
9019                                 // payments.
9020                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
9021                                         .into_iter()
9022                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
9023                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
9024                                                         if let Some(payment_preimage) = preimage_opt {
9025                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
9026                                                                         // Check if `counterparty_opt.is_none()` to see if the
9027                                                                         // downstream chan is closed (because we don't have a
9028                                                                         // channel_id -> peer map entry).
9029                                                                         counterparty_opt.is_none(),
9030                                                                         monitor.get_funding_txo().0))
9031                                                         } else { None }
9032                                                 } else {
9033                                                         // If it was an outbound payment, we've handled it above - if a preimage
9034                                                         // came in and we persisted the `ChannelManager` we either handled it and
9035                                                         // are good to go or the channel force-closed - we don't have to handle the
9036                                                         // channel still live case here.
9037                                                         None
9038                                                 }
9039                                         });
9040                                 for tuple in outbound_claimed_htlcs_iter {
9041                                         pending_claims_to_replay.push(tuple);
9042                                 }
9043                         }
9044                 }
9045
9046                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
9047                         // If we have pending HTLCs to forward, assume we either dropped a
9048                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
9049                         // shut down before the timer hit. Either way, set the time_forwardable to a small
9050                         // constant as enough time has likely passed that we should simply handle the forwards
9051                         // now, or at least after the user gets a chance to reconnect to our peers.
9052                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
9053                                 time_forwardable: Duration::from_secs(2),
9054                         }, None));
9055                 }
9056
9057                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
9058                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
9059
9060                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
9061                 if let Some(purposes) = claimable_htlc_purposes {
9062                         if purposes.len() != claimable_htlcs_list.len() {
9063                                 return Err(DecodeError::InvalidValue);
9064                         }
9065                         if let Some(onion_fields) = claimable_htlc_onion_fields {
9066                                 if onion_fields.len() != claimable_htlcs_list.len() {
9067                                         return Err(DecodeError::InvalidValue);
9068                                 }
9069                                 for (purpose, (onion, (payment_hash, htlcs))) in
9070                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
9071                                 {
9072                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
9073                                                 purpose, htlcs, onion_fields: onion,
9074                                         });
9075                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
9076                                 }
9077                         } else {
9078                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
9079                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
9080                                                 purpose, htlcs, onion_fields: None,
9081                                         });
9082                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
9083                                 }
9084                         }
9085                 } else {
9086                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
9087                         // include a `_legacy_hop_data` in the `OnionPayload`.
9088                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
9089                                 if htlcs.is_empty() {
9090                                         return Err(DecodeError::InvalidValue);
9091                                 }
9092                                 let purpose = match &htlcs[0].onion_payload {
9093                                         OnionPayload::Invoice { _legacy_hop_data } => {
9094                                                 if let Some(hop_data) = _legacy_hop_data {
9095                                                         events::PaymentPurpose::InvoicePayment {
9096                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
9097                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
9098                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
9099                                                                                 Ok((payment_preimage, _)) => payment_preimage,
9100                                                                                 Err(()) => {
9101                                                                                         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", log_bytes!(payment_hash.0));
9102                                                                                         return Err(DecodeError::InvalidValue);
9103                                                                                 }
9104                                                                         }
9105                                                                 },
9106                                                                 payment_secret: hop_data.payment_secret,
9107                                                         }
9108                                                 } else { return Err(DecodeError::InvalidValue); }
9109                                         },
9110                                         OnionPayload::Spontaneous(payment_preimage) =>
9111                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
9112                                 };
9113                                 claimable_payments.insert(payment_hash, ClaimablePayment {
9114                                         purpose, htlcs, onion_fields: None,
9115                                 });
9116                         }
9117                 }
9118
9119                 let mut secp_ctx = Secp256k1::new();
9120                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
9121
9122                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
9123                         Ok(key) => key,
9124                         Err(()) => return Err(DecodeError::InvalidValue)
9125                 };
9126                 if let Some(network_pubkey) = received_network_pubkey {
9127                         if network_pubkey != our_network_pubkey {
9128                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
9129                                 return Err(DecodeError::InvalidValue);
9130                         }
9131                 }
9132
9133                 let mut outbound_scid_aliases = HashSet::new();
9134                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
9135                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9136                         let peer_state = &mut *peer_state_lock;
9137                         for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
9138                                 if chan.context.outbound_scid_alias() == 0 {
9139                                         let mut outbound_scid_alias;
9140                                         loop {
9141                                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias
9142                                                         .get_fake_scid(best_block_height, &genesis_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
9143                                                 if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
9144                                         }
9145                                         chan.context.set_outbound_scid_alias(outbound_scid_alias);
9146                                 } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
9147                                         // Note that in rare cases its possible to hit this while reading an older
9148                                         // channel if we just happened to pick a colliding outbound alias above.
9149                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
9150                                         return Err(DecodeError::InvalidValue);
9151                                 }
9152                                 if chan.context.is_usable() {
9153                                         if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
9154                                                 // Note that in rare cases its possible to hit this while reading an older
9155                                                 // channel if we just happened to pick a colliding outbound alias above.
9156                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
9157                                                 return Err(DecodeError::InvalidValue);
9158                                         }
9159                                 }
9160                         }
9161                 }
9162
9163                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
9164
9165                 for (_, monitor) in args.channel_monitors.iter() {
9166                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
9167                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
9168                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", log_bytes!(payment_hash.0));
9169                                         let mut claimable_amt_msat = 0;
9170                                         let mut receiver_node_id = Some(our_network_pubkey);
9171                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
9172                                         if phantom_shared_secret.is_some() {
9173                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
9174                                                         .expect("Failed to get node_id for phantom node recipient");
9175                                                 receiver_node_id = Some(phantom_pubkey)
9176                                         }
9177                                         for claimable_htlc in payment.htlcs {
9178                                                 claimable_amt_msat += claimable_htlc.value;
9179
9180                                                 // Add a holding-cell claim of the payment to the Channel, which should be
9181                                                 // applied ~immediately on peer reconnection. Because it won't generate a
9182                                                 // new commitment transaction we can just provide the payment preimage to
9183                                                 // the corresponding ChannelMonitor and nothing else.
9184                                                 //
9185                                                 // We do so directly instead of via the normal ChannelMonitor update
9186                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
9187                                                 // we're not allowed to call it directly yet. Further, we do the update
9188                                                 // without incrementing the ChannelMonitor update ID as there isn't any
9189                                                 // reason to.
9190                                                 // If we were to generate a new ChannelMonitor update ID here and then
9191                                                 // crash before the user finishes block connect we'd end up force-closing
9192                                                 // this channel as well. On the flip side, there's no harm in restarting
9193                                                 // without the new monitor persisted - we'll end up right back here on
9194                                                 // restart.
9195                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
9196                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
9197                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
9198                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9199                                                         let peer_state = &mut *peer_state_lock;
9200                                                         if let Some(channel) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
9201                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
9202                                                         }
9203                                                 }
9204                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
9205                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
9206                                                 }
9207                                         }
9208                                         pending_events_read.push_back((events::Event::PaymentClaimed {
9209                                                 receiver_node_id,
9210                                                 payment_hash,
9211                                                 purpose: payment.purpose,
9212                                                 amount_msat: claimable_amt_msat,
9213                                         }, None));
9214                                 }
9215                         }
9216                 }
9217
9218                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
9219                         if let Some(peer_state) = per_peer_state.get(&node_id) {
9220                                 for (_, actions) in monitor_update_blocked_actions.iter() {
9221                                         for action in actions.iter() {
9222                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
9223                                                         downstream_counterparty_and_funding_outpoint:
9224                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
9225                                                 } = action {
9226                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
9227                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
9228                                                                         .entry(blocked_channel_outpoint.to_channel_id())
9229                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
9230                                                         } else {
9231                                                                 // If the channel we were blocking has closed, we don't need to
9232                                                                 // worry about it - the blocked monitor update should never have
9233                                                                 // been released from the `Channel` object so it can't have
9234                                                                 // completed, and if the channel closed there's no reason to bother
9235                                                                 // anymore.
9236                                                         }
9237                                                 }
9238                                         }
9239                                 }
9240                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
9241                         } else {
9242                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
9243                                 return Err(DecodeError::InvalidValue);
9244                         }
9245                 }
9246
9247                 let channel_manager = ChannelManager {
9248                         genesis_hash,
9249                         fee_estimator: bounded_fee_estimator,
9250                         chain_monitor: args.chain_monitor,
9251                         tx_broadcaster: args.tx_broadcaster,
9252                         router: args.router,
9253
9254                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
9255
9256                         inbound_payment_key: expanded_inbound_key,
9257                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
9258                         pending_outbound_payments: pending_outbounds,
9259                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
9260
9261                         forward_htlcs: Mutex::new(forward_htlcs),
9262                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
9263                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
9264                         id_to_peer: Mutex::new(id_to_peer),
9265                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
9266                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
9267
9268                         probing_cookie_secret: probing_cookie_secret.unwrap(),
9269
9270                         our_network_pubkey,
9271                         secp_ctx,
9272
9273                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
9274
9275                         per_peer_state: FairRwLock::new(per_peer_state),
9276
9277                         pending_events: Mutex::new(pending_events_read),
9278                         pending_events_processor: AtomicBool::new(false),
9279                         pending_background_events: Mutex::new(pending_background_events),
9280                         total_consistency_lock: RwLock::new(()),
9281                         background_events_processed_since_startup: AtomicBool::new(false),
9282                         persistence_notifier: Notifier::new(),
9283
9284                         entropy_source: args.entropy_source,
9285                         node_signer: args.node_signer,
9286                         signer_provider: args.signer_provider,
9287
9288                         logger: args.logger,
9289                         default_configuration: args.default_config,
9290                 };
9291
9292                 for htlc_source in failed_htlcs.drain(..) {
9293                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
9294                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
9295                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
9296                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
9297                 }
9298
9299                 for (source, preimage, downstream_value, downstream_closed, downstream_funding) in pending_claims_to_replay {
9300                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
9301                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
9302                         // channel is closed we just assume that it probably came from an on-chain claim.
9303                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
9304                                 downstream_closed, downstream_funding);
9305                 }
9306
9307                 //TODO: Broadcast channel update for closed channels, but only after we've made a
9308                 //connection or two.
9309
9310                 Ok((best_block_hash.clone(), channel_manager))
9311         }
9312 }
9313
9314 #[cfg(test)]
9315 mod tests {
9316         use bitcoin::hashes::Hash;
9317         use bitcoin::hashes::sha256::Hash as Sha256;
9318         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
9319         use core::sync::atomic::Ordering;
9320         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
9321         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
9322         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
9323         use crate::ln::functional_test_utils::*;
9324         use crate::ln::msgs::{self, ErrorAction};
9325         use crate::ln::msgs::ChannelMessageHandler;
9326         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
9327         use crate::util::errors::APIError;
9328         use crate::util::test_utils;
9329         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
9330         use crate::sign::EntropySource;
9331
9332         #[test]
9333         fn test_notify_limits() {
9334                 // Check that a few cases which don't require the persistence of a new ChannelManager,
9335                 // indeed, do not cause the persistence of a new ChannelManager.
9336                 let chanmon_cfgs = create_chanmon_cfgs(3);
9337                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9338                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9339                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9340
9341                 // All nodes start with a persistable update pending as `create_network` connects each node
9342                 // with all other nodes to make most tests simpler.
9343                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
9344                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
9345                 assert!(nodes[2].node.get_persistable_update_future().poll_is_complete());
9346
9347                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9348
9349                 // We check that the channel info nodes have doesn't change too early, even though we try
9350                 // to connect messages with new values
9351                 chan.0.contents.fee_base_msat *= 2;
9352                 chan.1.contents.fee_base_msat *= 2;
9353                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
9354                         &nodes[1].node.get_our_node_id()).pop().unwrap();
9355                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
9356                         &nodes[0].node.get_our_node_id()).pop().unwrap();
9357
9358                 // The first two nodes (which opened a channel) should now require fresh persistence
9359                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
9360                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
9361                 // ... but the last node should not.
9362                 assert!(!nodes[2].node.get_persistable_update_future().poll_is_complete());
9363                 // After persisting the first two nodes they should no longer need fresh persistence.
9364                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
9365                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
9366
9367                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
9368                 // about the channel.
9369                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
9370                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
9371                 assert!(!nodes[2].node.get_persistable_update_future().poll_is_complete());
9372
9373                 // The nodes which are a party to the channel should also ignore messages from unrelated
9374                 // parties.
9375                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
9376                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
9377                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
9378                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
9379                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
9380                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
9381
9382                 // At this point the channel info given by peers should still be the same.
9383                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
9384                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
9385
9386                 // An earlier version of handle_channel_update didn't check the directionality of the
9387                 // update message and would always update the local fee info, even if our peer was
9388                 // (spuriously) forwarding us our own channel_update.
9389                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
9390                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
9391                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
9392
9393                 // First deliver each peers' own message, checking that the node doesn't need to be
9394                 // persisted and that its channel info remains the same.
9395                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
9396                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
9397                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
9398                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
9399                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
9400                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
9401
9402                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
9403                 // the channel info has updated.
9404                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
9405                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
9406                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
9407                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
9408                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
9409                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
9410         }
9411
9412         #[test]
9413         fn test_keysend_dup_hash_partial_mpp() {
9414                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
9415                 // expected.
9416                 let chanmon_cfgs = create_chanmon_cfgs(2);
9417                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9418                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9419                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9420                 create_announced_chan_between_nodes(&nodes, 0, 1);
9421
9422                 // First, send a partial MPP payment.
9423                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
9424                 let mut mpp_route = route.clone();
9425                 mpp_route.paths.push(mpp_route.paths[0].clone());
9426
9427                 let payment_id = PaymentId([42; 32]);
9428                 // Use the utility function send_payment_along_path to send the payment with MPP data which
9429                 // indicates there are more HTLCs coming.
9430                 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.
9431                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9432                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
9433                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
9434                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9435                 check_added_monitors!(nodes[0], 1);
9436                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9437                 assert_eq!(events.len(), 1);
9438                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9439
9440                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
9441                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9442                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9443                 check_added_monitors!(nodes[0], 1);
9444                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9445                 assert_eq!(events.len(), 1);
9446                 let ev = events.drain(..).next().unwrap();
9447                 let payment_event = SendEvent::from_event(ev);
9448                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9449                 check_added_monitors!(nodes[1], 0);
9450                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9451                 expect_pending_htlcs_forwardable!(nodes[1]);
9452                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9453                 check_added_monitors!(nodes[1], 1);
9454                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9455                 assert!(updates.update_add_htlcs.is_empty());
9456                 assert!(updates.update_fulfill_htlcs.is_empty());
9457                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9458                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9459                 assert!(updates.update_fee.is_none());
9460                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9461                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9462                 expect_payment_failed!(nodes[0], our_payment_hash, true);
9463
9464                 // Send the second half of the original MPP payment.
9465                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
9466                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9467                 check_added_monitors!(nodes[0], 1);
9468                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9469                 assert_eq!(events.len(), 1);
9470                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
9471
9472                 // Claim the full MPP payment. Note that we can't use a test utility like
9473                 // claim_funds_along_route because the ordering of the messages causes the second half of the
9474                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
9475                 // lightning messages manually.
9476                 nodes[1].node.claim_funds(payment_preimage);
9477                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
9478                 check_added_monitors!(nodes[1], 2);
9479
9480                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9481                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
9482                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
9483                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
9484                 check_added_monitors!(nodes[0], 1);
9485                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9486                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
9487                 check_added_monitors!(nodes[1], 1);
9488                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9489                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
9490                 check_added_monitors!(nodes[1], 1);
9491                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
9492                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
9493                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
9494                 check_added_monitors!(nodes[0], 1);
9495                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9496                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
9497                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9498                 check_added_monitors!(nodes[0], 1);
9499                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
9500                 check_added_monitors!(nodes[1], 1);
9501                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
9502                 check_added_monitors!(nodes[1], 1);
9503                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
9504                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
9505                 check_added_monitors!(nodes[0], 1);
9506
9507                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
9508                 // path's success and a PaymentPathSuccessful event for each path's success.
9509                 let events = nodes[0].node.get_and_clear_pending_events();
9510                 assert_eq!(events.len(), 2);
9511                 match events[0] {
9512                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
9513                                 assert_eq!(payment_id, *actual_payment_id);
9514                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
9515                                 assert_eq!(route.paths[0], *path);
9516                         },
9517                         _ => panic!("Unexpected event"),
9518                 }
9519                 match events[1] {
9520                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
9521                                 assert_eq!(payment_id, *actual_payment_id);
9522                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
9523                                 assert_eq!(route.paths[0], *path);
9524                         },
9525                         _ => panic!("Unexpected event"),
9526                 }
9527         }
9528
9529         #[test]
9530         fn test_keysend_dup_payment_hash() {
9531                 do_test_keysend_dup_payment_hash(false);
9532                 do_test_keysend_dup_payment_hash(true);
9533         }
9534
9535         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
9536                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
9537                 //      outbound regular payment fails as expected.
9538                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
9539                 //      fails as expected.
9540                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
9541                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
9542                 //      reject MPP keysend payments, since in this case where the payment has no payment
9543                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
9544                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
9545                 //      payment secrets and reject otherwise.
9546                 let chanmon_cfgs = create_chanmon_cfgs(2);
9547                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9548                 let mut mpp_keysend_cfg = test_default_channel_config();
9549                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
9550                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
9551                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9552                 create_announced_chan_between_nodes(&nodes, 0, 1);
9553                 let scorer = test_utils::TestScorer::new();
9554                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9555
9556                 // To start (1), send a regular payment but don't claim it.
9557                 let expected_route = [&nodes[1]];
9558                 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &expected_route, 100_000);
9559
9560                 // Next, attempt a keysend payment and make sure it fails.
9561                 let route_params = RouteParameters {
9562                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
9563                         final_value_msat: 100_000,
9564                 };
9565                 let route = find_route(
9566                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9567                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9568                 ).unwrap();
9569                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9570                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9571                 check_added_monitors!(nodes[0], 1);
9572                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9573                 assert_eq!(events.len(), 1);
9574                 let ev = events.drain(..).next().unwrap();
9575                 let payment_event = SendEvent::from_event(ev);
9576                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9577                 check_added_monitors!(nodes[1], 0);
9578                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9579                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
9580                 // fails), the second will process the resulting failure and fail the HTLC backward
9581                 expect_pending_htlcs_forwardable!(nodes[1]);
9582                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9583                 check_added_monitors!(nodes[1], 1);
9584                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9585                 assert!(updates.update_add_htlcs.is_empty());
9586                 assert!(updates.update_fulfill_htlcs.is_empty());
9587                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9588                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9589                 assert!(updates.update_fee.is_none());
9590                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9591                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9592                 expect_payment_failed!(nodes[0], payment_hash, true);
9593
9594                 // Finally, claim the original payment.
9595                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9596
9597                 // To start (2), send a keysend payment but don't claim it.
9598                 let payment_preimage = PaymentPreimage([42; 32]);
9599                 let route = find_route(
9600                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9601                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9602                 ).unwrap();
9603                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9604                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9605                 check_added_monitors!(nodes[0], 1);
9606                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9607                 assert_eq!(events.len(), 1);
9608                 let event = events.pop().unwrap();
9609                 let path = vec![&nodes[1]];
9610                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
9611
9612                 // Next, attempt a regular payment and make sure it fails.
9613                 let payment_secret = PaymentSecret([43; 32]);
9614                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9615                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9616                 check_added_monitors!(nodes[0], 1);
9617                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9618                 assert_eq!(events.len(), 1);
9619                 let ev = events.drain(..).next().unwrap();
9620                 let payment_event = SendEvent::from_event(ev);
9621                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9622                 check_added_monitors!(nodes[1], 0);
9623                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9624                 expect_pending_htlcs_forwardable!(nodes[1]);
9625                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9626                 check_added_monitors!(nodes[1], 1);
9627                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9628                 assert!(updates.update_add_htlcs.is_empty());
9629                 assert!(updates.update_fulfill_htlcs.is_empty());
9630                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9631                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9632                 assert!(updates.update_fee.is_none());
9633                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9634                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9635                 expect_payment_failed!(nodes[0], payment_hash, true);
9636
9637                 // Finally, succeed the keysend payment.
9638                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9639
9640                 // To start (3), send a keysend payment but don't claim it.
9641                 let payment_id_1 = PaymentId([44; 32]);
9642                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9643                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
9644                 check_added_monitors!(nodes[0], 1);
9645                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9646                 assert_eq!(events.len(), 1);
9647                 let event = events.pop().unwrap();
9648                 let path = vec![&nodes[1]];
9649                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
9650
9651                 // Next, attempt a keysend payment and make sure it fails.
9652                 let route_params = RouteParameters {
9653                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
9654                         final_value_msat: 100_000,
9655                 };
9656                 let route = find_route(
9657                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9658                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9659                 ).unwrap();
9660                 let payment_id_2 = PaymentId([45; 32]);
9661                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9662                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
9663                 check_added_monitors!(nodes[0], 1);
9664                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9665                 assert_eq!(events.len(), 1);
9666                 let ev = events.drain(..).next().unwrap();
9667                 let payment_event = SendEvent::from_event(ev);
9668                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9669                 check_added_monitors!(nodes[1], 0);
9670                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9671                 expect_pending_htlcs_forwardable!(nodes[1]);
9672                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9673                 check_added_monitors!(nodes[1], 1);
9674                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9675                 assert!(updates.update_add_htlcs.is_empty());
9676                 assert!(updates.update_fulfill_htlcs.is_empty());
9677                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9678                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9679                 assert!(updates.update_fee.is_none());
9680                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9681                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9682                 expect_payment_failed!(nodes[0], payment_hash, true);
9683
9684                 // Finally, claim the original payment.
9685                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9686         }
9687
9688         #[test]
9689         fn test_keysend_hash_mismatch() {
9690                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
9691                 // preimage doesn't match the msg's payment hash.
9692                 let chanmon_cfgs = create_chanmon_cfgs(2);
9693                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9694                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9695                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9696
9697                 let payer_pubkey = nodes[0].node.get_our_node_id();
9698                 let payee_pubkey = nodes[1].node.get_our_node_id();
9699
9700                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9701                 let route_params = RouteParameters {
9702                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9703                         final_value_msat: 10_000,
9704                 };
9705                 let network_graph = nodes[0].network_graph.clone();
9706                 let first_hops = nodes[0].node.list_usable_channels();
9707                 let scorer = test_utils::TestScorer::new();
9708                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9709                 let route = find_route(
9710                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9711                         nodes[0].logger, &scorer, &(), &random_seed_bytes
9712                 ).unwrap();
9713
9714                 let test_preimage = PaymentPreimage([42; 32]);
9715                 let mismatch_payment_hash = PaymentHash([43; 32]);
9716                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
9717                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
9718                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
9719                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
9720                 check_added_monitors!(nodes[0], 1);
9721
9722                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9723                 assert_eq!(updates.update_add_htlcs.len(), 1);
9724                 assert!(updates.update_fulfill_htlcs.is_empty());
9725                 assert!(updates.update_fail_htlcs.is_empty());
9726                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9727                 assert!(updates.update_fee.is_none());
9728                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
9729
9730                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
9731         }
9732
9733         #[test]
9734         fn test_keysend_msg_with_secret_err() {
9735                 // Test that we error as expected if we receive a keysend payment that includes a payment
9736                 // secret when we don't support MPP keysend.
9737                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
9738                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
9739                 let chanmon_cfgs = create_chanmon_cfgs(2);
9740                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9741                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
9742                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9743
9744                 let payer_pubkey = nodes[0].node.get_our_node_id();
9745                 let payee_pubkey = nodes[1].node.get_our_node_id();
9746
9747                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9748                 let route_params = RouteParameters {
9749                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9750                         final_value_msat: 10_000,
9751                 };
9752                 let network_graph = nodes[0].network_graph.clone();
9753                 let first_hops = nodes[0].node.list_usable_channels();
9754                 let scorer = test_utils::TestScorer::new();
9755                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9756                 let route = find_route(
9757                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9758                         nodes[0].logger, &scorer, &(), &random_seed_bytes
9759                 ).unwrap();
9760
9761                 let test_preimage = PaymentPreimage([42; 32]);
9762                 let test_secret = PaymentSecret([43; 32]);
9763                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
9764                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
9765                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
9766                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
9767                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
9768                         PaymentId(payment_hash.0), None, session_privs).unwrap();
9769                 check_added_monitors!(nodes[0], 1);
9770
9771                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9772                 assert_eq!(updates.update_add_htlcs.len(), 1);
9773                 assert!(updates.update_fulfill_htlcs.is_empty());
9774                 assert!(updates.update_fail_htlcs.is_empty());
9775                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9776                 assert!(updates.update_fee.is_none());
9777                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
9778
9779                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
9780         }
9781
9782         #[test]
9783         fn test_multi_hop_missing_secret() {
9784                 let chanmon_cfgs = create_chanmon_cfgs(4);
9785                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9786                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9787                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9788
9789                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
9790                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
9791                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
9792                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
9793
9794                 // Marshall an MPP route.
9795                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
9796                 let path = route.paths[0].clone();
9797                 route.paths.push(path);
9798                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
9799                 route.paths[0].hops[0].short_channel_id = chan_1_id;
9800                 route.paths[0].hops[1].short_channel_id = chan_3_id;
9801                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
9802                 route.paths[1].hops[0].short_channel_id = chan_2_id;
9803                 route.paths[1].hops[1].short_channel_id = chan_4_id;
9804
9805                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
9806                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
9807                 .unwrap_err() {
9808                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
9809                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
9810                         },
9811                         _ => panic!("unexpected error")
9812                 }
9813         }
9814
9815         #[test]
9816         fn test_drop_disconnected_peers_when_removing_channels() {
9817                 let chanmon_cfgs = create_chanmon_cfgs(2);
9818                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9819                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9820                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9821
9822                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9823
9824                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9825                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9826
9827                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
9828                 check_closed_broadcast!(nodes[0], true);
9829                 check_added_monitors!(nodes[0], 1);
9830                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
9831
9832                 {
9833                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
9834                         // disconnected and the channel between has been force closed.
9835                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9836                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
9837                         assert_eq!(nodes_0_per_peer_state.len(), 1);
9838                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
9839                 }
9840
9841                 nodes[0].node.timer_tick_occurred();
9842
9843                 {
9844                         // Assert that nodes[1] has now been removed.
9845                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
9846                 }
9847         }
9848
9849         #[test]
9850         fn bad_inbound_payment_hash() {
9851                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
9852                 let chanmon_cfgs = create_chanmon_cfgs(2);
9853                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9854                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9855                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9856
9857                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
9858                 let payment_data = msgs::FinalOnionHopData {
9859                         payment_secret,
9860                         total_msat: 100_000,
9861                 };
9862
9863                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
9864                 // payment verification fails as expected.
9865                 let mut bad_payment_hash = payment_hash.clone();
9866                 bad_payment_hash.0[0] += 1;
9867                 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) {
9868                         Ok(_) => panic!("Unexpected ok"),
9869                         Err(()) => {
9870                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
9871                         }
9872                 }
9873
9874                 // Check that using the original payment hash succeeds.
9875                 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());
9876         }
9877
9878         #[test]
9879         fn test_id_to_peer_coverage() {
9880                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
9881                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
9882                 // the channel is successfully closed.
9883                 let chanmon_cfgs = create_chanmon_cfgs(2);
9884                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9885                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9886                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9887
9888                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9889                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9890                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9891                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9892                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9893
9894                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9895                 let channel_id = &tx.txid().into_inner();
9896                 {
9897                         // Ensure that the `id_to_peer` map is empty until either party has received the
9898                         // funding transaction, and have the real `channel_id`.
9899                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
9900                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9901                 }
9902
9903                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9904                 {
9905                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
9906                         // as it has the funding transaction.
9907                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9908                         assert_eq!(nodes_0_lock.len(), 1);
9909                         assert!(nodes_0_lock.contains_key(channel_id));
9910                 }
9911
9912                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9913
9914                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9915
9916                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9917                 {
9918                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9919                         assert_eq!(nodes_0_lock.len(), 1);
9920                         assert!(nodes_0_lock.contains_key(channel_id));
9921                 }
9922                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9923
9924                 {
9925                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
9926                         // as it has the funding transaction.
9927                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9928                         assert_eq!(nodes_1_lock.len(), 1);
9929                         assert!(nodes_1_lock.contains_key(channel_id));
9930                 }
9931                 check_added_monitors!(nodes[1], 1);
9932                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9933                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9934                 check_added_monitors!(nodes[0], 1);
9935                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9936                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9937                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9938                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
9939
9940                 nodes[0].node.close_channel(channel_id, &nodes[1].node.get_our_node_id()).unwrap();
9941                 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()));
9942                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
9943                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
9944
9945                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
9946                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
9947                 {
9948                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
9949                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
9950                         // fee for the closing transaction has been negotiated and the parties has the other
9951                         // party's signature for the fee negotiated closing transaction.)
9952                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9953                         assert_eq!(nodes_0_lock.len(), 1);
9954                         assert!(nodes_0_lock.contains_key(channel_id));
9955                 }
9956
9957                 {
9958                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
9959                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
9960                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
9961                         // kept in the `nodes[1]`'s `id_to_peer` map.
9962                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9963                         assert_eq!(nodes_1_lock.len(), 1);
9964                         assert!(nodes_1_lock.contains_key(channel_id));
9965                 }
9966
9967                 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()));
9968                 {
9969                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
9970                         // therefore has all it needs to fully close the channel (both signatures for the
9971                         // closing transaction).
9972                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
9973                         // fully closed by `nodes[0]`.
9974                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
9975
9976                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
9977                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
9978                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9979                         assert_eq!(nodes_1_lock.len(), 1);
9980                         assert!(nodes_1_lock.contains_key(channel_id));
9981                 }
9982
9983                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
9984
9985                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
9986                 {
9987                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
9988                         // they both have everything required to fully close the channel.
9989                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9990                 }
9991                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
9992
9993                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
9994                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
9995         }
9996
9997         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
9998                 let expected_message = format!("Not connected to node: {}", expected_public_key);
9999                 check_api_error_message(expected_message, res_err)
10000         }
10001
10002         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
10003                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
10004                 check_api_error_message(expected_message, res_err)
10005         }
10006
10007         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
10008                 match res_err {
10009                         Err(APIError::APIMisuseError { err }) => {
10010                                 assert_eq!(err, expected_err_message);
10011                         },
10012                         Err(APIError::ChannelUnavailable { err }) => {
10013                                 assert_eq!(err, expected_err_message);
10014                         },
10015                         Ok(_) => panic!("Unexpected Ok"),
10016                         Err(_) => panic!("Unexpected Error"),
10017                 }
10018         }
10019
10020         #[test]
10021         fn test_api_calls_with_unkown_counterparty_node() {
10022                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
10023                 // expected if the `counterparty_node_id` is an unkown peer in the
10024                 // `ChannelManager::per_peer_state` map.
10025                 let chanmon_cfg = create_chanmon_cfgs(2);
10026                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
10027                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
10028                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
10029
10030                 // Dummy values
10031                 let channel_id = [4; 32];
10032                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
10033                 let intercept_id = InterceptId([0; 32]);
10034
10035                 // Test the API functions.
10036                 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);
10037
10038                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
10039
10040                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
10041
10042                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
10043
10044                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
10045
10046                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
10047
10048                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
10049         }
10050
10051         #[test]
10052         fn test_connection_limiting() {
10053                 // Test that we limit un-channel'd peers and un-funded channels properly.
10054                 let chanmon_cfgs = create_chanmon_cfgs(2);
10055                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10056                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10057                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10058
10059                 // Note that create_network connects the nodes together for us
10060
10061                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10062                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10063
10064                 let mut funding_tx = None;
10065                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
10066                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10067                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10068
10069                         if idx == 0 {
10070                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
10071                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
10072                                 funding_tx = Some(tx.clone());
10073                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
10074                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10075
10076                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
10077                                 check_added_monitors!(nodes[1], 1);
10078                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10079
10080                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10081
10082                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
10083                                 check_added_monitors!(nodes[0], 1);
10084                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
10085                         }
10086                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10087                 }
10088
10089                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
10090                 open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10091                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10092                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
10093                         open_channel_msg.temporary_channel_id);
10094
10095                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
10096                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
10097                 // limit.
10098                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
10099                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
10100                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
10101                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
10102                         peer_pks.push(random_pk);
10103                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
10104                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10105                         }, true).unwrap();
10106                 }
10107                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
10108                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
10109                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
10110                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10111                 }, true).unwrap_err();
10112
10113                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
10114                 // them if we have too many un-channel'd peers.
10115                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10116                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
10117                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
10118                 for ev in chan_closed_events {
10119                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
10120                 }
10121                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
10122                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10123                 }, true).unwrap();
10124                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10125                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10126                 }, true).unwrap_err();
10127
10128                 // but of course if the connection is outbound its allowed...
10129                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10130                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10131                 }, false).unwrap();
10132                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10133
10134                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
10135                 // Even though we accept one more connection from new peers, we won't actually let them
10136                 // open channels.
10137                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
10138                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
10139                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
10140                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
10141                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10142                 }
10143                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10144                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
10145                         open_channel_msg.temporary_channel_id);
10146
10147                 // Of course, however, outbound channels are always allowed
10148                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
10149                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
10150
10151                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
10152                 // "protected" and can connect again.
10153                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
10154                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10155                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10156                 }, true).unwrap();
10157                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
10158
10159                 // Further, because the first channel was funded, we can open another channel with
10160                 // last_random_pk.
10161                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10162                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
10163         }
10164
10165         #[test]
10166         fn test_outbound_chans_unlimited() {
10167                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
10168                 let chanmon_cfgs = create_chanmon_cfgs(2);
10169                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10170                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10171                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10172
10173                 // Note that create_network connects the nodes together for us
10174
10175                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10176                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10177
10178                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
10179                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10180                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10181                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10182                 }
10183
10184                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
10185                 // rejected.
10186                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10187                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
10188                         open_channel_msg.temporary_channel_id);
10189
10190                 // but we can still open an outbound channel.
10191                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10192                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
10193
10194                 // but even with such an outbound channel, additional inbound channels will still fail.
10195                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10196                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
10197                         open_channel_msg.temporary_channel_id);
10198         }
10199
10200         #[test]
10201         fn test_0conf_limiting() {
10202                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
10203                 // flag set and (sometimes) accept channels as 0conf.
10204                 let chanmon_cfgs = create_chanmon_cfgs(2);
10205                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10206                 let mut settings = test_default_channel_config();
10207                 settings.manually_accept_inbound_channels = true;
10208                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
10209                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10210
10211                 // Note that create_network connects the nodes together for us
10212
10213                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10214                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10215
10216                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
10217                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
10218                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
10219                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
10220                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
10221                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10222                         }, true).unwrap();
10223
10224                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
10225                         let events = nodes[1].node.get_and_clear_pending_events();
10226                         match events[0] {
10227                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
10228                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
10229                                 }
10230                                 _ => panic!("Unexpected event"),
10231                         }
10232                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
10233                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10234                 }
10235
10236                 // If we try to accept a channel from another peer non-0conf it will fail.
10237                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
10238                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
10239                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
10240                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10241                 }, true).unwrap();
10242                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10243                 let events = nodes[1].node.get_and_clear_pending_events();
10244                 match events[0] {
10245                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
10246                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
10247                                         Err(APIError::APIMisuseError { err }) =>
10248                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
10249                                         _ => panic!(),
10250                                 }
10251                         }
10252                         _ => panic!("Unexpected event"),
10253                 }
10254                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
10255                         open_channel_msg.temporary_channel_id);
10256
10257                 // ...however if we accept the same channel 0conf it should work just fine.
10258                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10259                 let events = nodes[1].node.get_and_clear_pending_events();
10260                 match events[0] {
10261                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
10262                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
10263                         }
10264                         _ => panic!("Unexpected event"),
10265                 }
10266                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
10267         }
10268
10269         #[test]
10270         fn reject_excessively_underpaying_htlcs() {
10271                 let chanmon_cfg = create_chanmon_cfgs(1);
10272                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
10273                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
10274                 let node = create_network(1, &node_cfg, &node_chanmgr);
10275                 let sender_intended_amt_msat = 100;
10276                 let extra_fee_msat = 10;
10277                 let hop_data = msgs::InboundOnionPayload::Receive {
10278                         amt_msat: 100,
10279                         outgoing_cltv_value: 42,
10280                         payment_metadata: None,
10281                         keysend_preimage: None,
10282                         payment_data: Some(msgs::FinalOnionHopData {
10283                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
10284                         }),
10285                         custom_tlvs: Vec::new(),
10286                 };
10287                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
10288                 // intended amount, we fail the payment.
10289                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
10290                         node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
10291                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat))
10292                 {
10293                         assert_eq!(err_code, 19);
10294                 } else { panic!(); }
10295
10296                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
10297                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
10298                         amt_msat: 100,
10299                         outgoing_cltv_value: 42,
10300                         payment_metadata: None,
10301                         keysend_preimage: None,
10302                         payment_data: Some(msgs::FinalOnionHopData {
10303                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
10304                         }),
10305                         custom_tlvs: Vec::new(),
10306                 };
10307                 assert!(node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
10308                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat)).is_ok());
10309         }
10310
10311         #[test]
10312         fn test_inbound_anchors_manual_acceptance() {
10313                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
10314                 // flag set and (sometimes) accept channels as 0conf.
10315                 let mut anchors_cfg = test_default_channel_config();
10316                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
10317
10318                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
10319                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
10320
10321                 let chanmon_cfgs = create_chanmon_cfgs(3);
10322                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10323                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
10324                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
10325                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10326
10327                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10328                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10329
10330                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10331                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
10332                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10333                 match &msg_events[0] {
10334                         MessageSendEvent::HandleError { node_id, action } => {
10335                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10336                                 match action {
10337                                         ErrorAction::SendErrorMessage { msg } =>
10338                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
10339                                         _ => panic!("Unexpected error action"),
10340                                 }
10341                         }
10342                         _ => panic!("Unexpected event"),
10343                 }
10344
10345                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10346                 let events = nodes[2].node.get_and_clear_pending_events();
10347                 match events[0] {
10348                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
10349                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
10350                         _ => panic!("Unexpected event"),
10351                 }
10352                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10353         }
10354
10355         #[test]
10356         fn test_anchors_zero_fee_htlc_tx_fallback() {
10357                 // Tests that if both nodes support anchors, but the remote node does not want to accept
10358                 // anchor channels at the moment, an error it sent to the local node such that it can retry
10359                 // the channel without the anchors feature.
10360                 let chanmon_cfgs = create_chanmon_cfgs(2);
10361                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10362                 let mut anchors_config = test_default_channel_config();
10363                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
10364                 anchors_config.manually_accept_inbound_channels = true;
10365                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
10366                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10367
10368                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
10369                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10370                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
10371
10372                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10373                 let events = nodes[1].node.get_and_clear_pending_events();
10374                 match events[0] {
10375                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
10376                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
10377                         }
10378                         _ => panic!("Unexpected event"),
10379                 }
10380
10381                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
10382                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
10383
10384                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10385                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
10386
10387                 // Since nodes[1] should not have accepted the channel, it should
10388                 // not have generated any events.
10389                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
10390         }
10391
10392         #[test]
10393         fn test_update_channel_config() {
10394                 let chanmon_cfg = create_chanmon_cfgs(2);
10395                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
10396                 let mut user_config = test_default_channel_config();
10397                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
10398                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
10399                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
10400                 let channel = &nodes[0].node.list_channels()[0];
10401
10402                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
10403                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10404                 assert_eq!(events.len(), 0);
10405
10406                 user_config.channel_config.forwarding_fee_base_msat += 10;
10407                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
10408                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
10409                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10410                 assert_eq!(events.len(), 1);
10411                 match &events[0] {
10412                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10413                         _ => panic!("expected BroadcastChannelUpdate event"),
10414                 }
10415
10416                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
10417                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10418                 assert_eq!(events.len(), 0);
10419
10420                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
10421                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
10422                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
10423                         ..Default::default()
10424                 }).unwrap();
10425                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
10426                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10427                 assert_eq!(events.len(), 1);
10428                 match &events[0] {
10429                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10430                         _ => panic!("expected BroadcastChannelUpdate event"),
10431                 }
10432
10433                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
10434                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
10435                         forwarding_fee_proportional_millionths: Some(new_fee),
10436                         ..Default::default()
10437                 }).unwrap();
10438                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
10439                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
10440                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10441                 assert_eq!(events.len(), 1);
10442                 match &events[0] {
10443                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10444                         _ => panic!("expected BroadcastChannelUpdate event"),
10445                 }
10446
10447                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
10448                 // should be applied to ensure update atomicity as specified in the API docs.
10449                 let bad_channel_id = [10; 32];
10450                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
10451                 let new_fee = current_fee + 100;
10452                 assert!(
10453                         matches!(
10454                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
10455                                         forwarding_fee_proportional_millionths: Some(new_fee),
10456                                         ..Default::default()
10457                                 }),
10458                                 Err(APIError::ChannelUnavailable { err: _ }),
10459                         )
10460                 );
10461                 // Check that the fee hasn't changed for the channel that exists.
10462                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
10463                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10464                 assert_eq!(events.len(), 0);
10465         }
10466 }
10467
10468 #[cfg(ldk_bench)]
10469 pub mod bench {
10470         use crate::chain::Listen;
10471         use crate::chain::chainmonitor::{ChainMonitor, Persist};
10472         use crate::sign::{KeysManager, InMemorySigner};
10473         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
10474         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
10475         use crate::ln::functional_test_utils::*;
10476         use crate::ln::msgs::{ChannelMessageHandler, Init};
10477         use crate::routing::gossip::NetworkGraph;
10478         use crate::routing::router::{PaymentParameters, RouteParameters};
10479         use crate::util::test_utils;
10480         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
10481
10482         use bitcoin::hashes::Hash;
10483         use bitcoin::hashes::sha256::Hash as Sha256;
10484         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
10485
10486         use crate::sync::{Arc, Mutex};
10487
10488         use criterion::Criterion;
10489
10490         type Manager<'a, P> = ChannelManager<
10491                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
10492                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
10493                         &'a test_utils::TestLogger, &'a P>,
10494                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
10495                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
10496                 &'a test_utils::TestLogger>;
10497
10498         struct ANodeHolder<'a, P: Persist<InMemorySigner>> {
10499                 node: &'a Manager<'a, P>,
10500         }
10501         impl<'a, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'a, P> {
10502                 type CM = Manager<'a, P>;
10503                 #[inline]
10504                 fn node(&self) -> &Manager<'a, P> { self.node }
10505                 #[inline]
10506                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
10507         }
10508
10509         pub fn bench_sends(bench: &mut Criterion) {
10510                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
10511         }
10512
10513         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
10514                 // Do a simple benchmark of sending a payment back and forth between two nodes.
10515                 // Note that this is unrealistic as each payment send will require at least two fsync
10516                 // calls per node.
10517                 let network = bitcoin::Network::Testnet;
10518                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
10519
10520                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
10521                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
10522                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
10523                 let scorer = Mutex::new(test_utils::TestScorer::new());
10524                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
10525
10526                 let mut config: UserConfig = Default::default();
10527                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
10528                 config.channel_handshake_config.minimum_depth = 1;
10529
10530                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
10531                 let seed_a = [1u8; 32];
10532                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
10533                 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 {
10534                         network,
10535                         best_block: BestBlock::from_network(network),
10536                 }, genesis_block.header.time);
10537                 let node_a_holder = ANodeHolder { node: &node_a };
10538
10539                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
10540                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
10541                 let seed_b = [2u8; 32];
10542                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
10543                 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 {
10544                         network,
10545                         best_block: BestBlock::from_network(network),
10546                 }, genesis_block.header.time);
10547                 let node_b_holder = ANodeHolder { node: &node_b };
10548
10549                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
10550                         features: node_b.init_features(), networks: None, remote_network_address: None
10551                 }, true).unwrap();
10552                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
10553                         features: node_a.init_features(), networks: None, remote_network_address: None
10554                 }, false).unwrap();
10555                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
10556                 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()));
10557                 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()));
10558
10559                 let tx;
10560                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
10561                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
10562                                 value: 8_000_000, script_pubkey: output_script,
10563                         }]};
10564                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
10565                 } else { panic!(); }
10566
10567                 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()));
10568                 let events_b = node_b.get_and_clear_pending_events();
10569                 assert_eq!(events_b.len(), 1);
10570                 match events_b[0] {
10571                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
10572                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
10573                         },
10574                         _ => panic!("Unexpected event"),
10575                 }
10576
10577                 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()));
10578                 let events_a = node_a.get_and_clear_pending_events();
10579                 assert_eq!(events_a.len(), 1);
10580                 match events_a[0] {
10581                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
10582                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
10583                         },
10584                         _ => panic!("Unexpected event"),
10585                 }
10586
10587                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
10588
10589                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
10590                 Listen::block_connected(&node_a, &block, 1);
10591                 Listen::block_connected(&node_b, &block, 1);
10592
10593                 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()));
10594                 let msg_events = node_a.get_and_clear_pending_msg_events();
10595                 assert_eq!(msg_events.len(), 2);
10596                 match msg_events[0] {
10597                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
10598                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
10599                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
10600                         },
10601                         _ => panic!(),
10602                 }
10603                 match msg_events[1] {
10604                         MessageSendEvent::SendChannelUpdate { .. } => {},
10605                         _ => panic!(),
10606                 }
10607
10608                 let events_a = node_a.get_and_clear_pending_events();
10609                 assert_eq!(events_a.len(), 1);
10610                 match events_a[0] {
10611                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
10612                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
10613                         },
10614                         _ => panic!("Unexpected event"),
10615                 }
10616
10617                 let events_b = node_b.get_and_clear_pending_events();
10618                 assert_eq!(events_b.len(), 1);
10619                 match events_b[0] {
10620                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
10621                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
10622                         },
10623                         _ => panic!("Unexpected event"),
10624                 }
10625
10626                 let mut payment_count: u64 = 0;
10627                 macro_rules! send_payment {
10628                         ($node_a: expr, $node_b: expr) => {
10629                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
10630                                         .with_bolt11_features($node_b.invoice_features()).unwrap();
10631                                 let mut payment_preimage = PaymentPreimage([0; 32]);
10632                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
10633                                 payment_count += 1;
10634                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
10635                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
10636
10637                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
10638                                         PaymentId(payment_hash.0), RouteParameters {
10639                                                 payment_params, final_value_msat: 10_000,
10640                                         }, Retry::Attempts(0)).unwrap();
10641                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
10642                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
10643                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
10644                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
10645                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
10646                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
10647                                 $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()));
10648
10649                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
10650                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
10651                                 $node_b.claim_funds(payment_preimage);
10652                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
10653
10654                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
10655                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
10656                                                 assert_eq!(node_id, $node_a.get_our_node_id());
10657                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10658                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
10659                                         },
10660                                         _ => panic!("Failed to generate claim event"),
10661                                 }
10662
10663                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
10664                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
10665                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
10666                                 $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()));
10667
10668                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
10669                         }
10670                 }
10671
10672                 bench.bench_function(bench_name, |b| b.iter(|| {
10673                         send_payment!(node_a, node_b);
10674                         send_payment!(node_b, node_a);
10675                 }));
10676         }
10677 }